diff --git a/Code/BasicFilters/otbBSplineDecompositionImageFilter.h b/Code/BasicFilters/otbBSplineDecompositionImageFilter.h index 38684b775e6c1722d3b2405282ac0910aa97ba90..a0a970131fe6a1f58a6813b480a5785338f13c85 100644 --- a/Code/BasicFilters/otbBSplineDecompositionImageFilter.h +++ b/Code/BasicFilters/otbBSplineDecompositionImageFilter.h @@ -36,7 +36,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT BSplineDecompositionImageFilter : - public itk::ImageToImageFilter<TInputImage,TOutputImage> + public itk::ImageToImageFilter<TInputImage,TOutputImage> { public: /** Standard class typedefs. */ diff --git a/Code/BasicFilters/otbBSplineDecompositionImageFilter.txx b/Code/BasicFilters/otbBSplineDecompositionImageFilter.txx index b0c29ae68d36f076049ffded0d72c9ca19b8d564..ce10620fde7c03b7d113e78a3c553b7201dd6243 100644 --- a/Code/BasicFilters/otbBSplineDecompositionImageFilter.txx +++ b/Code/BasicFilters/otbBSplineDecompositionImageFilter.txx @@ -69,42 +69,42 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> double c0 = 1.0; if (m_DataLength[m_IteratorDirection] == 1) //Required by mirror boundaries - { + { return false; - } + } // Compute overall gain for (int k = 0; k < m_NumberOfPoles; k++) - { + { // Note for cubic splines lambda = 6 c0 = c0 * (1.0 - m_SplinePoles[k]) * (1.0 - 1.0 / m_SplinePoles[k]); - } + } // apply the gain for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) - { + { m_Scratch[n] *= c0; - } + } // loop over all poles for (int k = 0; k < m_NumberOfPoles; k++) - { + { // causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); // causal recursion for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) - { + { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; - } + } // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); // anticausal recursion for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) - { + { m_Scratch[n] = m_SplinePoles[k] * (m_Scratch[n + 1] - m_Scratch[n]); - } } + } return true; } @@ -116,9 +116,9 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> ::SetSplineOrder(unsigned int SplineOrder) { if (SplineOrder == m_SplineOrder) - { + { return; - } + } m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); @@ -135,41 +135,41 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, // 2000, pg. 416. switch (m_SplineOrder) - { - case 3: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; - break; - case 0: - m_NumberOfPoles = 0; - break; - case 1: - m_NumberOfPoles = 0; - break; - case 2: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; - break; - case 4: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; - m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; - break; - case 5: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - break; - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; - } + { + case 3: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; + break; + case 0: + m_NumberOfPoles = 0; + break; + case 1: + m_NumberOfPoles = 0; + break; + case 2: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; + break; + case 4: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; + m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; + break; + case 5: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + break; + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -188,33 +188,34 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> horizon = m_DataLength[m_IteratorDirection]; zn = z; if (m_Tolerance > 0.0) - { + { horizon = (long)vcl_ceil(log(m_Tolerance) / vcl_log(fabs(z))); - } + } if (horizon < m_DataLength[m_IteratorDirection]) - { + { /* accelerated loop */ sum = m_Scratch[0]; // verify this for (unsigned int n = 1; n < horizon; n++) - { + { sum += zn * m_Scratch[n]; zn *= z; - } - m_Scratch[0] = sum; } - else { - /* full loop */ - iz = 1.0 / z; - z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); - sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; - z2n *= z2n * iz; - for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) + m_Scratch[0] = sum; + } + else + { + /* full loop */ + iz = 1.0 / z; + z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); + sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; + z2n *= z2n * iz; + for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) { - sum += (zn + z2n) * m_Scratch[n]; - zn *= z; - z2n *= iz; + sum += (zn + z2n) * m_Scratch[n]; + zn *= z; + z2n *= iz; } - m_Scratch[0] = sum / (1.0 - zn * zn); + m_Scratch[0] = sum / (1.0 - zn * zn); } } @@ -250,7 +251,7 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> this->CopyImageToImage(); // Coefficients are initialized to the input data for (unsigned int n=0; n < ImageDimension; n++) - { + { m_IteratorDirection = n; // Loop through each dimension @@ -259,7 +260,7 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> CIterator.SetDirection( m_IteratorDirection ); // For each data vector while ( !CIterator.IsAtEnd() ) - { + { // Copy coefficients to scratch this->CopyCoefficientsToScratch( CIterator ); @@ -273,8 +274,8 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> this->CopyScratchToCoefficients( CIterator ); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); - } } + } } @@ -298,11 +299,11 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> outIt = outIt.Begin(); while ( !outIt.IsAtEnd() ) - { + { outIt.Set( static_cast<OutputPixelType>( inIt.Get() ) ); ++inIt; ++outIt; - } + } } @@ -318,11 +319,11 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> typedef typename TOutputImage::PixelType OutputPixelType; unsigned long j = 0; while ( !Iter.IsAtEndOfLine() ) - { + { Iter.Set( static_cast<OutputPixelType>( m_Scratch[j] ) ); ++Iter; ++j; - } + } } @@ -337,11 +338,11 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> { unsigned long j = 0; while ( !Iter.IsAtEndOfLine() ) - { + { m_Scratch[j] = static_cast<double>( Iter.Get() ); ++Iter; ++j; - } + } } /** @@ -359,12 +360,12 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> unsigned long maxLength = 0; for ( unsigned int n = 0; n < ImageDimension; n++ ) - { + { if ( m_DataLength[n] > maxLength ) - { + { maxLength = m_DataLength[n]; - } } + } m_Scratch.resize( maxLength ); // Allocate memory for output image diff --git a/Code/BasicFilters/otbBSplineInterpolateImageFunction.h b/Code/BasicFilters/otbBSplineInterpolateImageFunction.h index 119d522fbb15921ab6ad3fc4a95ff2eb6e157f5e..6509b97f35858060e6ae364c5e74ba39b749fd64 100644 --- a/Code/BasicFilters/otbBSplineInterpolateImageFunction.h +++ b/Code/BasicFilters/otbBSplineInterpolateImageFunction.h @@ -41,11 +41,11 @@ namespace otb * \ingroup ImageFunctions */ template < - class TImageType, - class TCoordRep = double, - class TCoefficientType = double > +class TImageType, +class TCoordRep = double, +class TCoefficientType = double > class ITK_EXPORT BSplineInterpolateImageFunction : - public itk::InterpolateImageFunction<TImageType,TCoordRep> + public itk::InterpolateImageFunction<TImageType,TCoordRep> { public: /** Standard class typedefs. */ @@ -73,8 +73,8 @@ public: /** Index typedef support. */ typedef typename Superclass::IndexType IndexType; -/** Region typedef support */ -typedef typename InputImageType::RegionType RegionType; + /** Region typedef support */ + typedef typename InputImageType::RegionType RegionType; /** ContinuousIndex typedef support. */ typedef typename Superclass::ContinuousIndexType ContinuousIndexType; @@ -88,8 +88,8 @@ typedef typename InputImageType::RegionType RegionType; /** Internal Coefficient typedef support */ typedef TCoefficientType CoefficientDataType; typedef itk::Image<CoefficientDataType, - itkGetStaticConstMacro(ImageDimension) - > CoefficientImageType; + itkGetStaticConstMacro(ImageDimension) + > CoefficientImageType; /** Define filter for calculating the BSpline coefficients */ typedef otb::BSplineDecompositionImageFilter<TImageType, CoefficientImageType> @@ -109,8 +109,8 @@ typedef typename InputImageType::RegionType RegionType; /** Derivative typedef support */ typedef itk::CovariantVector<OutputType, - itkGetStaticConstMacro(ImageDimension) - > CovariantVectorType; + itkGetStaticConstMacro(ImageDimension) + > CovariantVectorType; CovariantVectorType EvaluateDerivative( const PointType & point ) const { @@ -135,7 +135,7 @@ typedef typename InputImageType::RegionType RegionType; /** Update coefficients filter. Coefficient filter are computed over the buffered region of the input image. */ -virtual void UpdateCoefficientsFilter(void); + virtual void UpdateCoefficientsFilter(void); protected: BSplineInterpolateImageFunction(); diff --git a/Code/BasicFilters/otbBSplineInterpolateImageFunction.txx b/Code/BasicFilters/otbBSplineInterpolateImageFunction.txx index c1ba5b5c0b9dff224b54d7db92f2b418cb946710..963befe2fc174833ee37c17c1b72cdebeacc9b8b 100644 --- a/Code/BasicFilters/otbBSplineInterpolateImageFunction.txx +++ b/Code/BasicFilters/otbBSplineInterpolateImageFunction.txx @@ -64,12 +64,12 @@ void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::UpdateCoefficientsFilter(void) { - m_CoefficientFilter->GetOutput()->UpdateOutputInformation(); - m_CoefficientFilter->GetOutput()->SetRequestedRegion(m_CoefficientFilter->GetInput()->GetBufferedRegion()); - m_CoefficientFilter->GetOutput()->PropagateRequestedRegion(); - m_CoefficientFilter->GetOutput()->UpdateOutputData(); - m_Coefficients = m_CoefficientFilter->GetOutput(); - m_CurrentBufferedRegion =m_CoefficientFilter->GetInput()->GetBufferedRegion(); + m_CoefficientFilter->GetOutput()->UpdateOutputInformation(); + m_CoefficientFilter->GetOutput()->SetRequestedRegion(m_CoefficientFilter->GetInput()->GetBufferedRegion()); + m_CoefficientFilter->GetOutput()->PropagateRequestedRegion(); + m_CoefficientFilter->GetOutput()->UpdateOutputData(); + m_Coefficients = m_CoefficientFilter->GetOutput(); + m_CurrentBufferedRegion =m_CoefficientFilter->GetInput()->GetBufferedRegion(); } template <class TImageType, class TCoordRep, class TCoefficientType> void @@ -77,8 +77,8 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::SetInputImage(const TImageType * inputData) { if ( inputData ) - { - m_CoefficientFilter->SetInput(inputData); + { + m_CoefficientFilter->SetInput(inputData); // the Coefficient Filter requires that the spline order and the input data be set. // TODO: We need to ensure that this is only run once and only after both input and @@ -92,11 +92,11 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> Superclass::SetInputImage(inputData); m_DataLength = inputData->GetBufferedRegion().GetSize(); - } + } else - { - m_Coefficients = NULL; - } + { + m_Coefficients = NULL; + } } @@ -106,18 +106,18 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::SetSplineOrder(unsigned int SplineOrder) { if (SplineOrder == m_SplineOrder) - { + { return; - } + } m_SplineOrder = SplineOrder; m_CoefficientFilter->SetSplineOrder( SplineOrder ); //this->SetPoles(); m_MaxNumberInterpolationPoints = 1; for (unsigned int n=0; n < ImageDimension; n++) - { + { m_MaxNumberInterpolationPoints *= ( m_SplineOrder + 1); - } + } this->GeneratePointsToIndex( ); } @@ -153,42 +153,42 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> IndexType coefficientIndex; // Step through eachpoint in the N-dimensional interpolation cube. for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { + { // translate each step into the N-dimensional index. // IndexType pointIndex = PointToIndex( p ); double w = 1.0; for (unsigned int n = 0; n < ImageDimension; n++ ) - { + { w *= weights[n][ m_PointsToIndex[p][n] ]; coefficientIndex[n] = EvaluateIndex[n][m_PointsToIndex[p][n]]; // Build up ND index for coefficients. //std::cout<<"From inside: "<<n<<" "<<p<<" "<<m_PointsToIndex[p][n]<<" "<< EvaluateIndex[n][m_PointsToIndex[p][n]]<<std::endl; - } + } //std::cout<<"CoefficientIndex: "<<coefficientIndex<<std::endl; // Convert our step p to the appropriate point in ND space in the // m_Coefficients cube. interpolated += w * m_Coefficients->GetPixel(coefficientIndex); - } + } -/* double interpolated = 0.0; - IndexType coefficientIndex; - // Step through eachpoint in the N-dimensional interpolation cube. - for (unsigned int sp = 0; sp <= m_SplineOrder; sp++) - { - for (unsigned int sp1=0; sp1 <= m_SplineOrder; sp1++) + /* double interpolated = 0.0; + IndexType coefficientIndex; + // Step through eachpoint in the N-dimensional interpolation cube. + for (unsigned int sp = 0; sp <= m_SplineOrder; sp++) { - - double w = 1.0; - for (unsigned int n1 = 0; n1 < ImageDimension; n1++ ) + for (unsigned int sp1=0; sp1 <= m_SplineOrder; sp1++) { - w *= weights[n1][ sp1 ]; - coefficientIndex[n1] = EvaluateIndex[n1][sp]; // Build up ND index for coefficients. - } - interpolated += w * m_Coefficients->GetPixel(coefficientIndex); + double w = 1.0; + for (unsigned int n1 = 0; n1 < ImageDimension; n1++ ) + { + w *= weights[n1][ sp1 ]; + coefficientIndex[n1] = EvaluateIndex[n1][sp]; // Build up ND index for coefficients. + } + + interpolated += w * m_Coefficients->GetPixel(coefficientIndex); + } } - } -*/ + */ return(interpolated); } @@ -223,30 +223,30 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> double tempValue; IndexType coefficientIndex; for (unsigned int n = 0; n < ImageDimension; n++) - { + { derivativeValue[n] = 0.0; for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { + { tempValue = 1.0; for (unsigned int n1 = 0; n1 < ImageDimension; n1++) - { + { //coefficientIndex[n1] = EvaluateIndex[n1][sp]; coefficientIndex[n1] = EvaluateIndex[n1][m_PointsToIndex[p][n1]]; if (n1 == n) - { + { //w *= weights[n][ m_PointsToIndex[p][n] ]; tempValue *= weightsDerivative[n1][ m_PointsToIndex[p][n1] ]; - } + } else - { + { tempValue *= weights[n1][ m_PointsToIndex[p][n1] ]; - } } - derivativeValue[n] += m_Coefficients->GetPixel(coefficientIndex) * tempValue; } - derivativeValue[n] /= this->GetInputImage()->GetSpacing()[n]; // take spacing into account + derivativeValue[n] += m_Coefficients->GetPixel(coefficientIndex) * tempValue; } + derivativeValue[n] /= this->GetInputImage()->GetSpacing()[n]; // take spacing into account + } return(derivativeValue); @@ -265,89 +265,89 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> double w, w2, w4, t, t0, t1; switch (splineOrder) + { + case 3: + for (unsigned int n = 0; n < ImageDimension; n++) { - case 3: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] - (double) EvaluateIndex[n][1]; - weights[n][3] = (1.0 / 6.0) * w * w * w; - weights[n][0] = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - weights[n][3]; - weights[n][2] = w + weights[n][0] - 2.0 * weights[n][3]; - weights[n][1] = 1.0 - weights[n][0] - weights[n][2] - weights[n][3]; - } - break; - case 0: - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = 1; // implements nearest neighbor - } - break; - case 1: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] - (double) EvaluateIndex[n][0]; - weights[n][1] = w; - weights[n][0] = 1.0 - w; - } - break; - case 2: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][1]; - weights[n][1] = 0.75 - w * w; - weights[n][2] = 0.5 * (w - weights[n][1] + 1.0); - weights[n][0] = 1.0 - weights[n][1] - weights[n][2]; - } - break; - case 4: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][2]; - w2 = w * w; - t = (1.0 / 6.0) * w2; - weights[n][0] = 0.5 - w; - weights[n][0] *= weights[n][0]; - weights[n][0] *= (1.0 / 24.0) * weights[n][0]; - t0 = w * (t - 11.0 / 24.0); - t1 = 19.0 / 96.0 + w2 * (0.25 - t); - weights[n][1] = t1 + t0; - weights[n][3] = t1 - t0; - weights[n][4] = weights[n][0] + t0 + 0.5 * w; - weights[n][2] = 1.0 - weights[n][0] - weights[n][1] - weights[n][3] - weights[n][4]; - } - break; - case 5: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][2]; - w2 = w * w; - weights[n][5] = (1.0 / 120.0) * w * w2 * w2; - w2 -= w; - w4 = w2 * w2; - w -= 0.5; - t = w2 * (w2 - 3.0); - weights[n][0] = (1.0 / 24.0) * (1.0 / 5.0 + w2 + w4) - weights[n][5]; - t0 = (1.0 / 24.0) * (w2 * (w2 - 5.0) + 46.0 / 5.0); - t1 = (-1.0 / 12.0) * w * (t + 4.0); - weights[n][2] = t0 + t1; - weights[n][3] = t0 - t1; - t0 = (1.0 / 16.0) * (9.0 / 5.0 - t); - t1 = (1.0 / 24.0) * w * (w4 - w2 - 5.0); - weights[n][1] = t0 + t1; - weights[n][4] = t0 - t1; - } - break; - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; + w = x[n] - (double) EvaluateIndex[n][1]; + weights[n][3] = (1.0 / 6.0) * w * w * w; + weights[n][0] = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - weights[n][3]; + weights[n][2] = w + weights[n][0] - 2.0 * weights[n][3]; + weights[n][1] = 1.0 - weights[n][0] - weights[n][2] - weights[n][3]; + } + break; + case 0: + for (unsigned int n = 0; n < ImageDimension; n++) + { + weights[n][0] = 1; // implements nearest neighbor + } + break; + case 1: + for (unsigned int n = 0; n < ImageDimension; n++) + { + w = x[n] - (double) EvaluateIndex[n][0]; + weights[n][1] = w; + weights[n][0] = 1.0 - w; } + break; + case 2: + for (unsigned int n = 0; n < ImageDimension; n++) + { + /* x */ + w = x[n] - (double)EvaluateIndex[n][1]; + weights[n][1] = 0.75 - w * w; + weights[n][2] = 0.5 * (w - weights[n][1] + 1.0); + weights[n][0] = 1.0 - weights[n][1] - weights[n][2]; + } + break; + case 4: + for (unsigned int n = 0; n < ImageDimension; n++) + { + /* x */ + w = x[n] - (double)EvaluateIndex[n][2]; + w2 = w * w; + t = (1.0 / 6.0) * w2; + weights[n][0] = 0.5 - w; + weights[n][0] *= weights[n][0]; + weights[n][0] *= (1.0 / 24.0) * weights[n][0]; + t0 = w * (t - 11.0 / 24.0); + t1 = 19.0 / 96.0 + w2 * (0.25 - t); + weights[n][1] = t1 + t0; + weights[n][3] = t1 - t0; + weights[n][4] = weights[n][0] + t0 + 0.5 * w; + weights[n][2] = 1.0 - weights[n][0] - weights[n][1] - weights[n][3] - weights[n][4]; + } + break; + case 5: + for (unsigned int n = 0; n < ImageDimension; n++) + { + /* x */ + w = x[n] - (double)EvaluateIndex[n][2]; + w2 = w * w; + weights[n][5] = (1.0 / 120.0) * w * w2 * w2; + w2 -= w; + w4 = w2 * w2; + w -= 0.5; + t = w2 * (w2 - 3.0); + weights[n][0] = (1.0 / 24.0) * (1.0 / 5.0 + w2 + w4) - weights[n][5]; + t0 = (1.0 / 24.0) * (w2 * (w2 - 5.0) + 46.0 / 5.0); + t1 = (-1.0 / 12.0) * w * (t + 4.0); + weights[n][2] = t0 + t1; + weights[n][3] = t0 - t1; + t0 = (1.0 / 16.0) * (9.0 / 5.0 - t); + t1 = (1.0 / 24.0) * w * (w4 - w2 - 5.0); + weights[n][1] = t0 + t1; + weights[n][4] = t0 - t1; + } + break; + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -366,100 +366,100 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> int derivativeSplineOrder = (int) splineOrder -1; switch (derivativeSplineOrder) - { + { // Calculates B(splineOrder) ( (x + 1/2) - xi) - B(splineOrder -1) ( (x - 1/2) - xi) - case -1: - // Why would we want to do this? - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = 0.0; - } - break; - case 0: - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = -1.0; - weights[n][1] = 1.0; - } - break; - case 1: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + 0.5 - (double)EvaluateIndex[n][1]; - // w2 = w; - w1 = 1.0 - w; + case -1: + // Why would we want to do this? + for (unsigned int n = 0; n < ImageDimension; n++) + { + weights[n][0] = 0.0; + } + break; + case 0: + for (unsigned int n = 0; n < ImageDimension; n++) + { + weights[n][0] = -1.0; + weights[n][1] = 1.0; + } + break; + case 1: + for (unsigned int n = 0; n < ImageDimension; n++) + { + w = x[n] + 0.5 - (double)EvaluateIndex[n][1]; + // w2 = w; + w1 = 1.0 - w; - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w; - weights[n][2] = w; - } - break; - case 2: + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w; + weights[n][2] = w; + } + break; + case 2: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + .5 - (double)EvaluateIndex[n][2]; - w2 = 0.75 - w * w; - w3 = 0.5 * (w - w2 + 1.0); - w1 = 1.0 - w2 - w3; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3; - } - break; - case 3: + for (unsigned int n = 0; n < ImageDimension; n++) + { + w = x[n] + .5 - (double)EvaluateIndex[n][2]; + w2 = 0.75 - w * w; + w3 = 0.5 * (w - w2 + 1.0); + w1 = 1.0 - w2 - w3; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3; + } + break; + case 3: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + 0.5 - (double)EvaluateIndex[n][2]; - w4 = (1.0 / 6.0) * w * w * w; - w1 = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - w4; - w3 = w + w1 - 2.0 * w4; - w2 = 1.0 - w1 - w3 - w4; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3 - w4; - weights[n][4] = w4; - } - break; - case 4: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + .5 - (double)EvaluateIndex[n][3]; - t2 = w * w; - t = (1.0 / 6.0) * t2; - w1 = 0.5 - w; - w1 *= w1; - w1 *= (1.0 / 24.0) * w1; - t0 = w * (t - 11.0 / 24.0); - t1 = 19.0 / 96.0 + t2 * (0.25 - t); - w2 = t1 + t0; - w4 = t1 - t0; - w5 = w1 + t0 + 0.5 * w; - w3 = 1.0 - w1 - w2 - w4 - w5; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3 - w4; - weights[n][4] = w4 - w5; - weights[n][5] = w5; - } - break; - - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "SplineOrder (for derivatives) must be between 1 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; + for (unsigned int n = 0; n < ImageDimension; n++) + { + w = x[n] + 0.5 - (double)EvaluateIndex[n][2]; + w4 = (1.0 / 6.0) * w * w * w; + w1 = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - w4; + w3 = w + w1 - 2.0 * w4; + w2 = 1.0 - w1 - w3 - w4; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3 - w4; + weights[n][4] = w4; + } + break; + case 4: + for (unsigned int n = 0; n < ImageDimension; n++) + { + w = x[n] + .5 - (double)EvaluateIndex[n][3]; + t2 = w * w; + t = (1.0 / 6.0) * t2; + w1 = 0.5 - w; + w1 *= w1; + w1 *= (1.0 / 24.0) * w1; + t0 = w * (t - 11.0 / 24.0); + t1 = 19.0 / 96.0 + t2 * (0.25 - t); + w2 = t1 + t0; + w4 = t1 - t0; + w5 = w1 + t0 + 0.5 * w; + w3 = 1.0 - w1 - w2 - w4 - w5; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3 - w4; + weights[n][4] = w4 - w5; + weights[n][5] = w5; } + break; + + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "SplineOrder (for derivatives) must be between 1 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -474,20 +474,20 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // index vector. This is precomputed to save time during the interpolation routine. m_PointsToIndex.resize(m_MaxNumberInterpolationPoints); for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { + { int pp = p; unsigned long indexFactor[ImageDimension]; indexFactor[0] = 1; for (int j=1; j< static_cast<int>(ImageDimension); j++) - { + { indexFactor[j] = indexFactor[j-1] * ( m_SplineOrder + 1 ); - } + } for (int j = (static_cast<int>(ImageDimension) - 1); j >= 0; j--) - { + { m_PointsToIndex[p][j] = pp / indexFactor[j]; pp = pp % indexFactor[j]; - } } + } } template <class TImageType, class TCoordRep, class TCoefficientType> @@ -501,31 +501,31 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // compute the interpolation indexes for (unsigned int n = 0; n< ImageDimension; n++) - { + { if (splineOrder & 1) // Use this index calculation for odd splineOrder - { + { indx = (long)vcl_floor((float)x[n]) - splineOrder / 2; //std::cout<<"x: "<<x<<std::endl; //std::cout<<"splineOrder: "<<splineOrder<<std::endl; //std::cout<<"indx: "<<indx<<std::endl; for (unsigned int k = 0; k <= splineOrder; k++) - { + { evaluateIndex[n][k] = indx++; - } } + } else // Use this index calculation for even splineOrder - { + { indx = (long)vcl_floor((float)(x[n] + 0.5)) - splineOrder / 2; //std::cout<<"x: "<<x<<std::endl; //std::cout<<"splineOrder: "<<splineOrder<<std::endl; //std::cout<<"indx: "<<indx<<std::endl; for (unsigned int k = 0; k <= splineOrder; k++) - { + { evaluateIndex[n][k] = indx++; - } } } + } } template <class TImageType, class TCoordRep, class TCoefficientType> @@ -536,35 +536,35 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> { for (unsigned int n = 0; n < ImageDimension; n++) - { + { long dataLength = m_DataLength[n]; long dataOffset = m_CurrentBufferedRegion.GetIndex()[n]; // apply the mirror boundary conditions // TODO: We could implement other boundary options beside mirror if (m_DataLength[n] == 1) - { + { for (unsigned int k = 0; k <= splineOrder; k++) - { + { evaluateIndex[n][k] = 0; - } } + } else - { + { for (unsigned int k = 0; k <= splineOrder; k++) - { + { // btw - Think about this couldn't this be replaced with a more elagent modulus method? - evaluateIndex[n][k] = (evaluateIndex[n][k] < dataOffset) ? (dataOffset+(dataOffset-evaluateIndex[n][k])%dataLength) - : (evaluateIndex[n][k]); + evaluateIndex[n][k] = (evaluateIndex[n][k] < dataOffset) ? (dataOffset+(dataOffset-evaluateIndex[n][k])%dataLength) + : (evaluateIndex[n][k]); if ((long) dataLength+dataOffset <= evaluateIndex[n][k]) - { - evaluateIndex[n][k] = dataOffset + dataLength - (evaluateIndex[n][k]-dataOffset - dataLength)%dataLength; - } + { + evaluateIndex[n][k] = dataOffset + dataLength - (evaluateIndex[n][k]-dataOffset - dataLength)%dataLength; } - } } + + } } } // namespace otb diff --git a/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.h b/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.h index 877d3bf13570d8d028605b69c532bfefb78a204f..02cdafa663f86195347844a99eab2e369b495d65 100644 --- a/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.h +++ b/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.h @@ -37,7 +37,7 @@ namespace otb */ template <class TInputImage> class ITK_EXPORT BinaryImageMinimalBoundingRegionCalculator - : public itk::ImageToImageFilter<TInputImage,TInputImage> + : public itk::ImageToImageFilter<TInputImage,TInputImage> { public: /** Standard typedefs */ diff --git a/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.txx b/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.txx index 637dc641bb8341157094a6ca712d55bb8c822c1e..4e52933c9ed6dc20bfceb85d2d934aab22c850d6 100644 --- a/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.txx +++ b/Code/BasicFilters/otbBinaryImageMinimalBoundingRegionCalculator.txx @@ -52,93 +52,93 @@ void BinaryImageMinimalBoundingRegionCalculator<TInputImage> ::GenerateData(void) { - // Input images pointers - const InputImageType* image = this->GetInput(); - // Iterator definition - typedef itk::ImageSliceConstIteratorWithIndex<InputImageType> SliceIteratorType; - // Indexes containing upper-left and lower-right corner - typename InputImageType::IndexType min; - typename InputImageType::IndexType max; - min[0]=0; - min[1]=0; - max[1]=0; - max[1]=0; - for ( unsigned int axis = 0; axis < InputImageType::ImageDimension; axis++ ) - { // Create the forward iterator to find lower bound - SliceIteratorType fit(image,image->GetLargestPossibleRegion()); - - fit.SetFirstDirection( !axis ); - fit.SetSecondDirection( axis ); - fit.GoToBegin(); -; - // Walk through the two images line by line - while (!fit.IsAtEnd()) + // Input images pointers + const InputImageType* image = this->GetInput(); + // Iterator definition + typedef itk::ImageSliceConstIteratorWithIndex<InputImageType> SliceIteratorType; + // Indexes containing upper-left and lower-right corner + typename InputImageType::IndexType min; + typename InputImageType::IndexType max; + min[0]=0; + min[1]=0; + max[1]=0; + max[1]=0; + for ( unsigned int axis = 0; axis < InputImageType::ImageDimension; axis++ ) + { // Create the forward iterator to find lower bound + SliceIteratorType fit(image,image->GetLargestPossibleRegion()); + + fit.SetFirstDirection( !axis ); + fit.SetSecondDirection( axis ); + fit.GoToBegin(); + ; + // Walk through the two images line by line + while (!fit.IsAtEnd()) { while (!fit.IsAtEndOfSlice()) - { - while(!fit.IsAtEndOfLine()) { - // If a common intersection is found - if (fit.Get()==m_InsideValue) + while (!fit.IsAtEndOfLine()) + { + // If a common intersection is found + if (fit.Get()==m_InsideValue) { - // then the lower bound is found - min[axis]=fit.GetIndex()[axis]; - fit.GoToReverseBegin(); // skip to the end - break; + // then the lower bound is found + min[axis]=fit.GetIndex()[axis]; + fit.GoToReverseBegin(); // skip to the end + break; } - ++fit; - } - fit.NextLine(); + ++fit; } + fit.NextLine(); + } fit.NextSlice(); } - // Create the reverse iterator to find upper bound - SliceIteratorType rit(image,image->GetLargestPossibleRegion()); - rit.SetFirstDirection(!axis); - rit.SetSecondDirection(axis); - rit.GoToReverseBegin(); - // Walk through the two images line by line - while (!rit.IsAtReverseEnd()) + // Create the reverse iterator to find upper bound + SliceIteratorType rit(image,image->GetLargestPossibleRegion()); + rit.SetFirstDirection(!axis); + rit.SetSecondDirection(axis); + rit.GoToReverseBegin(); + // Walk through the two images line by line + while (!rit.IsAtReverseEnd()) { while (!rit.IsAtReverseEndOfSlice()) - { - while (!rit.IsAtReverseEndOfLine()) { - // If a common intersection is found - if (rit.Get()==m_InsideValue) + while (!rit.IsAtReverseEndOfLine()) + { + // If a common intersection is found + if (rit.Get()==m_InsideValue) { - max[axis]=rit.GetIndex()[axis]; - rit.GoToBegin(); //Skip to reverse end - break; + max[axis]=rit.GetIndex()[axis]; + rit.GoToBegin(); //Skip to reverse end + break; } - --rit; - - } - rit.PreviousLine(); + --rit; } + rit.PreviousLine(); + + } rit.PreviousSlice(); } - } + } - typename InputImageType::SizeType size; - typename InputImageType::IndexType index; + typename InputImageType::SizeType size; + typename InputImageType::IndexType index; - for(int i=0;i<InputImageType::ImageDimension;i++) - { - size[i]=max[i]-min[i]+1; - index[i]=min[i]; - } + for (int i=0;i<InputImageType::ImageDimension;i++) + { + size[i]=max[i]-min[i]+1; + index[i]=min[i]; + } - m_Region.SetIndex(index); - m_Region.SetSize(size); + m_Region.SetIndex(index); + m_Region.SetSize(size); - if(m_Pad) - { - m_Region.PadByRadius(m_Pad); - } + if (m_Pad) + { + m_Region.PadByRadius(m_Pad); + } - m_Region.Crop(image->GetLargestPossibleRegion()); + m_Region.Crop(image->GetLargestPossibleRegion()); } /** * PrintSelf method @@ -147,9 +147,9 @@ template <class TInputImage> void BinaryImageMinimalBoundingRegionCalculator<TInputImage> ::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - } +{ + Superclass::PrintSelf(os,indent); +} } // End namespace otb diff --git a/Code/BasicFilters/otbChangeLabelImageFilter.h b/Code/BasicFilters/otbChangeLabelImageFilter.h index 2594e18d0b268e598db25137c43a17759094ca21..8c7053d763c3747a339bfde60e230e9bebdd01e9 100644 --- a/Code/BasicFilters/otbChangeLabelImageFilter.h +++ b/Code/BasicFilters/otbChangeLabelImageFilter.h @@ -28,9 +28,9 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ChangeLabelImageFilter - : public itk::ChangeLabelImageFilter<TInputImage,TOutputImage> + : public itk::ChangeLabelImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef ChangeLabelImageFilter Self; typedef itk::ChangeLabelImageFilter<TInputImage,TOutputImage> Superclass; @@ -51,24 +51,24 @@ class ITK_EXPORT ChangeLabelImageFilter protected: /** Constructor */ ChangeLabelImageFilter() - { - m_NumberOfComponentsPerPixel = 1; - } + { + m_NumberOfComponentsPerPixel = 1; + } /** Generate the output information missing */ void GenerateOutputInformation() - { - Superclass::GenerateOutputInformation(); + { + Superclass::GenerateOutputInformation(); - this->GetOutput()->SetNumberOfComponentsPerPixel(m_NumberOfComponentsPerPixel); - } + this->GetOutput()->SetNumberOfComponentsPerPixel(m_NumberOfComponentsPerPixel); + } /** Destructor */ virtual ~ChangeLabelImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"Number of components per pixel: "<<m_NumberOfComponentsPerPixel; - } + { + Superclass::PrintSelf(os,indent); + os<<indent<<"Number of components per pixel: "<<m_NumberOfComponentsPerPixel; + } private: ChangeLabelImageFilter(const Self&); //purposely not implemented diff --git a/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.h b/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.h index 65d3249f682d47517006b2cfe71deb80e59b60e3..db7d1cb341013a35e055672660d3a2f623d7781a 100644 --- a/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.h +++ b/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.h @@ -20,7 +20,8 @@ #include "itkImageToImageFilter.h" -namespace otb { +namespace otb +{ /** * \class ClosingOpeningMorphologicalFilter * \brief This filter implements an opening grayscale morphological operation @@ -40,7 +41,7 @@ namespace otb { */ template <class TInputImage, class TOutputImage, class TKernel> class ITK_EXPORT ClosingOpeningMorphologicalFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { public : /** Standard typedefs */ diff --git a/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.txx b/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.txx index 3120fc410877a946e8b131b51436e78e3454f7b3..6d4f670545fbede5a148152709d2c8025e9db724 100644 --- a/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.txx +++ b/Code/BasicFilters/otbClosingOpeningMorphologicalFilter.txx @@ -24,7 +24,8 @@ #include "itkGrayscaleMorphologicalClosingImageFilter.h" #include "itkProgressAccumulator.h" -namespace otb { +namespace otb +{ /** * Constructor */ @@ -32,8 +33,8 @@ template <class TInputImage,class TOutputImage, class TKernel> ClosingOpeningMorphologicalFilter<TInputImage, TOutputImage, TKernel> ::ClosingOpeningMorphologicalFilter() { -m_Kernel.SetRadius(1); -m_Kernel.CreateStructuringElement(); + m_Kernel.SetRadius(1); + m_Kernel.CreateStructuringElement(); } /** * Main computation method diff --git a/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.h b/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.h index 8ad9cc5a917b095c2f12f4d32066ec656a1a878d..511822cf5a685dc31a3f7919fbbffc1d43856388 100644 --- a/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.h +++ b/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.h @@ -56,104 +56,104 @@ namespace otb * */ - template <class TInputImage> - class ITK_EXPORT ContinuousMinimumMaximumImageCalculator : +template <class TInputImage> +class ITK_EXPORT ContinuousMinimumMaximumImageCalculator : public itk::Object - { - public: - /** Standard class typedefs. */ - typedef ContinuousMinimumMaximumImageCalculator Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public: + /** Standard class typedefs. */ + typedef ContinuousMinimumMaximumImageCalculator Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(ContinuousMinimumMaximumImageCalculator, Object); + /** Run-time type information (and related methods). */ + itkTypeMacro(ContinuousMinimumMaximumImageCalculator, Object); - /** Type definition for the input image. */ - typedef TInputImage ImageType; + /** Type definition for the input image. */ + typedef TInputImage ImageType; - /** Pointer type for the image. */ - typedef typename TInputImage::Pointer ImagePointer; + /** Pointer type for the image. */ + typedef typename TInputImage::Pointer ImagePointer; - /** Const Pointer type for the image. */ - typedef typename TInputImage::ConstPointer ImageConstPointer; + /** Const Pointer type for the image. */ + typedef typename TInputImage::ConstPointer ImageConstPointer; - /** Type definition for the input image pixel type. */ - typedef typename TInputImage::PixelType PixelType; + /** Type definition for the input image pixel type. */ + typedef typename TInputImage::PixelType PixelType; - /** Type definition for the input image real pixel type. */ - typedef typename itk::NumericTraits<PixelType>::RealType RealPixelType; + /** Type definition for the input image real pixel type. */ + typedef typename itk::NumericTraits<PixelType>::RealType RealPixelType; - /** Type definition for the input image index type. */ - typedef typename TInputImage::IndexType IndexType; + /** Type definition for the input image index type. */ + typedef typename TInputImage::IndexType IndexType; - /** Type definition for the input image index type. */ - typedef typename TInputImage::PointType ContinuousIndexType; + /** Type definition for the input image index type. */ + typedef typename TInputImage::PointType ContinuousIndexType; - /** Type definition for the input image region type. */ - typedef typename TInputImage::RegionType RegionType; + /** Type definition for the input image region type. */ + typedef typename TInputImage::RegionType RegionType; - /** Set the input image. */ - itkSetConstObjectMacro(Image,ImageType); + /** Set the input image. */ + itkSetConstObjectMacro(Image,ImageType); - /** Compute the minimum value of intensity of the input image. */ - void ComputeMinimum(void); + /** Compute the minimum value of intensity of the input image. */ + void ComputeMinimum(void); - /** Compute the maximum value of intensity of the input image. */ - void ComputeMaximum(void); + /** Compute the maximum value of intensity of the input image. */ + void ComputeMaximum(void); - /** Compute the minimum and maximum values of intensity of the input image. */ - void Compute(void); + /** Compute the minimum and maximum values of intensity of the input image. */ + void Compute(void); - /** Return the minimum intensity value. */ - itkGetMacro(Minimum,PixelType); + /** Return the minimum intensity value. */ + itkGetMacro(Minimum,PixelType); - /** Return the maximum intensity value. */ - itkGetMacro(Maximum,PixelType); + /** Return the maximum intensity value. */ + itkGetMacro(Maximum,PixelType); - /** Return the index of the minimum intensity value. */ - itkGetConstReferenceMacro(IndexOfMinimum,IndexType); + /** Return the index of the minimum intensity value. */ + itkGetConstReferenceMacro(IndexOfMinimum,IndexType); - /** Return the index of the maximum intensity value. */ - itkGetConstReferenceMacro(IndexOfMaximum,IndexType); + /** Return the index of the maximum intensity value. */ + itkGetConstReferenceMacro(IndexOfMaximum,IndexType); - /** Return the index of the minimum intensity value. */ - itkGetConstReferenceMacro(ContinuousIndexOfMinimum,ContinuousIndexType); + /** Return the index of the minimum intensity value. */ + itkGetConstReferenceMacro(ContinuousIndexOfMinimum,ContinuousIndexType); - /** Return the index of the maximum intensity value. */ - itkGetConstReferenceMacro(ContinuousIndexOfMaximum,ContinuousIndexType); + /** Return the index of the maximum intensity value. */ + itkGetConstReferenceMacro(ContinuousIndexOfMaximum,ContinuousIndexType); - /** Set the region over which the values will be computed */ - void SetRegion( const RegionType & region ); + /** Set the region over which the values will be computed */ + void SetRegion( const RegionType & region ); - protected: - ContinuousMinimumMaximumImageCalculator(); - virtual ~ContinuousMinimumMaximumImageCalculator() {}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + ContinuousMinimumMaximumImageCalculator(); + virtual ~ContinuousMinimumMaximumImageCalculator() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; - PixelType m_Minimum; - PixelType m_Maximum; - ImageConstPointer m_ContinuousImage; + PixelType m_Minimum; + PixelType m_Maximum; + ImageConstPointer m_ContinuousImage; - IndexType m_IndexOfMinimum; - IndexType m_IndexOfMaximum; - ContinuousIndexType m_ContinuousIndexOfMinimum; - ContinuousIndexType m_ContinuousIndexOfMaximum; - ImageConstPointer m_Image; + IndexType m_IndexOfMinimum; + IndexType m_IndexOfMaximum; + ContinuousIndexType m_ContinuousIndexOfMinimum; + ContinuousIndexType m_ContinuousIndexOfMaximum; + ImageConstPointer m_Image; - RegionType m_Region; - bool m_RegionSetByUser; + RegionType m_Region; + bool m_RegionSetByUser; - private: - ContinuousMinimumMaximumImageCalculator(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + ContinuousMinimumMaximumImageCalculator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; diff --git a/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.txx b/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.txx index 281aad4b217f36590934fd6a7e7475f6ad34943c..f8b129a03b0ba050c4cb047a65f13c082717b1ca 100644 --- a/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.txx +++ b/Code/BasicFilters/otbContinuousMinimumMaximumImageCalculator.txx @@ -29,148 +29,56 @@ namespace otb /* * Constructor */ - template<class TInputImage> - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::ContinuousMinimumMaximumImageCalculator() - { - m_Image = TInputImage::New(); - m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); - m_Minimum = itk::NumericTraits<PixelType>::max(); - m_IndexOfMinimum.Fill(0); - m_IndexOfMaximum.Fill(0); - m_RegionSetByUser = false; - } +template<class TInputImage> +ContinuousMinimumMaximumImageCalculator<TInputImage> +::ContinuousMinimumMaximumImageCalculator() +{ + m_Image = TInputImage::New(); + m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); + m_Minimum = itk::NumericTraits<PixelType>::max(); + m_IndexOfMinimum.Fill(0); + m_IndexOfMaximum.Fill(0); + m_RegionSetByUser = false; +} /* * Compute Min and Max of m_Image */ - template<class TInputImage> - void - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::Compute(void) +template<class TInputImage> +void +ContinuousMinimumMaximumImageCalculator<TInputImage> +::Compute(void) +{ + if ( !m_RegionSetByUser ) { - if( !m_RegionSetByUser ) - { - m_Region = m_Image->GetRequestedRegion(); - } - - itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); - m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); - m_Minimum = itk::NumericTraits<PixelType>::max(); - - - while( !it.IsAtEnd() ) - { - const RealPixelType value = it.Get(); - if (value > static_cast<RealPixelType>(m_Maximum) ) - { - m_Maximum = static_cast<PixelType>(value); - m_IndexOfMaximum = it.GetIndex(); - } - if (value < static_cast<RealPixelType>(m_Minimum)) - { - m_Minimum = static_cast<PixelType>(value); - m_IndexOfMinimum = it.GetIndex(); - } - ++it; - } - - IndexType indexNeighbor; - - { //Continuous Minimum calculation - //Compute horizontal offset - indexNeighbor[0] = m_IndexOfMinimum[0]-1; - indexNeighbor[1] = m_IndexOfMinimum[1]; - it.SetIndex(indexNeighbor); - const RealPixelType leftValue= it.Get(); - indexNeighbor[0] = m_IndexOfMinimum[0]+1; - indexNeighbor[1] = m_IndexOfMinimum[1]; - it.SetIndex(indexNeighbor); - const RealPixelType rightValue= it.Get(); - - double hOffset = -(rightValue-leftValue) / (2*(rightValue+leftValue-2*m_Minimum)); - - //Compute vertical offset - indexNeighbor[0] = m_IndexOfMinimum[0]; - indexNeighbor[1] = m_IndexOfMinimum[1]-1; - it.SetIndex(indexNeighbor); - const RealPixelType topValue= it.Get(); - indexNeighbor[0] = m_IndexOfMinimum[0]; - indexNeighbor[1] = m_IndexOfMinimum[1]+1; - it.SetIndex(indexNeighbor); - const RealPixelType bottomValue= it.Get(); - - - double vOffset = -(bottomValue-topValue) / (2*(bottomValue+topValue-2*m_Minimum)); - - - m_ContinuousIndexOfMinimum[0] = m_IndexOfMinimum[0] + hOffset; - m_ContinuousIndexOfMinimum[1] = m_IndexOfMinimum[1] + vOffset; - } - - - { //Continuous Maximum calculation - //Compute horizontal offset - indexNeighbor[0] = m_IndexOfMaximum[0]-1; - indexNeighbor[1] = m_IndexOfMaximum[1]; - it.SetIndex(indexNeighbor); - const RealPixelType leftValue= it.Get(); - indexNeighbor[0] = m_IndexOfMaximum[0]+1; - indexNeighbor[1] = m_IndexOfMaximum[1]; - it.SetIndex(indexNeighbor); - const RealPixelType rightValue= it.Get(); - - double hOffset = -(rightValue-leftValue) / (2*(rightValue+leftValue-2*m_Maximum)); - - //Compute vertical offset - indexNeighbor[0] = m_IndexOfMaximum[0]; - indexNeighbor[1] = m_IndexOfMaximum[1]-1; - it.SetIndex(indexNeighbor); - const RealPixelType topValue= it.Get(); - indexNeighbor[0] = m_IndexOfMaximum[0]; - indexNeighbor[1] = m_IndexOfMaximum[1]+1; - it.SetIndex(indexNeighbor); - const RealPixelType bottomValue= it.Get(); - - - double vOffset = -(bottomValue-topValue) / (2*(bottomValue+topValue-2*m_Maximum)); - + m_Region = m_Image->GetRequestedRegion(); + } - m_ContinuousIndexOfMaximum[0] = m_IndexOfMaximum[0] + hOffset; - m_ContinuousIndexOfMaximum[1] = m_IndexOfMaximum[1] + vOffset; - } + itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); + m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); + m_Minimum = itk::NumericTraits<PixelType>::max(); - } -/* - * Compute the minimum intensity value of the image - */ - template<class TInputImage> - void - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::ComputeMinimum(void) + while ( !it.IsAtEnd() ) { - if( !m_RegionSetByUser ) + const RealPixelType value = it.Get(); + if (value > static_cast<RealPixelType>(m_Maximum) ) { - m_Region = m_Image->GetRequestedRegion(); + m_Maximum = static_cast<PixelType>(value); + m_IndexOfMaximum = it.GetIndex(); } - itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); - m_Minimum = itk::NumericTraits<PixelType>::max(); - - while( !it.IsAtEnd() ) + if (value < static_cast<RealPixelType>(m_Minimum)) { - const RealPixelType value = it.Get(); - if (value < static_cast<RealPixelType>(m_Minimum)) - { - m_Minimum = static_cast<PixelType>(value); - m_IndexOfMinimum = it.GetIndex(); - } - ++it; + m_Minimum = static_cast<PixelType>(value); + m_IndexOfMinimum = it.GetIndex(); } + ++it; + } - IndexType indexNeighbor; + IndexType indexNeighbor; + { //Continuous Minimum calculation //Compute horizontal offset indexNeighbor[0] = m_IndexOfMinimum[0]-1; indexNeighbor[1] = m_IndexOfMinimum[1]; @@ -199,52 +107,10 @@ namespace otb m_ContinuousIndexOfMinimum[0] = m_IndexOfMinimum[0] + hOffset; m_ContinuousIndexOfMinimum[1] = m_IndexOfMinimum[1] + vOffset; - - - - } -/* - * Compute the maximum intensity value of the image - */ - template<class TInputImage> - void - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::ComputeMaximum(void) - { - if( !m_RegionSetByUser ) - { - m_Region = m_Image->GetRequestedRegion(); - } - itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); - m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); - - while( !it.IsAtEnd() ) - { - const RealPixelType value = it.Get(); - if (value > static_cast<RealPixelType>(m_Maximum) ) - { - m_Maximum = static_cast<PixelType>(value); - m_IndexOfMaximum = it.GetIndex(); - } - ++it; - } - - //Solve equations a,b,c -// y0 = a*x0^2 + b*x0 +c -// y1 = a*x1^2 + b*x1 +c -// y2 = a*x2^2 + b*x2 +c - // -// y0 = a - b +c -// y1 = c -// y2 = a + b +c - // - // - // Max is at -b/2a - // -(y2-y0)/(2*(y0+y2-2y1)) - IndexType indexNeighbor; + { //Continuous Maximum calculation //Compute horizontal offset indexNeighbor[0] = m_IndexOfMaximum[0]-1; indexNeighbor[1] = m_IndexOfMaximum[1]; @@ -273,46 +139,180 @@ namespace otb m_ContinuousIndexOfMaximum[0] = m_IndexOfMaximum[0] + hOffset; m_ContinuousIndexOfMaximum[1] = m_IndexOfMaximum[1] + vOffset; - } +} +/* + * Compute the minimum intensity value of the image + */ +template<class TInputImage> +void +ContinuousMinimumMaximumImageCalculator<TInputImage> +::ComputeMinimum(void) +{ + if ( !m_RegionSetByUser ) + { + m_Region = m_Image->GetRequestedRegion(); + } + itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); + m_Minimum = itk::NumericTraits<PixelType>::max(); - template<class TInputImage> - void - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::SetRegion( const RegionType & region ) + while ( !it.IsAtEnd() ) { - m_Region = region; - m_RegionSetByUser = true; + const RealPixelType value = it.Get(); + if (value < static_cast<RealPixelType>(m_Minimum)) + { + m_Minimum = static_cast<PixelType>(value); + m_IndexOfMinimum = it.GetIndex(); + } + ++it; } + IndexType indexNeighbor; + + //Compute horizontal offset + indexNeighbor[0] = m_IndexOfMinimum[0]-1; + indexNeighbor[1] = m_IndexOfMinimum[1]; + it.SetIndex(indexNeighbor); + const RealPixelType leftValue= it.Get(); + indexNeighbor[0] = m_IndexOfMinimum[0]+1; + indexNeighbor[1] = m_IndexOfMinimum[1]; + it.SetIndex(indexNeighbor); + const RealPixelType rightValue= it.Get(); + + double hOffset = -(rightValue-leftValue) / (2*(rightValue+leftValue-2*m_Minimum)); + + //Compute vertical offset + indexNeighbor[0] = m_IndexOfMinimum[0]; + indexNeighbor[1] = m_IndexOfMinimum[1]-1; + it.SetIndex(indexNeighbor); + const RealPixelType topValue= it.Get(); + indexNeighbor[0] = m_IndexOfMinimum[0]; + indexNeighbor[1] = m_IndexOfMinimum[1]+1; + it.SetIndex(indexNeighbor); + const RealPixelType bottomValue= it.Get(); - template<class TInputImage> - void - ContinuousMinimumMaximumImageCalculator<TInputImage> - ::PrintSelf( std::ostream& os, itk::Indent indent ) const + double vOffset = -(bottomValue-topValue) / (2*(bottomValue+topValue-2*m_Minimum)); + + + m_ContinuousIndexOfMinimum[0] = m_IndexOfMinimum[0] + hOffset; + m_ContinuousIndexOfMinimum[1] = m_IndexOfMinimum[1] + vOffset; + + + + +} + +/* + * Compute the maximum intensity value of the image + */ +template<class TInputImage> +void +ContinuousMinimumMaximumImageCalculator<TInputImage> +::ComputeMaximum(void) +{ + if ( !m_RegionSetByUser ) { - Superclass::PrintSelf(os,indent); - - os << indent << "Minimum: " - << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(m_Minimum) - << std::endl; - os << indent << "Maximum: " - << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(m_Maximum) - << std::endl; - os << indent << "Index of Minimum: " << m_IndexOfMinimum << std::endl; - os << indent << "Index of Maximum: " << m_IndexOfMaximum << std::endl; - os << indent << "Continuous Index of Minimum: " << m_ContinuousIndexOfMinimum << std::endl; - os << indent << "Continuous Index of Maximum: " << m_ContinuousIndexOfMaximum << std::endl; - - os << indent << "Image: " << std::endl; - m_Image->Print(os, indent.GetNextIndent()); - os << indent << "Region: " << std::endl; - m_Region.Print(os,indent.GetNextIndent()); - os << indent << "Region set by User: " << m_RegionSetByUser << std::endl; + m_Region = m_Image->GetRequestedRegion(); } + itk::ImageRegionConstIteratorWithIndex< TInputImage > it( m_Image, m_Region ); + m_Maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); + + while ( !it.IsAtEnd() ) + { + const RealPixelType value = it.Get(); + if (value > static_cast<RealPixelType>(m_Maximum) ) + { + m_Maximum = static_cast<PixelType>(value); + m_IndexOfMaximum = it.GetIndex(); + } + ++it; + } + + //Solve equations a,b,c +// y0 = a*x0^2 + b*x0 +c +// y1 = a*x1^2 + b*x1 +c +// y2 = a*x2^2 + b*x2 +c + // +// y0 = a - b +c +// y1 = c +// y2 = a + b +c + // + // + // Max is at -b/2a + // -(y2-y0)/(2*(y0+y2-2y1)) + IndexType indexNeighbor; + + //Compute horizontal offset + indexNeighbor[0] = m_IndexOfMaximum[0]-1; + indexNeighbor[1] = m_IndexOfMaximum[1]; + it.SetIndex(indexNeighbor); + const RealPixelType leftValue= it.Get(); + indexNeighbor[0] = m_IndexOfMaximum[0]+1; + indexNeighbor[1] = m_IndexOfMaximum[1]; + it.SetIndex(indexNeighbor); + const RealPixelType rightValue= it.Get(); + + double hOffset = -(rightValue-leftValue) / (2*(rightValue+leftValue-2*m_Maximum)); + + //Compute vertical offset + indexNeighbor[0] = m_IndexOfMaximum[0]; + indexNeighbor[1] = m_IndexOfMaximum[1]-1; + it.SetIndex(indexNeighbor); + const RealPixelType topValue= it.Get(); + indexNeighbor[0] = m_IndexOfMaximum[0]; + indexNeighbor[1] = m_IndexOfMaximum[1]+1; + it.SetIndex(indexNeighbor); + const RealPixelType bottomValue= it.Get(); + + + double vOffset = -(bottomValue-topValue) / (2*(bottomValue+topValue-2*m_Maximum)); + + + m_ContinuousIndexOfMaximum[0] = m_IndexOfMaximum[0] + hOffset; + m_ContinuousIndexOfMaximum[1] = m_IndexOfMaximum[1] + vOffset; + +} + + + +template<class TInputImage> +void +ContinuousMinimumMaximumImageCalculator<TInputImage> +::SetRegion( const RegionType & region ) +{ + m_Region = region; + m_RegionSetByUser = true; +} + + + +template<class TInputImage> +void +ContinuousMinimumMaximumImageCalculator<TInputImage> +::PrintSelf( std::ostream& os, itk::Indent indent ) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Minimum: " + << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(m_Minimum) + << std::endl; + os << indent << "Maximum: " + << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(m_Maximum) + << std::endl; + os << indent << "Index of Minimum: " << m_IndexOfMinimum << std::endl; + os << indent << "Index of Maximum: " << m_IndexOfMaximum << std::endl; + os << indent << "Continuous Index of Minimum: " << m_ContinuousIndexOfMinimum << std::endl; + os << indent << "Continuous Index of Maximum: " << m_ContinuousIndexOfMaximum << std::endl; + + os << indent << "Image: " << std::endl; + m_Image->Print(os, indent.GetNextIndent()); + os << indent << "Region: " << std::endl; + m_Region.Print(os,indent.GetNextIndent()); + os << indent << "Region set by User: " << m_RegionSetByUser << std::endl; +} } // end namespace otb diff --git a/Code/BasicFilters/otbConvolutionImageFilter.h b/Code/BasicFilters/otbConvolutionImageFilter.h index 5ebe5cad675e0b7abfaf39ba5380e534c2bf408d..cde1adfc48e8b5ee1ff430a37df88eec21c2def9 100644 --- a/Code/BasicFilters/otbConvolutionImageFilter.h +++ b/Code/BasicFilters/otbConvolutionImageFilter.h @@ -60,7 +60,7 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TBoundaryCondition = itk::ZeroFluxNeumannBoundaryCondition<TInputImage> > class ITK_EXPORT ConvolutionImageFilter : - public itk::ImageToImageFilter< TInputImage, TOutputImage > + public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: /** Extract dimension from input and output image. */ @@ -98,19 +98,19 @@ public: /** Set the radius of the neighborhood of the filter */ virtual void SetRadius (const InputSizeType rad) { - itkDebugMacro("setting radius to " << rad); - if (this->m_Radius != rad) - { - this->m_Radius = rad; - unsigned int arraySize=1; - for (unsigned int i=0; i<m_Radius.GetSizeDimension(); i++) - { - arraySize *= 2*this->m_Radius[i]+1; - } - this->m_Filter.SetSize(arraySize); - this->m_Filter.Fill(1); - this->Modified(); - } + itkDebugMacro("setting radius to " << rad); + if (this->m_Radius != rad) + { + this->m_Radius = rad; + unsigned int arraySize=1; + for (unsigned int i=0; i<m_Radius.GetSizeDimension(); i++) + { + arraySize *= 2*this->m_Radius[i]+1; + } + this->m_Filter.SetSize(arraySize); + this->m_Filter.Fill(1); + this->Modified(); + } } /** Get the radius of the neighborhood of the filter*/ @@ -118,17 +118,17 @@ public: /** Set the input filter */ void SetFilter( ArrayType filter ) - { - if(filter.Size()!= m_Filter.Size()) - { - itkExceptionMacro("Error in SetFilter, invalid filter size:"<< filter.Size()<<" instead of 2*(m_Radius[0]+1)*(2*m_Radius[1]+1): "<<m_Filter.Size()); - } - else { - m_Filter = filter; - } - this->Modified(); + if (filter.Size()!= m_Filter.Size()) + { + itkExceptionMacro("Error in SetFilter, invalid filter size:"<< filter.Size()<<" instead of 2*(m_Radius[0]+1)*(2*m_Radius[1]+1): "<<m_Filter.Size()); } + else + { + m_Filter = filter; + } + this->Modified(); + } itkGetConstReferenceMacro(Filter, ArrayType); diff --git a/Code/BasicFilters/otbConvolutionImageFilter.txx b/Code/BasicFilters/otbConvolutionImageFilter.txx index 54cb03b1c7b5af32249efdd4013f7ed9d36f8892..4d7420875a70165f2439208557892228d6cf356f 100644 --- a/Code/BasicFilters/otbConvolutionImageFilter.txx +++ b/Code/BasicFilters/otbConvolutionImageFilter.txx @@ -54,9 +54,9 @@ ConvolutionImageFilter<TInputImage, TOutputImage, TBoundaryCondition> typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -68,12 +68,12 @@ ConvolutionImageFilter<TInputImage, TOutputImage, TBoundaryCondition> // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -86,7 +86,7 @@ ConvolutionImageFilter<TInputImage, TOutputImage, TBoundaryCondition> e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } @@ -124,7 +124,7 @@ ConvolutionImageFilter< TInputImage, TOutputImage, TBoundaryCondition> for (fit=faceList.begin(); fit != faceList.end(); ++fit) { bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, - input, *fit); + input, *fit); it = itk::ImageRegionIterator<OutputImageType>(output, *fit); bit.OverrideBoundaryCondition(&nbc); diff --git a/Code/BasicFilters/otbCountImageFilter.h b/Code/BasicFilters/otbCountImageFilter.h index df4905853bfc0c577317bdeff71219ec5421b738..7dececf6a8b15c847b22286a637216fc3a72bee7 100644 --- a/Code/BasicFilters/otbCountImageFilter.h +++ b/Code/BasicFilters/otbCountImageFilter.h @@ -35,88 +35,88 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - class ITK_EXPORT CountImageFilter - : public itk::ImageToImageFilter<TInputImage, TOutputImage> - { - - public: - - /** Standard class typedefs. */ - typedef CountImageFilter Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass ; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(CountImageFilter,itk::ImageToImageFilter); - - - /** Template parameters typedefs*/ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef typename InputImageType::IndexType IndexType; - - /** OutputImageType typedef support*/ - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::PixelType OutputPixelType; - - typedef typename itk::NumericTraits< OutputPixelType>::RealType OutputRealType; - - /** Detector typedef Support*/ - typedef TDetector DetectorType; - - /** Count Function typedef Support*/ - typedef TCount CountMethodType; - - /** CountImageFunction support*/ - typedef otb::CountImageFunction<InputImageType,DetectorType, - CountMethodType > CountImageFunctionType; - typedef typename CountImageFunctionType::Pointer CountImageFunctionTypePointer; - - /** Get/Set the radius of the neighborhood over which the - statistics are evaluated */ - itkSetMacro( NeighborhoodRadius, unsigned int ); - itkGetConstReferenceMacro( NeighborhoodRadius, unsigned int ); - - - /**Set/Get Descriptor from the otbCountmageFunction*/ - virtual void SetDetector(DetectorType* detector); - virtual DetectorType* GetDetector(); - - protected: - - /** - * Constructor. - */ - CountImageFilter(); - /** - * Destructor. - */ - virtual ~CountImageFilter(); - /** - * Standard PrintSelf method. - */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Main computation method. - */ - virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); - - private: - - CountImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - CountImageFunctionTypePointer m_CountImageFunction; - - unsigned int m_NeighborhoodRadius; - }; +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +class ITK_EXPORT CountImageFilter + : public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ + +public: + + /** Standard class typedefs. */ + typedef CountImageFilter Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass ; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(CountImageFilter,itk::ImageToImageFilter); + + + /** Template parameters typedefs*/ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef typename InputImageType::IndexType IndexType; + + /** OutputImageType typedef support*/ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputPixelType; + + typedef typename itk::NumericTraits< OutputPixelType>::RealType OutputRealType; + + /** Detector typedef Support*/ + typedef TDetector DetectorType; + + /** Count Function typedef Support*/ + typedef TCount CountMethodType; + + /** CountImageFunction support*/ + typedef otb::CountImageFunction<InputImageType,DetectorType, + CountMethodType > CountImageFunctionType; + typedef typename CountImageFunctionType::Pointer CountImageFunctionTypePointer; + + /** Get/Set the radius of the neighborhood over which the + statistics are evaluated */ + itkSetMacro( NeighborhoodRadius, unsigned int ); + itkGetConstReferenceMacro( NeighborhoodRadius, unsigned int ); + + + /**Set/Get Descriptor from the otbCountmageFunction*/ + virtual void SetDetector(DetectorType* detector); + virtual DetectorType* GetDetector(); + +protected: + + /** + * Constructor. + */ + CountImageFilter(); + /** + * Destructor. + */ + virtual ~CountImageFilter(); + /** + * Standard PrintSelf method. + */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Main computation method. + */ + virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + +private: + + CountImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + CountImageFunctionTypePointer m_CountImageFunction; + + unsigned int m_NeighborhoodRadius; +}; } #ifndef OTB_MANUAL_INSTANTIATION #include "otbCountImageFilter.txx" diff --git a/Code/BasicFilters/otbCountImageFilter.txx b/Code/BasicFilters/otbCountImageFilter.txx index d03536bbef8ab6e875e0621e64f2d75d201512bb..4f8338dc205ccf57481c964c640862721769d270 100644 --- a/Code/BasicFilters/otbCountImageFilter.txx +++ b/Code/BasicFilters/otbCountImageFilter.txx @@ -24,34 +24,34 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /**--------------------------------------------------------- - * Constructor - ----------------------------------------------------------*/ - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - CountImageFilter<TInputImage , TDetector, TCount, TOutputImage> - ::CountImageFilter() - { - this->SetNumberOfRequiredInputs( 1 ); - m_CountImageFunction = CountImageFunctionType::New(); - m_NeighborhoodRadius = 1; - } - +/**--------------------------------------------------------- + * Constructor + ----------------------------------------------------------*/ +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +CountImageFilter<TInputImage , TDetector, TCount, TOutputImage> +::CountImageFilter() +{ + this->SetNumberOfRequiredInputs( 1 ); + m_CountImageFunction = CountImageFunctionType::New(); + m_NeighborhoodRadius = 1; +} - /*--------------------------------------------------------- - * Destructor.c - ----------------------------------------------------------*/ - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > - ::~CountImageFilter() - {} - /** - * threaded Generate Data - */ +/*--------------------------------------------------------- + * Destructor.c + ----------------------------------------------------------*/ +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > +::~CountImageFilter() +{} - /** - * ThreadedGenerateData Performs the pixel-wise addition +/** + * threaded Generate Data */ + +/** +* ThreadedGenerateData Performs the pixel-wise addition +*/ template <class TInputImage , class TDetector, class TCount, class TOutputImage> void CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > @@ -60,69 +60,69 @@ CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > typename Superclass::OutputImagePointer outputImage = this->GetOutput(); InputImagePointerType ptr = const_cast<InputImageType *>(this->GetInput()); - /** Update the radius for the CountImageFunction */ - m_CountImageFunction->SetInputImage(ptr); - m_CountImageFunction->SetNeighborhoodRadius(m_NeighborhoodRadius); - - - itk::ImageRegionIterator<InputImageType> - itInput(ptr, ptr->GetLargestPossibleRegion()); - - itk::ImageRegionIterator<OutputImageType> - itOutput(outputImage, outputImage->GetLargestPossibleRegion()); - - itInput.GoToBegin(); - itOutput.GoToBegin(); - - while(!itInput.IsAtEnd() && !itOutput.IsAtEnd()) - { - IndexType index = itInput.GetIndex(); - itOutput.Set(m_CountImageFunction->EvaluateAtIndex(index)); - - ++itInput; - ++itOutput; - } - - -} + /** Update the radius for the CountImageFunction */ + m_CountImageFunction->SetInputImage(ptr); + m_CountImageFunction->SetNeighborhoodRadius(m_NeighborhoodRadius); - /** - * Set Detector - */ - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - void - CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > - ::SetDetector(DetectorType* detector) - { - m_CountImageFunction->SetDetector(detector); - } - - - /** - * Get Detector - */ - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - typename CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > - ::DetectorType * - CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > - ::GetDetector() - { - return m_CountImageFunction->GetDetector(); - } - + itk::ImageRegionIterator<InputImageType> + itInput(ptr, ptr->GetLargestPossibleRegion()); + + itk::ImageRegionIterator<OutputImageType> + itOutput(outputImage, outputImage->GetLargestPossibleRegion()); + itInput.GoToBegin(); + itOutput.GoToBegin(); - /*---------------------------------------------------------------- - PrintSelf - -----------------------------------------------------------------*/ - template <class TInputImage , class TDetector, class TCount, class TOutputImage> - void - CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > - ::PrintSelf(std::ostream& os, itk::Indent indent) const + while (!itInput.IsAtEnd() && !itOutput.IsAtEnd()) { - Superclass::PrintSelf(os, indent); - os << indent << "Neighborhood Radius " << m_NeighborhoodRadius << std::endl; + IndexType index = itInput.GetIndex(); + itOutput.Set(m_CountImageFunction->EvaluateAtIndex(index)); + + ++itInput; + ++itOutput; } + +} + + +/** + * Set Detector + */ +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +void +CountImageFilter<TInputImage, TDetector, TCount, TOutputImage > +::SetDetector(DetectorType* detector) +{ + m_CountImageFunction->SetDetector(detector); +} + + +/** + * Get Detector + */ +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +typename CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > +::DetectorType * +CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > +::GetDetector() +{ + return m_CountImageFunction->GetDetector(); +} + + + +/*---------------------------------------------------------------- + PrintSelf + -----------------------------------------------------------------*/ +template <class TInputImage , class TDetector, class TCount, class TOutputImage> +void +CountImageFilter< TInputImage , TDetector, TCount, TOutputImage > +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Neighborhood Radius " << m_NeighborhoodRadius << std::endl; +} + }/** end namesapce otb*/ diff --git a/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.h b/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.h index 6139e1cb9483a6a8d8cb21ab8a0210479760a69e..6f5eeeba7913f428650082d4b55081eea39f4444 100644 --- a/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.h +++ b/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.h @@ -23,9 +23,11 @@ #include "itkEuclideanDistance.h" -namespace otb { +namespace otb +{ -namespace Statistics { +namespace Statistics +{ /** \class EuclideanDistanceWithMissingValue * \brief Euclidean distance function facing missing value. @@ -43,49 +45,51 @@ namespace Statistics { */ template< class TVector > class ITK_EXPORT EuclideanDistanceWithMissingValue : - public itk::Statistics::EuclideanDistance< TVector > + public itk::Statistics::EuclideanDistance< TVector > { - public: - /** Standard "Self" typedef. */ - typedef EuclideanDistanceWithMissingValue Self; - typedef itk::Statistics::EuclideanDistance< TVector > Superclass; - typedef itk::SmartPointer< Self > Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; +public: + /** Standard "Self" typedef. */ + typedef EuclideanDistanceWithMissingValue Self; + typedef itk::Statistics::EuclideanDistance< TVector > Superclass; + typedef itk::SmartPointer< Self > Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - /** Run-time type information (and related methods). */ - itkTypeMacro(EuclideanDistanceWithMissingValue, EuclideanDistance); + /** Run-time type information (and related methods). */ + itkTypeMacro(EuclideanDistanceWithMissingValue, EuclideanDistance); - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Type of the component of a vector */ - typedef typename TVector::ValueType ValueType; + /** Type of the component of a vector */ + typedef typename TVector::ValueType ValueType; - /** Gets the distance between the origin and x */ - double Evaluate(const TVector &x) const; + /** Gets the distance between the origin and x */ + double Evaluate(const TVector &x) const; - /** Gets the distance between x1 and x2 */ - double Evaluate(const TVector &x1, const TVector &x2) const; + /** Gets the distance between x1 and x2 */ + double Evaluate(const TVector &x1, const TVector &x2) const; - /** Gets the cooridnate distance between a and b. NOTE: a and b - * should be type of component */ - double Evaluate(const ValueType &a, const ValueType &b) const; + /** Gets the cooridnate distance between a and b. NOTE: a and b + * should be type of component */ + double Evaluate(const ValueType &a, const ValueType &b) const; - /** Returns true if the distance between x and the origin is less - * than radius */ - bool IsWithinRange(const TVector &x, const double radius) const { - return Superclass::IsWithinRange( x, radius ); } + /** Returns true if the distance between x and the origin is less + * than radius */ + bool IsWithinRange(const TVector &x, const double radius) const + { + return Superclass::IsWithinRange( x, radius ); + } - /** Check if a value is NaN or not */ - static bool IsMissingValue ( const ValueType & v); + /** Check if a value is NaN or not */ + static bool IsMissingValue ( const ValueType & v); - /** Set a value to Nan */ - static void SetToMissingValue ( ValueType & v ); + /** Set a value to Nan */ + static void SetToMissingValue ( ValueType & v ); - protected: - EuclideanDistanceWithMissingValue() {} - virtual ~EuclideanDistanceWithMissingValue() {} +protected: + EuclideanDistanceWithMissingValue() {} + virtual ~EuclideanDistanceWithMissingValue() {} }; // end of class } // end namespace statistics diff --git a/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.txx b/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.txx index b9adaaba95af0e3d8fa8678343557b39c7e2b7b4..4bfbcd336772b0c175ad88739283ddf12b74f32e 100644 --- a/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.txx +++ b/Code/BasicFilters/otbEuclideanDistanceWithMissingValue.txx @@ -24,24 +24,26 @@ #include "itkNumericTraits.h" #include "vnl/vnl_math.h" -namespace otb { +namespace otb +{ -namespace Statistics { +namespace Statistics +{ template< class TVector > inline double EuclideanDistanceWithMissingValue< TVector > ::Evaluate(const TVector &x1, const TVector &x2) const { - if( itk::MeasurementVectorTraits::GetLength( x1 ) != - itk::MeasurementVectorTraits::GetLength( x2 ) ) + if ( itk::MeasurementVectorTraits::GetLength( x1 ) != + itk::MeasurementVectorTraits::GetLength( x2 ) ) { itkExceptionMacro( << "Vector lengths must be equal." ); } double temp, distance = itk::NumericTraits< double >::Zero; - for(unsigned int i = 0; i < x1.Size(); i++ ) + for (unsigned int i = 0; i < x1.Size(); i++ ) { if ( !IsMissingValue( x1[i] ) && !IsMissingValue( x2[i] ) ) { @@ -59,17 +61,17 @@ EuclideanDistanceWithMissingValue< TVector > ::Evaluate(const TVector &x) const { MeasurementVectorSizeType - measurementVectorSize = this->GetMeasurementVectorSize(); - if(measurementVectorSize == 0) + measurementVectorSize = this->GetMeasurementVectorSize(); + if (measurementVectorSize == 0) { itkExceptionMacro( << "Please set the MeasurementVectorSize first" ); } itk::MeasurementVectorTraits::Assert( this->m_Origin, measurementVectorSize, - "EuclideanDistance::Evaluate Origin and input vector have different lengths"); + "EuclideanDistance::Evaluate Origin and input vector have different lengths"); double temp, distance = itk::NumericTraits< double >::Zero; - for(unsigned int i = 0; i < measurementVectorSize; i++ ) + for (unsigned int i = 0; i < measurementVectorSize; i++ ) { if ( !IsMissingValue( this->GetOrigin()[i] ) && !IsMissingValue( x[i] ) ) { @@ -107,7 +109,7 @@ void EuclideanDistanceWithMissingValue< TVector > ::SetToMissingValue ( ValueType & v ) { - v = vcl_numeric_limits<ValueType>::quiet_NaN(); + v = vcl_numeric_limits<ValueType>::quiet_NaN(); } diff --git a/Code/BasicFilters/otbFrostImageFilter.h b/Code/BasicFilters/otbFrostImageFilter.h index b70d9f2a7083750271e9b63c24a0654ce814ea74..4e391faffe6cd5deffc37f930f6bf6b75cc1053c 100644 --- a/Code/BasicFilters/otbFrostImageFilter.h +++ b/Code/BasicFilters/otbFrostImageFilter.h @@ -49,10 +49,10 @@ class ITK_EXPORT FrostImageFilter : public itk::ImageToImageFilter< TInputImage public: /** Extract input and output images sizes. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef to simplify variables definition and declaration. */ diff --git a/Code/BasicFilters/otbFrostImageFilter.txx b/Code/BasicFilters/otbFrostImageFilter.txx index 5bcb8624c37aaa0831cede8141200f14a6d3b9d9..97c70d9c4810e526be788f45ef1cbde86666ba84 100644 --- a/Code/BasicFilters/otbFrostImageFilter.txx +++ b/Code/BasicFilters/otbFrostImageFilter.txx @@ -54,9 +54,9 @@ void FrostImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -68,12 +68,12 @@ void FrostImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -84,20 +84,20 @@ void FrostImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << static_cast<const char *>(this->GetNameOfClass()) - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } template< class TInputImage, class TOutputImage> void FrostImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - int threadId - ) + const OutputImageRegionType& outputRegionForThread, + int threadId +) { unsigned int i; itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; @@ -135,7 +135,7 @@ void FrostImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, input, *fit); unsigned int neighborhoodSize = bit.Size(); it = itk::ImageRegionIterator<OutputImageType>(output, *fit); @@ -143,26 +143,26 @@ void FrostImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( bit.GoToBegin(); while ( ! bit.IsAtEnd() ) - { + { sum = itk::NumericTraits<InputRealType>::Zero; sum2 = itk::NumericTraits<InputRealType>::Zero; for (i = 0; i < neighborhoodSize; ++i) - { - dPixel = static_cast<double>( bit.GetPixel(i) ); - sum += dPixel; - sum2 += dPixel * dPixel; - } + { + dPixel = static_cast<double>( bit.GetPixel(i) ); + sum += dPixel; + sum2 += dPixel * dPixel; + } Mean = sum / double(neighborhoodSize); Variance = sum2 / double(neighborhoodSize) - Mean * Mean; - if(Mean == 0) - { - Alpha = 0; - } + if (Mean == 0) + { + Alpha = 0; + } else - { - Alpha = m_Deramp * Variance / (Mean * Mean); - } + { + Alpha = m_Deramp * Variance / (Mean * Mean); + } NormFilter = 0.0; FrostFilter = 0.0; @@ -171,26 +171,26 @@ void FrostImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( const double rad_y = static_cast<double>(m_Radius[1]); for (double x = -rad_x; x<= rad_x; x++) + { + for (double y = -rad_y; y <= rad_y; y++) { - for (double y = -rad_y; y <= rad_y; y++) - { - double Dist = double(vcl_sqrt(x*x+y*y)); - off[0]= static_cast<int>(x); - off[1]= static_cast<int>(y); + double Dist = double(vcl_sqrt(x*x+y*y)); + off[0]= static_cast<int>(x); + off[1]= static_cast<int>(y); // i = (unsigned int)((y+rad_y)*(2*rad_y+1)+(x+rad_x)); - dPixel= static_cast<double>( bit.GetPixel(off)); + dPixel= static_cast<double>( bit.GetPixel(off)); // dPixel= static_cast<double>( bit.GetPixel(i)); - CoefFilter = Alpha * vcl_exp(-Alpha *Dist); - NormFilter = NormFilter + CoefFilter; - FrostFilter = FrostFilter + (CoefFilter * dPixel); - } + CoefFilter = Alpha * vcl_exp(-Alpha *Dist); + NormFilter = NormFilter + CoefFilter; + FrostFilter = FrostFilter + (CoefFilter * dPixel); } + } - if (NormFilter==0.) + if (NormFilter==0.) dPixel=0.; - else - dPixel=FrostFilter/NormFilter; + else + dPixel=FrostFilter/NormFilter; it.Set( static_cast<OutputPixelType>( dPixel ) ); @@ -198,8 +198,8 @@ void FrostImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( ++it; progress.CompletedPixel(); - } } + } } /** diff --git a/Code/BasicFilters/otbFunctionToImageFilter.h b/Code/BasicFilters/otbFunctionToImageFilter.h index 8fde5f9fdf5c5c9833ae2fe441ca6c650582b643..1fc01c23cb5a94a6b592d5a5e82da88f82f636c3 100644 --- a/Code/BasicFilters/otbFunctionToImageFilter.h +++ b/Code/BasicFilters/otbFunctionToImageFilter.h @@ -53,7 +53,7 @@ namespace otb template <class TInputImage, class TOutputImage,class TFunction > class ITK_EXPORT FunctionToImageFilter : - public itk::InPlaceImageFilter<TInputImage,TOutputImage> + public itk::InPlaceImageFilter<TInputImage,TOutputImage> { public: /** Standard class typedefs. */ @@ -86,9 +86,16 @@ public: /** Connect one of the operands for pixel-wise addition. */ //void SetInput( const TInputImage *image); -/** Set the internal spatial function. */ - void SetFunction( FunctionType* PixelFunction ) {m_PixelFunction = PixelFunction; this->Modified(); }; - FunctionType* GetFunction() { return m_PixelFunction; }; + /** Set the internal spatial function. */ + void SetFunction( FunctionType* PixelFunction ) + { + m_PixelFunction = PixelFunction; + this->Modified(); + }; + FunctionType* GetFunction() + { + return m_PixelFunction; + }; /** Image dimensions */ itkStaticConstMacro(InputImageDimension, unsigned int, diff --git a/Code/BasicFilters/otbFunctionToImageFilter.txx b/Code/BasicFilters/otbFunctionToImageFilter.txx index 3dec7157db50bdd7ca7112f07b2ef0f88f6f57ce..5d7b9800be94e94cd4be2b78d623853d63c9a24b 100644 --- a/Code/BasicFilters/otbFunctionToImageFilter.txx +++ b/Code/BasicFilters/otbFunctionToImageFilter.txx @@ -65,15 +65,15 @@ FunctionToImageFilter<TInputImage,TOutputImage,TFunction> ::BeforeThreadedGenerateData() { InputImagePointer inputPtr - = dynamic_cast<const TInputImage*>((itk::ProcessObject::GetInput(0))); + = dynamic_cast<const TInputImage*>((itk::ProcessObject::GetInput(0))); if (inputPtr.IsNull()) - { - itkExceptionMacro(<< "At least one input is missing." - << " Input is missing :" << inputPtr.GetPointer();) + { + itkExceptionMacro(<< "At least one input is missing." + << " Input is missing :" << inputPtr.GetPointer();) - } + } - m_PixelFunction->SetInputImage(inputPtr); + m_PixelFunction->SetInputImage(inputPtr); } /** @@ -88,7 +88,7 @@ FunctionToImageFilter<TInputImage,TOutputImage,TFunction> // We use dynamic_cast since inputs are stored as DataObjects. InputImagePointer inputPtr - = dynamic_cast<const TInputImage*>((itk::ProcessObject::GetInput(0))); + = dynamic_cast<const TInputImage*>((itk::ProcessObject::GetInput(0))); OutputImagePointer outputPtr = this->GetOutput(0); @@ -100,14 +100,14 @@ FunctionToImageFilter<TInputImage,TOutputImage,TFunction> inputIt.GoToBegin(); outputIt.GoToBegin(); - while( !inputIt.IsAtEnd() ) - { - outputIt.Set( static_cast<OutputImagePixelType>(m_PixelFunction->EvaluateAtIndex(inputIt.GetIndex())) ); - ++inputIt; - ++outputIt; + while ( !inputIt.IsAtEnd() ) + { + outputIt.Set( static_cast<OutputImagePixelType>(m_PixelFunction->EvaluateAtIndex(inputIt.GetIndex())) ); + ++inputIt; + ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } + progress.CompletedPixel(); // potential exception thrown here + } } } // end namespace otb diff --git a/Code/BasicFilters/otbGaborFilterGenerator.h b/Code/BasicFilters/otbGaborFilterGenerator.h index acd6791d5706522051cdb4cf6b7131d9f37c6ee8..52f465169209e325e137ac2761a829e316e11759 100644 --- a/Code/BasicFilters/otbGaborFilterGenerator.h +++ b/Code/BasicFilters/otbGaborFilterGenerator.h @@ -30,119 +30,119 @@ namespace otb { - /** \class GaborFilterGenerator - * This class allows to generate gabor filter convolution mask. The mask is stored - * in a linear buffer of type itk::Array returned by the GetFilter() method. - * - * When calling the GetFilter() method, if the filter has to be regenerated, it will be - * done seamlessly. - * - * Gabor filters are commonly used in image processing for textures description for instance - * The complex Gabor function is the product in spatial domain of a complex sinusoidal, also - * known as the carrier, and a gaussian-shaped function, also knwown as the envelop. - * - * Please note that this helper class generates a filter whose coefficients are the real part - * of a complex Gabor fucntion. - * - * The formula used to compute these coefficients is as follows: - * - * \f$ g(x,y) = \exp\Big(-\pi((a x_\theta)^{2} +(b y_\theta)^{2})\Big) * \cos\big(2\pi(u_0*x + v_0*y)+\phi\big) \f$ - * - * with: - * - * \f$ x_\theta = x \cos(\theta)+y \sin(\theta) \f$ - * and - * \f$ y_\theta = y \cos(\theta)-x \sin(\theta) \f$ - * - * Where: - * - * - Radius : Radius of the generated filter (GetRadius()/SetRadius()) - * - \f$ a \f$ : Scale the x axis of the gaussian envelop. (GetA()/SetA()) - * - \f$ b \f$ : Scale the y axis of the gaussian envelop (GetB()/SetB()) - * - \f$ \theta \f$ : Rotation angle of the gaussian envelop (in degree) (GetTheta()/SetTheta()) - * - \f$ u_0 \f$ : x spatial frenquency of the sinusoidal carrier (GetU0()/SetU0()) - * - \f$ v_0 \f$ : y spatial frenquency of the sinusoidal carrier (GetV0()/SetV0()) - * - \f$ \phi \f$ : Phase of the sinusoidal carrier (GetPhi()/SetPhi()) - * - */ +/** \class GaborFilterGenerator + * This class allows to generate gabor filter convolution mask. The mask is stored + * in a linear buffer of type itk::Array returned by the GetFilter() method. + * + * When calling the GetFilter() method, if the filter has to be regenerated, it will be + * done seamlessly. + * + * Gabor filters are commonly used in image processing for textures description for instance + * The complex Gabor function is the product in spatial domain of a complex sinusoidal, also + * known as the carrier, and a gaussian-shaped function, also knwown as the envelop. + * + * Please note that this helper class generates a filter whose coefficients are the real part + * of a complex Gabor fucntion. + * + * The formula used to compute these coefficients is as follows: + * + * \f$ g(x,y) = \exp\Big(-\pi((a x_\theta)^{2} +(b y_\theta)^{2})\Big) * \cos\big(2\pi(u_0*x + v_0*y)+\phi\big) \f$ + * + * with: + * + * \f$ x_\theta = x \cos(\theta)+y \sin(\theta) \f$ + * and + * \f$ y_\theta = y \cos(\theta)-x \sin(\theta) \f$ + * + * Where: + * + * - Radius : Radius of the generated filter (GetRadius()/SetRadius()) + * - \f$ a \f$ : Scale the x axis of the gaussian envelop. (GetA()/SetA()) + * - \f$ b \f$ : Scale the y axis of the gaussian envelop (GetB()/SetB()) + * - \f$ \theta \f$ : Rotation angle of the gaussian envelop (in degree) (GetTheta()/SetTheta()) + * - \f$ u_0 \f$ : x spatial frenquency of the sinusoidal carrier (GetU0()/SetU0()) + * - \f$ v_0 \f$ : y spatial frenquency of the sinusoidal carrier (GetV0()/SetV0()) + * - \f$ \phi \f$ : Phase of the sinusoidal carrier (GetPhi()/SetPhi()) + * + */ template <class TPrecision> class GaborFilterGenerator - : public itk::Object - { - public: - // Standard class typedefs - typedef GaborFilterGenerator Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - // Standard new and type macro - itkNewMacro(Self); - itkTypeMacro(GaborFilterGenerator,Object); - - // usefull typedefs - typedef TPrecision PrecisionType; - typedef itk::Array<PrecisionType> ArrayType; - typedef itk::Size<2> RadiusType; - - /** Setters/Getters */ - itkSetMacro(A,PrecisionType); - itkGetMacro(A,PrecisionType); - itkSetMacro(B,PrecisionType); - itkGetMacro(B,PrecisionType); - itkSetMacro(Theta,PrecisionType); - itkGetMacro(Theta,PrecisionType); - itkSetMacro(Phi,PrecisionType); - itkGetMacro(Phi,PrecisionType); - itkSetMacro(U0,PrecisionType); - itkGetMacro(U0,PrecisionType); - itkSetMacro(V0,PrecisionType); - itkGetMacro(V0,PrecisionType); - itkSetMacro(Radius,RadiusType); - itkGetConstReferenceMacro(Radius,RadiusType); - - /** Get The generated filter */ - const ArrayType & GetFilter(); - - protected: - /** constructor */ - GaborFilterGenerator(); - /** destructor */ - ~GaborFilterGenerator(){} - - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Generate the filter coefficients */ - void GenerateFilter(); - - /** Reimplement the Modified() method - *to set the NeedToGenerateFilter to true */ - virtual void Modified(); - - private: - GaborFilterGenerator(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Radius of the filter */ - RadiusType m_Radius; - - /** Gabor parameters */ - PrecisionType m_A; - PrecisionType m_B; - PrecisionType m_Theta; - PrecisionType m_U0; - PrecisionType m_V0; - PrecisionType m_Phi; - - /** Output filter coefficient array */ - ArrayType m_Filter; - - /** Wether we need to regenerate the filter */ - bool m_NeedToRegenerateFilter; - - }; + : public itk::Object +{ +public: + // Standard class typedefs + typedef GaborFilterGenerator Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + // Standard new and type macro + itkNewMacro(Self); + itkTypeMacro(GaborFilterGenerator,Object); + + // usefull typedefs + typedef TPrecision PrecisionType; + typedef itk::Array<PrecisionType> ArrayType; + typedef itk::Size<2> RadiusType; + + /** Setters/Getters */ + itkSetMacro(A,PrecisionType); + itkGetMacro(A,PrecisionType); + itkSetMacro(B,PrecisionType); + itkGetMacro(B,PrecisionType); + itkSetMacro(Theta,PrecisionType); + itkGetMacro(Theta,PrecisionType); + itkSetMacro(Phi,PrecisionType); + itkGetMacro(Phi,PrecisionType); + itkSetMacro(U0,PrecisionType); + itkGetMacro(U0,PrecisionType); + itkSetMacro(V0,PrecisionType); + itkGetMacro(V0,PrecisionType); + itkSetMacro(Radius,RadiusType); + itkGetConstReferenceMacro(Radius,RadiusType); + + /** Get The generated filter */ + const ArrayType & GetFilter(); + +protected: + /** constructor */ + GaborFilterGenerator(); + /** destructor */ + ~GaborFilterGenerator() {} + + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** Generate the filter coefficients */ + void GenerateFilter(); + + /** Reimplement the Modified() method + *to set the NeedToGenerateFilter to true */ + virtual void Modified(); + +private: + GaborFilterGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Radius of the filter */ + RadiusType m_Radius; + + /** Gabor parameters */ + PrecisionType m_A; + PrecisionType m_B; + PrecisionType m_Theta; + PrecisionType m_U0; + PrecisionType m_V0; + PrecisionType m_Phi; + + /** Output filter coefficient array */ + ArrayType m_Filter; + + /** Wether we need to regenerate the filter */ + bool m_NeedToRegenerateFilter; + +}; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/BasicFilters/otbGaborFilterGenerator.txx b/Code/BasicFilters/otbGaborFilterGenerator.txx index 7e9a355820eb1d8ec391f6bf6dd108796132b4c5..0ae4becae9456f2816dda1db9fa7bbd273adc789 100644 --- a/Code/BasicFilters/otbGaborFilterGenerator.txx +++ b/Code/BasicFilters/otbGaborFilterGenerator.txx @@ -44,10 +44,10 @@ const typename GaborFilterGenerator<TPrecision> GaborFilterGenerator<TPrecision> ::GetFilter() { - if(m_NeedToRegenerateFilter) - { - this->GenerateFilter(); - } + if (m_NeedToRegenerateFilter) + { + this->GenerateFilter(); + } return m_Filter; } @@ -66,19 +66,19 @@ GaborFilterGenerator<TPrecision> sintheta = vcl_sin(m_Theta*M_PI/180.); - for(PrecisionType y = - static_cast<PrecisionType>(m_Radius[1]); - y<=static_cast<PrecisionType>(m_Radius[1]);y+=1) - { - for(PrecisionType x = - static_cast<PrecisionType>(m_Radius[0]); - x<=static_cast<PrecisionType>(m_Radius[0]);x+=1) + for (PrecisionType y = - static_cast<PrecisionType>(m_Radius[1]); + y<=static_cast<PrecisionType>(m_Radius[1]);y+=1) { - xr = x * costheta + y * sintheta; - yr = y * costheta - x * sintheta; - coef = vcl_exp(-M_PI*(vcl_pow(m_A*xr,2)+vcl_pow(m_B*yr,2)))*cos(2*M_PI*(m_U0*x+m_V0*y)+m_Phi); - m_Filter.SetElement(k,coef); - ++k; - } + for (PrecisionType x = - static_cast<PrecisionType>(m_Radius[0]); + x<=static_cast<PrecisionType>(m_Radius[0]);x+=1) + { + xr = x * costheta + y * sintheta; + yr = y * costheta - x * sintheta; + coef = vcl_exp(-M_PI*(vcl_pow(m_A*xr,2)+vcl_pow(m_B*yr,2)))*cos(2*M_PI*(m_U0*x+m_V0*y)+m_Phi); + m_Filter.SetElement(k,coef); + ++k; } + } } template <class TPrecision> diff --git a/Code/BasicFilters/otbImageListToImageListApplyFilter.h b/Code/BasicFilters/otbImageListToImageListApplyFilter.h index 08bfb97d16bbf898d71587204642f4b4f9d5acaa..1b56b8780f8874df00bbd31809b912fc693e914f 100644 --- a/Code/BasicFilters/otbImageListToImageListApplyFilter.h +++ b/Code/BasicFilters/otbImageListToImageListApplyFilter.h @@ -41,14 +41,14 @@ namespace otb */ template <class TInputImageList, class TOutputImageList, class TFilter> class ITK_EXPORT ImageListToImageListApplyFilter - : public ImageListToImageListFilter<typename TInputImageList::ImageType, - typename TOutputImageList::ImageType> + : public ImageListToImageListFilter<typename TInputImageList::ImageType, + typename TOutputImageList::ImageType> { - public: +public: /** Standard typedefs */ typedef ImageListToImageListApplyFilter Self; typedef ImageListToImageListFilter<typename TInputImageList::ImageType, - typename TOutputImageList::ImageType> Superclass; + typename TOutputImageList::ImageType> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -89,7 +89,7 @@ protected: ImageListToImageListApplyFilter(); /** Destructor */ virtual ~ImageListToImageListApplyFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/BasicFilters/otbImageListToImageListApplyFilter.txx b/Code/BasicFilters/otbImageListToImageListApplyFilter.txx index bbf872b6caa8bfa42ee581cd513ccce552a4d631..d9687a1108493d6a812090f36845215f1921f9b9 100644 --- a/Code/BasicFilters/otbImageListToImageListApplyFilter.txx +++ b/Code/BasicFilters/otbImageListToImageListApplyFilter.txx @@ -42,36 +42,36 @@ ImageListToImageListApplyFilter<TInputImageList,TOutputImageList,TFilter> // Retrieving input/output pointers InputImageListPointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); - if(outputPtr) - { - if(outputPtr->Size()!=inputPtr->Size()) + if (outputPtr) { - // in this case, clear the list - outputPtr->Clear(); - typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - while(inputListIt!=inputPtr->End()) + if (outputPtr->Size()!=inputPtr->Size()) + { + // in this case, clear the list + outputPtr->Clear(); + typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); + while (inputListIt!=inputPtr->End()) { outputPtr->PushBack(OutputImageType::New()); ++inputListIt; } - } - - // For each input image - typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); + } - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) - { - // Create the output image and set its information + // For each input image + typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); + typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); - m_Filter->SetInput(inputListIt.Get()); - m_Filter->UpdateOutputInformation(); - outputListIt.Get()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); - outputListIt.Get()->SetLargestPossibleRegion(m_Filter->GetOutput(m_OutputIndex)->GetLargestPossibleRegion()); - ++inputListIt; - ++outputListIt; - } + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + { + // Create the output image and set its information + + m_Filter->SetInput(inputListIt.Get()); + m_Filter->UpdateOutputInformation(); + outputListIt.Get()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); + outputListIt.Get()->SetLargestPossibleRegion(m_Filter->GetOutput(m_OutputIndex)->GetLargestPossibleRegion()); + ++inputListIt; + ++outputListIt; } + } } /** Generate input requested region for each image in the List. */ template <class TInputImageList, class TOutputImageList, class TFilter> @@ -79,7 +79,7 @@ void ImageListToImageListApplyFilter<TInputImageList,TOutputImageList,TFilter> ::GenerateInputRequestedRegion() { - // Retrieving input/output pointers + // Retrieving input/output pointers InputImageListPointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); @@ -88,7 +88,7 @@ ImageListToImageListApplyFilter<TInputImageList,TOutputImageList,TFilter> typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); // Use the filter to generate input requested region - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) { m_Filter->SetInput(inputListIt.Get()); m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); @@ -113,7 +113,7 @@ ImageListToImageListApplyFilter<TInputImageList,TOutputImageList,TFilter> unsigned int counter = 0; - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) { m_Filter->SetInput(inputListIt.Get()); m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); diff --git a/Code/BasicFilters/otbImageListToVectorImageFilter.h b/Code/BasicFilters/otbImageListToVectorImageFilter.h index 3d1ae244dfe51f6e7257508b19bd7ce6019f36dd..76381f671256727b325c2ce4b2694f96660900ab 100644 --- a/Code/BasicFilters/otbImageListToVectorImageFilter.h +++ b/Code/BasicFilters/otbImageListToVectorImageFilter.h @@ -35,13 +35,13 @@ namespace otb */ template <class TImageList, class TVectorImage> class ITK_EXPORT ImageListToVectorImageFilter - : public ImageListToImageFilter<typename TImageList::ImageType, TVectorImage> + : public ImageListToImageFilter<typename TImageList::ImageType, TVectorImage> { - public: +public: /** Standard typedefs */ typedef ImageListToVectorImageFilter Self; typedef ImageListToImageFilter<typename TImageList::ImageType, - TVectorImage> Superclass; + TVectorImage> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -80,7 +80,7 @@ protected: ImageListToVectorImageFilter() {}; /** Destructor */ virtual ~ImageListToVectorImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/BasicFilters/otbImageListToVectorImageFilter.txx b/Code/BasicFilters/otbImageListToVectorImageFilter.txx index 7c5942fc698108fdfab0d08ca3def5615c11dce1..05ea83e3c9dd9de506b2fac66a3dbcd963b7a09a 100644 --- a/Code/BasicFilters/otbImageListToVectorImageFilter.txx +++ b/Code/BasicFilters/otbImageListToVectorImageFilter.txx @@ -35,15 +35,15 @@ void ImageListToVectorImageFilter<TImageList,TVectorImage> ::GenerateOutputInformation(void) { - if(this->GetOutput()) - { - if(this->GetInput()->Size()>0) + if (this->GetOutput()) { - this->GetOutput()->CopyInformation(this->GetInput()->GetNthElement(0)); - this->GetOutput()->SetNumberOfComponentsPerPixel(this->GetInput()->Size()); - this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetNthElement(0)->GetLargestPossibleRegion()); - } + if (this->GetInput()->Size()>0) + { + this->GetOutput()->CopyInformation(this->GetInput()->GetNthElement(0)); + this->GetOutput()->SetNumberOfComponentsPerPixel(this->GetInput()->Size()); + this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetNthElement(0)->GetLargestPossibleRegion()); } + } } /** * GenerateInputRequestedRegion @@ -55,11 +55,11 @@ ImageListToVectorImageFilter<TImageList,TVectorImage> { InputImageListPointerType inputPtr = this->GetInput(); typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - while(inputListIt!=inputPtr->End()) - { - inputListIt.Get()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); - ++inputListIt; - } + while (inputListIt!=inputPtr->End()) + { + inputListIt.Get()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); + ++inputListIt; + } } /** * Main computation method @@ -94,35 +94,35 @@ ImageListToVectorImageFilter<TImageList,TVectorImage> InputIteratorListType inputIteratorList; // fills the vector of input iterators - for(;inputListIt!=inputPtr->End();++inputListIt) - { - inputIteratorList.push_back(InputIteratorType(inputListIt.Get(),outputPtr->GetRequestedRegion())); - inputIteratorList.back().GoToBegin(); - } + for (;inputListIt!=inputPtr->End();++inputListIt) + { + inputIteratorList.push_back(InputIteratorType(inputListIt.Get(),outputPtr->GetRequestedRegion())); + inputIteratorList.back().GoToBegin(); + } // walk through the output image OutputIteratorType outputIt(outputPtr,outputPtr->GetRequestedRegion()); outputIt.GoToBegin(); - while(!outputIt.IsAtEnd()) - { - typename OutputVectorImageType::PixelType pixel = outputIt.Get(); - unsigned int counter = 0; - // for each input iterator, fill the right component - for(typename InputIteratorListType::iterator it = inputIteratorList.begin(); - it != inputIteratorList.end();++it) + while (!outputIt.IsAtEnd()) { - if(!it->IsAtEnd()) - { + typename OutputVectorImageType::PixelType pixel = outputIt.Get(); + unsigned int counter = 0; + // for each input iterator, fill the right component + for (typename InputIteratorListType::iterator it = inputIteratorList.begin(); + it != inputIteratorList.end();++it) + { + if (!it->IsAtEnd()) + { pixel[counter]=static_cast<typename OutputVectorImageType::InternalPixelType>(it->Get()); ++(*it); ++counter; - } - } - outputIt.Set(pixel); - progress.CompletedPixel(); - ++outputIt; + } } + outputIt.Set(pixel); + progress.CompletedPixel(); + ++outputIt; + } } /** * PrintSelf Method diff --git a/Code/BasicFilters/otbImageToPointSetFilter.txx b/Code/BasicFilters/otbImageToPointSetFilter.txx index df56a48e4fdc06130abce0cd868534190decc134..c3339697490ee3fff3ff8d09e0587cb89ea2107e 100644 --- a/Code/BasicFilters/otbImageToPointSetFilter.txx +++ b/Code/BasicFilters/otbImageToPointSetFilter.txx @@ -34,7 +34,7 @@ ImageToPointSetFilter<TInputImage,TOutputPointSet> this->ProcessObjectType::SetNumberOfRequiredInputs(1); OutputPointSetPointer output - = dynamic_cast<OutputPointSetType*>(this->MakeOutput(0).GetPointer()); + = dynamic_cast<OutputPointSetType*>(this->MakeOutput(0).GetPointer()); ProcessObjectType::SetNumberOfRequiredOutputs(1); ProcessObjectType::SetNthOutput(0, output.GetPointer()); @@ -61,7 +61,7 @@ ImageToPointSetFilter<TInputImage,TOutputPointSet> // process object is not const-correct, the const_cast // is required here. this->ProcessObjectType::SetNthInput(idx, - const_cast< InputImageType * >(input) ); + const_cast< InputImageType * >(input) ); } /** * @@ -74,7 +74,7 @@ ImageToPointSetFilter<TInputImage,TOutputPointSet> // process object is not const-correct, the const_cast // is required here. this->ProcessObjectType::SetNthInput(0, - const_cast< InputImageType * >(input) ); + const_cast< InputImageType * >(input) ); } @@ -87,9 +87,9 @@ const typename ImageToPointSetFilter<TInputImage,TOutputPointSet>::InputImageTyp ImageToPointSetFilter<TInputImage,TOutputPointSet> ::GetInput(unsigned int idx) { - + return dynamic_cast<const InputImageType*> - (this->ProcessObjectType::GetInput(idx)); + (this->ProcessObjectType::GetInput(idx)); } /** @@ -100,11 +100,11 @@ const typename ImageToPointSetFilter<TInputImage,TOutputPointSet>::InputImageTyp ImageToPointSetFilter<TInputImage,TOutputPointSet> ::GetInput(void) { - if(this->GetNumberOfInputs() < 1) + if (this->GetNumberOfInputs() < 1) return 0; - + return dynamic_cast<const InputImageType*> - (this->ProcessObjectType::GetInput(0)); + (this->ProcessObjectType::GetInput(0)); } /** diff --git a/Code/BasicFilters/otbImportGeoInformationImageFilter.h b/Code/BasicFilters/otbImportGeoInformationImageFilter.h index 94a31e0fd5ddd753212944808bba02a8fcb20dec..63c42e78a01c79e823142440c4e311e9b14685df 100644 --- a/Code/BasicFilters/otbImportGeoInformationImageFilter.h +++ b/Code/BasicFilters/otbImportGeoInformationImageFilter.h @@ -36,9 +36,9 @@ namespace otb */ template <class TImage, class TSourceImage> class ITK_EXPORT ImportGeoInformationImageFilter - : public itk::CastImageFilter<TImage,TImage> + : public itk::CastImageFilter<TImage,TImage> { - public: +public: /** Standard typedefs */ typedef ImportGeoInformationImageFilter Self; typedef itk::CastImageFilter<TImage,TImage> Superclass; @@ -74,14 +74,14 @@ protected: ImportGeoInformationImageFilter(); /** Destructor */ virtual ~ImportGeoInformationImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Generate input requested region */ virtual void GenerateInputRequestedRegion(void); /** Generate output information */ virtual void GenerateOutputInformation(void); -/* /\** Generate data *\/ */ -/* virtual void GenerateData(void); */ + /* /\** Generate data *\/ */ + /* virtual void GenerateData(void); */ private: ImportGeoInformationImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/BasicFilters/otbImportGeoInformationImageFilter.txx b/Code/BasicFilters/otbImportGeoInformationImageFilter.txx index 42f367d7b59b3662ede243d8b8f371cee31af1ea..c59941cc50bf8d5e9a09b7360ea9f0d4c0e052af 100644 --- a/Code/BasicFilters/otbImportGeoInformationImageFilter.txx +++ b/Code/BasicFilters/otbImportGeoInformationImageFilter.txx @@ -53,7 +53,7 @@ ImportGeoInformationImageFilter<TImage,TSourceImage> template <class TImage, class TSourceImage> void - ImportGeoInformationImageFilter<TImage,TSourceImage> +ImportGeoInformationImageFilter<TImage,TSourceImage> ::GenerateInputRequestedRegion(void) { Superclass::GenerateInputRequestedRegion(); @@ -73,7 +73,7 @@ void template <class TImage, class TSourceImage> void - ImportGeoInformationImageFilter<TImage,TSourceImage> +ImportGeoInformationImageFilter<TImage,TSourceImage> ::GenerateOutputInformation(void) { Superclass::GenerateOutputInformation(); diff --git a/Code/BasicFilters/otbImportImageFilter.h b/Code/BasicFilters/otbImportImageFilter.h index e4cf1edf32aeba8330fd58fde50bec05f49d9b90..a394ec83e2367b76f99f1c177313b31dec194239 100644 --- a/Code/BasicFilters/otbImportImageFilter.h +++ b/Code/BasicFilters/otbImportImageFilter.h @@ -40,7 +40,7 @@ namespace otb template <typename TOutputImageType> class ITK_EXPORT ImportImageFilter: - public itk::ImageSource< TOutputImageType > + public itk::ImageSource< TOutputImageType > { public: /** Typedef for the output image. */ @@ -93,14 +93,22 @@ public: * the BufferedRegion, and the RequestedRegion. * \sa ImageRegion */ void SetRegion(const RegionType ®ion) - { if (m_Region != region) {m_Region = region; this->Modified();} }; + { + if (m_Region != region) + { + m_Region = region; + this->Modified(); + } + }; /** Get the region object that defines the size and starting index * for the imported image. This will serve as the LargestPossibleRegion, * the BufferedRegion, and the RequestedRegion. * \sa ImageRegion */ const RegionType& GetRegion() const - { return m_Region;}; + { + return m_Region; + }; /** Set the spacing (size of a pixel) of the image. * \sa GetSpacing() */ diff --git a/Code/BasicFilters/otbImportImageFilter.txx b/Code/BasicFilters/otbImportImageFilter.txx index 1916b2ecb8d50b122586a3151e6ce2e4385350c8..5de383ede580220b5f2ac637bc7411411486d1c8 100644 --- a/Code/BasicFilters/otbImportImageFilter.txx +++ b/Code/BasicFilters/otbImportImageFilter.txx @@ -37,10 +37,10 @@ ImportImageFilter<TOutputImage> unsigned int idx; for (idx = 0; idx < TOutputImage::ImageDimension; ++idx) - { + { m_Spacing[idx] = 1.0; m_Origin[idx] = 0.0; - } + } m_Direction.SetIdentity(); m_ImportPointer = 0; @@ -56,9 +56,9 @@ ImportImageFilter<TOutputImage> ::~ImportImageFilter() { if (m_ImportPointer && m_FilterManageMemory) - { + { delete [] m_ImportPointer; - } + } } @@ -75,29 +75,29 @@ ImportImageFilter<TOutputImage> Superclass::PrintSelf(os,indent); if (m_ImportPointer) - { + { os << indent << "Imported pointer: (" << m_ImportPointer << ")" << std::endl; - } + } else - { + { os << indent << "Imported pointer: (None)" << std::endl; - } + } os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Filter manages memory: " << (m_FilterManageMemory ? "true" : "false") << std::endl; os << indent << "Spacing: ["; for (i=0; i < static_cast<int>(TOutputImage::ImageDimension) - 1; i++) - { + { os << m_Spacing[i] << ", "; - } + } os << m_Spacing[i] << "]" << std::endl; os << indent << "Origin: ["; for (i=0; i < static_cast<int>(TOutputImage::ImageDimension) - 1; i++) - { + { os << m_Origin[i] << ", "; - } + } os << m_Origin[i] << "]" << std::endl; os << indent << "Direction: " << std::endl << this->GetDirection() << std::endl; } @@ -112,14 +112,14 @@ ImportImageFilter<TOutputImage> ::SetImportPointer(TPixel *ptr, unsigned long num, bool LetFilterManageMemory) { if (ptr != m_ImportPointer) - { + { if (m_ImportPointer && m_FilterManageMemory) - { + { delete [] m_ImportPointer; - } + } m_ImportPointer = ptr; this->Modified(); - } + } m_FilterManageMemory = LetFilterManageMemory; m_Size = num; } @@ -205,7 +205,7 @@ ImportImageFilter<TOutputImage> // memory itself. This filter will properly manage the memory (as // opposed to the container) if the user wants it to. outputPtr->GetPixelContainer()->SetImportPointer( m_ImportPointer, - m_Size, false ); + m_Size, false ); } @@ -218,10 +218,10 @@ ImportImageFilter<TOutputImage> ::SetSpacing( const SpacingType & spacing ) { double dspacing[TOutputImage::ImageDimension]; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { dspacing[i] = spacing[i]; - } + } this->SetSpacing( dspacing ); } @@ -235,10 +235,10 @@ ImportImageFilter<TOutputImage> ::SetOrigin( const OriginType & origin ) { double dorigin[TOutputImage::ImageDimension]; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { dorigin[i] = origin[i]; - } + } this->SetOrigin( dorigin ); } @@ -250,20 +250,20 @@ ImportImageFilter<TOutputImage> { bool modified = false; for (unsigned int r = 0; r < TOutputImage::ImageDimension; r++) - { + { for (unsigned int c = 0; c < TOutputImage::ImageDimension; c++) - { + { if (m_Direction[r][c] != direction[r][c]) - { + { m_Direction[r][c] = direction[r][c]; modified = true; - } } } + } if (modified) - { + { this->Modified(); - } + } } diff --git a/Code/BasicFilters/otbImportVectorImageFilter.h b/Code/BasicFilters/otbImportVectorImageFilter.h index 9b38d1a3ebfa05839cc351a5d879220748a4bd20..cc1c43bbd1b82236bb493f0ed1827ce694abe226 100644 --- a/Code/BasicFilters/otbImportVectorImageFilter.h +++ b/Code/BasicFilters/otbImportVectorImageFilter.h @@ -40,7 +40,7 @@ namespace otb template <typename TOutputImageType> class ITK_EXPORT ImportVectorImageFilter: - public itk::ImageSource< TOutputImageType > + public itk::ImageSource< TOutputImageType > { public: /** Typedef for the output image. */ @@ -88,21 +88,29 @@ public: * data. If "LetFilterManageMemory" is true, then this class * will free the memory when this object is destroyed. */ virtual void SetImportPointer(TPixel *ptr, unsigned long num, - bool LetFilterManageMemory); + bool LetFilterManageMemory); /** Set the region object that defines the size and starting index * for the imported image. This will serve as the LargestPossibleRegion, * the BufferedRegion, and the RequestedRegion. * \sa ImageRegion */ void SetRegion(const RegionType ®ion) - { if (m_Region != region) {m_Region = region; this->Modified();} }; + { + if (m_Region != region) + { + m_Region = region; + this->Modified(); + } + }; /** Get the region object that defines the size and starting index * for the imported image. This will serve as the LargestPossibleRegion, * the BufferedRegion, and the RequestedRegion. * \sa ImageRegion */ const RegionType& GetRegion() const - { return m_Region;}; + { + return m_Region; + }; /** Set the spacing (size of a pixel) of the image. * \sa GetSpacing() */ diff --git a/Code/BasicFilters/otbImportVectorImageFilter.txx b/Code/BasicFilters/otbImportVectorImageFilter.txx index 50590e534a17f406971e6786dc8f5dbd4a02c903..03334984805f32ce73f0b8f2eee0a9e3028d38f5 100644 --- a/Code/BasicFilters/otbImportVectorImageFilter.txx +++ b/Code/BasicFilters/otbImportVectorImageFilter.txx @@ -37,10 +37,10 @@ ImportVectorImageFilter<TOutputImage> unsigned int idx; for (idx = 0; idx < TOutputImage::ImageDimension; ++idx) - { + { m_Spacing[idx] = 1.0; m_Origin[idx] = 0.0; - } + } m_Direction.SetIdentity(); m_ImportPointer = 0; @@ -56,9 +56,9 @@ ImportVectorImageFilter<TOutputImage> ::~ImportVectorImageFilter() { if (m_ImportPointer && m_FilterManageMemory) - { + { delete [] m_ImportPointer; - } + } } @@ -75,29 +75,29 @@ ImportVectorImageFilter<TOutputImage> Superclass::PrintSelf(os,indent); if (m_ImportPointer) - { + { os << indent << "Imported pointer: (" << m_ImportPointer << ")" << std::endl; - } + } else - { + { os << indent << "Imported pointer: (None)" << std::endl; - } + } os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Filter manages memory: " << (m_FilterManageMemory ? "true" : "false") << std::endl; os << indent << "Spacing: ["; for (i=0; i < static_cast<int>(TOutputImage::ImageDimension) - 1; i++) - { + { os << m_Spacing[i] << ", "; - } + } os << m_Spacing[i] << "]" << std::endl; os << indent << "Origin: ["; for (i=0; i < static_cast<int>(TOutputImage::ImageDimension) - 1; i++) - { + { os << m_Origin[i] << ", "; - } + } os << m_Origin[i] << "]" << std::endl; os << indent << "Direction: " << std::endl << this->GetDirection() << std::endl; } @@ -113,14 +113,14 @@ ImportVectorImageFilter<TOutputImage> ::SetImportPointer(TPixel *ptr, unsigned long num, bool LetFilterManageMemory) { if (ptr != m_ImportPointer) - { + { if (m_ImportPointer && m_FilterManageMemory) - { + { delete [] m_ImportPointer; - } + } m_ImportPointer = ptr; this->Modified(); - } + } m_FilterManageMemory = LetFilterManageMemory; m_Size = num; } @@ -186,7 +186,7 @@ ImportVectorImageFilter<TOutputImage> if (numberOfBands!=static_cast<int>(numberOfBands)) itkExceptionMacro(<<"Buffer size and image size are not compatible !"); - outputPtr->SetNumberOfComponentsPerPixel(numberOfBands); + outputPtr->SetNumberOfComponentsPerPixel(numberOfBands); } @@ -215,7 +215,7 @@ ImportVectorImageFilter<TOutputImage> // memory itself. This filter will properly manage the memory (as // opposed to the container) if the user wants it to. outputPtr->GetPixelContainer()->SetImportPointer( m_ImportPointer, - m_Size, false ); + m_Size, false ); } @@ -229,10 +229,10 @@ ImportVectorImageFilter<TOutputImage> ::SetSpacing( const SpacingType & spacing ) { double dspacing[TOutputImage::ImageDimension]; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { dspacing[i] = spacing[i]; - } + } this->SetSpacing( dspacing ); } @@ -246,10 +246,10 @@ ImportVectorImageFilter<TOutputImage> ::SetOrigin( const OriginType & origin ) { double dorigin[TOutputImage::ImageDimension]; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { dorigin[i] = origin[i]; - } + } this->SetOrigin( dorigin ); } @@ -261,20 +261,20 @@ ImportVectorImageFilter<TOutputImage> { bool modified = false; for (unsigned int r = 0; r < TOutputImage::ImageDimension; r++) - { + { for (unsigned int c = 0; c < TOutputImage::ImageDimension; c++) - { + { if (m_Direction[r][c] != direction[r][c]) - { + { m_Direction[r][c] = direction[r][c]; modified = true; - } } } + } if (modified) - { + { this->Modified(); - } + } } diff --git a/Code/BasicFilters/otbInverseLogPolarTransform.h b/Code/BasicFilters/otbInverseLogPolarTransform.h index 047ff4e535a1977d4cbae1fa02eb005593022fae..951a34b9ae2992414987adaa76420cdaad08283a 100644 --- a/Code/BasicFilters/otbInverseLogPolarTransform.h +++ b/Code/BasicFilters/otbInverseLogPolarTransform.h @@ -22,102 +22,102 @@ namespace otb { - /** \class InverseLogPolarTransform - * \brief This transform is the back transform of the LogPolarTransform. - * - * Given (x,y) the coordinates of a point in cartesian system, the corresponding - * log-polar coordinates are : - * \f$ \rho = 1/2*log((x-xc)^2+(y+yc)^2) \f$ - * \f$ \theta = asin(y-yc)/(\sqrt{(x-xc)^2+(y+yc)^2}) \f$ - * - * In this implemenatation, theta is expressed in degree, and the result of the asin function - * is clamped to the [0,360] range. Please note that since the transform of the center has no meaning - * it is rejected to the point [400,0], which does not belong to this range. This is done to provide - * a coordinate not likely to belong to a log-polar image buffer. - * - * \sa LogPolarTransform - * \ingroup Transform - */ +/** \class InverseLogPolarTransform + * \brief This transform is the back transform of the LogPolarTransform. + * + * Given (x,y) the coordinates of a point in cartesian system, the corresponding + * log-polar coordinates are : + * \f$ \rho = 1/2*log((x-xc)^2+(y+yc)^2) \f$ + * \f$ \theta = asin(y-yc)/(\sqrt{(x-xc)^2+(y+yc)^2}) \f$ + * + * In this implemenatation, theta is expressed in degree, and the result of the asin function + * is clamped to the [0,360] range. Please note that since the transform of the center has no meaning + * it is rejected to the point [400,0], which does not belong to this range. This is done to provide + * a coordinate not likely to belong to a log-polar image buffer. + * + * \sa LogPolarTransform + * \ingroup Transform + */ template <class TScalarType> class ITK_EXPORT InverseLogPolarTransform - : public itk::Transform<TScalarType,2,2> - { - public: - /** Standard typedef */ - typedef InverseLogPolarTransform Self; - typedef itk::Transform<TScalarType,2,2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory */ - itkNewMacro(Self); - /** Runtime information */ - itkTypeMacro(InverseLogPolarTransform,Transform); - - /** Template related typedefs */ - typedef TScalarType ScalarType; - - /** Superclass related typedefs */ - 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::ParametersType ParametersType; - typedef itk::FixedArray<TScalarType,2> ScaleType; - - /** Set/Get the origin */ - itkSetMacro(Center,InputPointType); - itkGetConstReferenceMacro(Center,InputPointType); - - /** Set/Get the scales */ - itkSetMacro(Scale,ScaleType); - itkGetConstReferenceMacro(Scale,ScaleType); - /** - * Set the transform parameters through the standard interface. - * \param parameters The parameters of the transform. - */ - void SetParameters(const ParametersType ¶meters); - /** - * Get the transform parameters through the standard interface. - * \return The parameters of the transform. - */ - virtual ParametersType& GetParameters(void) const; - /** - * Transform a point. - * \param point The point to transform. - * \return The transformed point. - */ - OutputPointType TransformPoint(const InputPointType &point) const; - /** - * Transform a vector representing a point. - * \param vector The point to transform. - * \return The transformed point. - */ - OutputVectorType TransformVector(const InputVectorType &vector) const; - /** - * Transform a vnl vector representing a point. - * \param vector The point to transform. - * \return The transformed point. - */ - OutputVnlVectorType TransformVector(const InputVnlVectorType &vector) const; - - protected: - /** Constructor */ - InverseLogPolarTransform(); - /** Destructor */ - ~InverseLogPolarTransform(); - /** PrintSelf method */ - void PrintSelf(std::ostream &os,itk::Indent indent) const; - - private: - InverseLogPolarTransform(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - - InputPointType m_Center; - ScaleType m_Scale; - }; + : public itk::Transform<TScalarType,2,2> +{ +public: + /** Standard typedef */ + typedef InverseLogPolarTransform Self; + typedef itk::Transform<TScalarType,2,2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory */ + itkNewMacro(Self); + /** Runtime information */ + itkTypeMacro(InverseLogPolarTransform,Transform); + + /** Template related typedefs */ + typedef TScalarType ScalarType; + + /** Superclass related typedefs */ + 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::ParametersType ParametersType; + typedef itk::FixedArray<TScalarType,2> ScaleType; + + /** Set/Get the origin */ + itkSetMacro(Center,InputPointType); + itkGetConstReferenceMacro(Center,InputPointType); + + /** Set/Get the scales */ + itkSetMacro(Scale,ScaleType); + itkGetConstReferenceMacro(Scale,ScaleType); + /** + * Set the transform parameters through the standard interface. + * \param parameters The parameters of the transform. + */ + void SetParameters(const ParametersType ¶meters); + /** + * Get the transform parameters through the standard interface. + * \return The parameters of the transform. + */ + virtual ParametersType& GetParameters(void) const; + /** + * Transform a point. + * \param point The point to transform. + * \return The transformed point. + */ + OutputPointType TransformPoint(const InputPointType &point) const; + /** + * Transform a vector representing a point. + * \param vector The point to transform. + * \return The transformed point. + */ + OutputVectorType TransformVector(const InputVectorType &vector) const; + /** + * Transform a vnl vector representing a point. + * \param vector The point to transform. + * \return The transformed point. + */ + OutputVnlVectorType TransformVector(const InputVnlVectorType &vector) const; + +protected: + /** Constructor */ + InverseLogPolarTransform(); + /** Destructor */ + ~InverseLogPolarTransform(); + /** PrintSelf method */ + void PrintSelf(std::ostream &os,itk::Indent indent) const; + +private: + InverseLogPolarTransform(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + + InputPointType m_Center; + ScaleType m_Scale; +}; }// end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbInverseLogPolarTransform.txx" diff --git a/Code/BasicFilters/otbInverseLogPolarTransform.txx b/Code/BasicFilters/otbInverseLogPolarTransform.txx index 54ebdcff11fcc3e874b172a686770b35ff23c8cb..eb3aa7ad8c79ee22e6cda3369f4610312ab4fe47 100644 --- a/Code/BasicFilters/otbInverseLogPolarTransform.txx +++ b/Code/BasicFilters/otbInverseLogPolarTransform.txx @@ -31,7 +31,7 @@ namespace otb template <class TScalarType> InverseLogPolarTransform<TScalarType> ::InverseLogPolarTransform() - :Superclass(2,4) + :Superclass(2,4) { m_Center[0]=0.0; m_Center[1]=0.0; @@ -89,32 +89,32 @@ InverseLogPolarTransform<TScalarType> template <class TScalarType> typename InverseLogPolarTransform<TScalarType> ::OutputPointType - InverseLogPolarTransform<TScalarType> +InverseLogPolarTransform<TScalarType> ::TransformPoint(const InputPointType &point) const { OutputPointType result; double rho =vcl_sqrt(vcl_pow(point[0]-m_Center[0],2)+vcl_pow(point[1]-m_Center[1],2)); - if(rho>0) - { - result[0]=(1./m_Scale[0])*vcl_asin((point[1]-m_Center[1])/rho); - // degree conversion - result[0]=result[0]*(180./M_PI); - // Deplacing the range to [0,90], [270,360] - result[0]= result[0]>0. ? result[0] : result[0]+360.; - // Avoiding asin indetermination - if((point[0]-m_Center[0])>=0) + if (rho>0) { - result[0]=result[0]<90. ? result[0]+90. : result[0]-90.; - } - result[1]=(1./m_Scale[1])*vcl_log(rho); - // otbMsgDebugMacro(<<vcl_log(vcl_pow(point[0]-m_Center[0],2)+vcl_pow(point[1]-m_Center[1],2))); - } - else + result[0]=(1./m_Scale[0])*vcl_asin((point[1]-m_Center[1])/rho); + // degree conversion + result[0]=result[0]*(180./M_PI); + // Deplacing the range to [0,90], [270,360] + result[0]= result[0]>0. ? result[0] : result[0]+360.; + // Avoiding asin indetermination + if ((point[0]-m_Center[0])>=0) { - // for rho=0, reject the point outside the angular range to avoid nan error - result[0]=400.; - result[1]=0.; + result[0]=result[0]<90. ? result[0]+90. : result[0]-90.; } + result[1]=(1./m_Scale[1])*vcl_log(rho); + // otbMsgDebugMacro(<<vcl_log(vcl_pow(point[0]-m_Center[0],2)+vcl_pow(point[1]-m_Center[1],2))); + } + else + { + // for rho=0, reject the point outside the angular range to avoid nan error + result[0]=400.; + result[1]=0.; + } return result; } /** @@ -129,28 +129,28 @@ InverseLogPolarTransform<TScalarType> ::TransformVector(const InputVectorType &vector) const { OutputVectorType result; - double rho =vcl_sqrt(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2)); - if(rho>0) - { - result[0]=(1/m_Scale[0])*vcl_asin((vector[1]-m_Center[1])/rho); - // degree conversion - result[0]=result[0]*(180/M_PI); - // Deplacing the range to [0,90], [270,360] - result[0]= result[0]>0 ? result[0] : result[0]+360; - // Avoiding asin indetermination - if((vector[0]-m_Center[0])>=0) + double rho =vcl_sqrt(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2)); + if (rho>0) { - result[0]=result[0]<90 ? result[0]+90 : result[0]-90; - } - result[1]=(1/m_Scale[1])*vcl_log(rho); - // otbMsgDebugMacro(<<vcl_log(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2))); - } - else + result[0]=(1/m_Scale[0])*vcl_asin((vector[1]-m_Center[1])/rho); + // degree conversion + result[0]=result[0]*(180/M_PI); + // Deplacing the range to [0,90], [270,360] + result[0]= result[0]>0 ? result[0] : result[0]+360; + // Avoiding asin indetermination + if ((vector[0]-m_Center[0])>=0) { - // for rho=0, reject the vector outside the angular range to avoid nan error - result[0]=400; - result[1]=0; + result[0]=result[0]<90 ? result[0]+90 : result[0]-90; } + result[1]=(1/m_Scale[1])*vcl_log(rho); + // otbMsgDebugMacro(<<vcl_log(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2))); + } + else + { + // for rho=0, reject the vector outside the angular range to avoid nan error + result[0]=400; + result[1]=0; + } return result; } /** @@ -166,27 +166,27 @@ InverseLogPolarTransform<TScalarType> { OutputVnlVectorType result; double rho =vcl_sqrt(vcl_pow(vector[0],2)+vcl_pow(vector[1],2)); - if(rho>0) - { - result[0]=(1/m_Scale[0])*vcl_asin((vector[1]-m_Center[1])/rho); - // degree conversion - result[0]=result[0]*(180/M_PI); - // Deplacing the range to [0,90], [270,360] - result[0]= result[0]>0 ? result[0] : result[0]+360; - // Avoiding vcl_asin indetermination - if((vector[0]-m_Center[0])>=0) + if (rho>0) { - result[0]=result[0]<90 ? result[0]+90 : result[0]-90; - } - result[1]=(1/m_Scale[1])*vcl_log(rho); - // otbMsgDebugMacro(<<log(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2))); - } - else + result[0]=(1/m_Scale[0])*vcl_asin((vector[1]-m_Center[1])/rho); + // degree conversion + result[0]=result[0]*(180/M_PI); + // Deplacing the range to [0,90], [270,360] + result[0]= result[0]>0 ? result[0] : result[0]+360; + // Avoiding vcl_asin indetermination + if ((vector[0]-m_Center[0])>=0) { - // for rho=0, reject the vector outside the angular range to avoid nan error - result[0]=400; - result[1]=0; + result[0]=result[0]<90 ? result[0]+90 : result[0]-90; } + result[1]=(1/m_Scale[1])*vcl_log(rho); + // otbMsgDebugMacro(<<log(vcl_pow(vector[0]-m_Center[0],2)+vcl_pow(vector[1]-m_Center[1],2))); + } + else + { + // for rho=0, reject the vector outside the angular range to avoid nan error + result[0]=400; + result[1]=0; + } return result; } /** diff --git a/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.h b/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.h index d164bd105212a1f91618c9d5ba2442278f1d8021..48671fc29633d2fe202db514a0da6c7c741c9b55 100644 --- a/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.h +++ b/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.h @@ -24,83 +24,95 @@ namespace otb { - /** \class LabelizeConfidenceConnectedImageFilter - * \brief Labels pixels with similar statistics using connectivity - * - * This class implements abstract class otb::LabelizeImageFilterBase - * \see itk::ConfidenceConnectedImageFilter - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT LabelizeConfidenceConnectedImageFilter - : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::ConfidenceConnectedImageFilter<TInputImage, TOutputImage> > - { - public: - /** typedef for standard classes. */ - typedef LabelizeConfidenceConnectedImageFilter Self; - typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::ConfidenceConnectedImageFilter<TInputImage, TOutputImage> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** typedef to simplify variables definition and declaration. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - - typedef typename TInputImage::PixelType InputPixelType; - typedef typename TOutputImage::PixelType OutputPixelType; - typedef typename TInputImage::IndexType IndexType; - - /** "object factory" management method. */ - itkNewMacro(Self); - - /** Return the class name. */ - itkTypeMacro(LabelizeConfidenceConnectedImageFilter, LabelizeImageFilterBase); - - /** Get multiplier */ - double& GetMultiplier() const - { return this->m_RegionGrowingFilter->GetMultiplier(); } - - /** Set multiplier */ - void SetMultiplier(const double multiplier) - { this->m_RegionGrowingFilter->SetMultiplier(multiplier); } - - /** Get number of iterations */ - unsigned int& GetNumberOfIterations() const - { return this->m_RegionGrowingFilter->GetNumberOfIterations(); } - - /** Set number of iterations */ - void SetNumberOfIterations( const unsigned int iteration ) - { this->m_RegionGrowingFilter->SetNumberOfIterations(iteration); } - - /** Get replace value */ - itkGetMacro(ReplaceValue, OutputPixelType); - - /** Set replace value */ - itkSetMacro(ReplaceValue, OutputPixelType); - - /** Set initial neigborhood radius */ - const unsigned int& GetInitialNeighborhoodRadius() - { return this->m_RegionGrowingFilter->GetInitialNeighborhoodRadius(); } - - /** Set initial neigborhood radius */ - void SetInitialNeighborhoodRadius(const unsigned int initial ) - { this->m_RegionGrowingFilter->SetInitialNeighborhoodRadius(initial); } - - protected: - LabelizeConfidenceConnectedImageFilter(); - virtual ~LabelizeConfidenceConnectedImageFilter() {}; - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Region growing */ - virtual void RegionGrowing( const IndexType indexSeed ); - - private: - LabelizeConfidenceConnectedImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Intial replace value*/ - OutputPixelType m_ReplaceValue; - - }; // end class LabelizeconnectedThresholdImageFilter +/** \class LabelizeConfidenceConnectedImageFilter + * \brief Labels pixels with similar statistics using connectivity + * + * This class implements abstract class otb::LabelizeImageFilterBase + * \see itk::ConfidenceConnectedImageFilter + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT LabelizeConfidenceConnectedImageFilter + : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::ConfidenceConnectedImageFilter<TInputImage, TOutputImage> > +{ +public: + /** typedef for standard classes. */ + typedef LabelizeConfidenceConnectedImageFilter Self; + typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::ConfidenceConnectedImageFilter<TInputImage, TOutputImage> > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** typedef to simplify variables definition and declaration. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TOutputImage::PixelType OutputPixelType; + typedef typename TInputImage::IndexType IndexType; + + /** "object factory" management method. */ + itkNewMacro(Self); + + /** Return the class name. */ + itkTypeMacro(LabelizeConfidenceConnectedImageFilter, LabelizeImageFilterBase); + + /** Get multiplier */ + double& GetMultiplier() const + { + return this->m_RegionGrowingFilter->GetMultiplier(); + } + + /** Set multiplier */ + void SetMultiplier(const double multiplier) + { + this->m_RegionGrowingFilter->SetMultiplier(multiplier); + } + + /** Get number of iterations */ + unsigned int& GetNumberOfIterations() const + { + return this->m_RegionGrowingFilter->GetNumberOfIterations(); + } + + /** Set number of iterations */ + void SetNumberOfIterations( const unsigned int iteration ) + { + this->m_RegionGrowingFilter->SetNumberOfIterations(iteration); + } + + /** Get replace value */ + itkGetMacro(ReplaceValue, OutputPixelType); + + /** Set replace value */ + itkSetMacro(ReplaceValue, OutputPixelType); + + /** Set initial neigborhood radius */ + const unsigned int& GetInitialNeighborhoodRadius() + { + return this->m_RegionGrowingFilter->GetInitialNeighborhoodRadius(); + } + + /** Set initial neigborhood radius */ + void SetInitialNeighborhoodRadius(const unsigned int initial ) + { + this->m_RegionGrowingFilter->SetInitialNeighborhoodRadius(initial); + } + +protected: + LabelizeConfidenceConnectedImageFilter(); + virtual ~LabelizeConfidenceConnectedImageFilter() {}; + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** Region growing */ + virtual void RegionGrowing( const IndexType indexSeed ); + +private: + LabelizeConfidenceConnectedImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Intial replace value*/ + OutputPixelType m_ReplaceValue; + +}; // end class LabelizeconnectedThresholdImageFilter } // end namespace otb diff --git a/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.txx b/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.txx index 6152dfd45365c23179f1c3565f7b070f1355c5cc..da55ed3408e3d89327bd6a29417e774ec0ecb83b 100644 --- a/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.txx +++ b/Code/BasicFilters/otbLabelizeConfidenceConnectedImageFilter.txx @@ -24,40 +24,40 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage> - LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> - ::LabelizeConfidenceConnectedImageFilter() - { - m_ReplaceValue = itk::NumericTraits<OutputPixelType>::One; - } - - /** Region growing - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> - ::RegionGrowing( const IndexType indexSeed ) - { - this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); - this->m_RegionGrowingFilter->SetSeed(indexSeed); - m_ReplaceValue++; - } - - /** PrintSelf Method - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; - } +/** + * Constructor + */ +template <class TInputImage, class TOutputImage> +LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::LabelizeConfidenceConnectedImageFilter() +{ + m_ReplaceValue = itk::NumericTraits<OutputPixelType>::One; +} + +/** Region growing + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::RegionGrowing( const IndexType indexSeed ) +{ + this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); + this->m_RegionGrowingFilter->SetSeed(indexSeed); + m_ReplaceValue++; +} + +/** PrintSelf Method + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; +} } // end namespace otb #endif diff --git a/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.h b/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.h index 1449ad7d4e87f8f42c507a1ba02f5cfa05dc87b7..fde008e5e46a5f47d1cee1fc6af4ce15c1a2f199 100644 --- a/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.h +++ b/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.h @@ -24,74 +24,74 @@ namespace otb { - /** \class LabelizeConnectedThresholdImageFilter - * \brief - * - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT LabelizeConnectedThresholdImageFilter - : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::ConnectedThresholdImageFilter<TInputImage, TOutputImage> > - { - public: - /** typedef for standard classes. */ - typedef LabelizeConnectedThresholdImageFilter Self; - typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::ConnectedThresholdImageFilter<TInputImage, TOutputImage> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +/** \class LabelizeConnectedThresholdImageFilter + * \brief + * + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT LabelizeConnectedThresholdImageFilter + : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::ConnectedThresholdImageFilter<TInputImage, TOutputImage> > +{ +public: + /** typedef for standard classes. */ + typedef LabelizeConnectedThresholdImageFilter Self; + typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::ConnectedThresholdImageFilter<TInputImage, TOutputImage> > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; - typedef typename TInputImage::PixelType InputPixelType; - typedef typename TOutputImage::PixelType OutputPixelType; - typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TOutputImage::PixelType OutputPixelType; + typedef typename TInputImage::IndexType IndexType; - /** "object factory" management method. */ - itkNewMacro(Self); + /** "object factory" management method. */ + itkNewMacro(Self); - /** Return the class name. */ - itkTypeMacro(LabelizeConnectedThresholdImageFilter, LabelizeImageFilterBase); + /** Return the class name. */ + itkTypeMacro(LabelizeConnectedThresholdImageFilter, LabelizeImageFilterBase); - /** Get delta lower threshold */ - itkGetMacro(LowerThresholdDelta, InputPixelType); + /** Get delta lower threshold */ + itkGetMacro(LowerThresholdDelta, InputPixelType); - /** Set delta lower threshold */ - itkSetMacro(LowerThresholdDelta, InputPixelType); + /** Set delta lower threshold */ + itkSetMacro(LowerThresholdDelta, InputPixelType); - /** Get delta upper threshold */ - itkGetMacro(UpperThresholdDelta, InputPixelType); + /** Get delta upper threshold */ + itkGetMacro(UpperThresholdDelta, InputPixelType); - /** Set delta upper threshold */ - itkSetMacro(UpperThresholdDelta, InputPixelType); + /** Set delta upper threshold */ + itkSetMacro(UpperThresholdDelta, InputPixelType); - /** Get replace value */ - itkGetMacro(ReplaceValue, OutputPixelType); + /** Get replace value */ + itkGetMacro(ReplaceValue, OutputPixelType); - /** Set replace value */ - itkSetMacro(ReplaceValue, OutputPixelType); + /** Set replace value */ + itkSetMacro(ReplaceValue, OutputPixelType); - protected: - LabelizeConnectedThresholdImageFilter(); - virtual ~LabelizeConnectedThresholdImageFilter() {}; - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + LabelizeConnectedThresholdImageFilter(); + virtual ~LabelizeConnectedThresholdImageFilter() {}; + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Region growing */ - virtual void RegionGrowing( const IndexType indexSeed ); + /** Region growing */ + virtual void RegionGrowing( const IndexType indexSeed ); - private: - LabelizeConnectedThresholdImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + LabelizeConnectedThresholdImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - /** Delta + threshold for growing region */ - InputPixelType m_UpperThresholdDelta; + /** Delta + threshold for growing region */ + InputPixelType m_UpperThresholdDelta; - /** Delta - threshold for growing region */ - InputPixelType m_LowerThresholdDelta; + /** Delta - threshold for growing region */ + InputPixelType m_LowerThresholdDelta; - /** Intial replace value*/ - OutputPixelType m_ReplaceValue; + /** Intial replace value*/ + OutputPixelType m_ReplaceValue; - }; // end class LabelizeconnectedThresholdImageFilter +}; // end class LabelizeconnectedThresholdImageFilter } // end namespace otb diff --git a/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.txx b/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.txx index 8caa3fb95965bd4ae9af3ffd939feeb7cab2be55..a08bd60e04bf7ad2b5fd2f64daa68ed6c37caa6f 100644 --- a/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.txx +++ b/Code/BasicFilters/otbLabelizeConnectedThresholdImageFilter.txx @@ -24,50 +24,50 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage> - LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> - ::LabelizeConnectedThresholdImageFilter() - { - m_LowerThresholdDelta = itk::NumericTraits<InputPixelType>::NonpositiveMin(); - m_UpperThresholdDelta = itk::NumericTraits<InputPixelType>::max(); +/** + * Constructor + */ +template <class TInputImage, class TOutputImage> +LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> +::LabelizeConnectedThresholdImageFilter() +{ + m_LowerThresholdDelta = itk::NumericTraits<InputPixelType>::NonpositiveMin(); + m_UpperThresholdDelta = itk::NumericTraits<InputPixelType>::max(); - m_ReplaceValue = 5;//itk::NumericTraits<OutputPixelType>::One; - } + m_ReplaceValue = 5;//itk::NumericTraits<OutputPixelType>::One; +} - /** Region growing - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> - ::RegionGrowing( const IndexType indexSeed ) - { - InputPixelType threshold = this->GetInput()->GetPixel(indexSeed); +/** Region growing + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> +::RegionGrowing( const IndexType indexSeed ) +{ + InputPixelType threshold = this->GetInput()->GetPixel(indexSeed); - this->m_RegionGrowingFilter->SetLower(threshold-m_LowerThresholdDelta); - this->m_RegionGrowingFilter->SetUpper(threshold+m_UpperThresholdDelta); + this->m_RegionGrowingFilter->SetLower(threshold-m_LowerThresholdDelta); + this->m_RegionGrowingFilter->SetUpper(threshold+m_UpperThresholdDelta); - this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); - this->m_RegionGrowingFilter->SetSeed(indexSeed); - m_ReplaceValue++; - } + this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); + this->m_RegionGrowingFilter->SetSeed(indexSeed); + m_ReplaceValue++; +} - /** PrintSelf Method - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "LowerThresholdDelta: " << m_LowerThresholdDelta << std::endl; - os << indent << "UpperThresholdDelta: " << m_UpperThresholdDelta << std::endl; - os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; - } +/** PrintSelf Method + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeConnectedThresholdImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "LowerThresholdDelta: " << m_LowerThresholdDelta << std::endl; + os << indent << "UpperThresholdDelta: " << m_UpperThresholdDelta << std::endl; + os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; +} } // end namespace otb #endif diff --git a/Code/BasicFilters/otbLabelizeImageFilterBase.h b/Code/BasicFilters/otbLabelizeImageFilterBase.h index 597316cadf23e3b1b1cbd9854c17f79f9953edc2..0720fed233d08ee6d2950e4f1eb764df7e9c20e3 100644 --- a/Code/BasicFilters/otbLabelizeImageFilterBase.h +++ b/Code/BasicFilters/otbLabelizeImageFilterBase.h @@ -26,108 +26,108 @@ namespace otb { - /** \class LabelizeImageFilterBase - * \brief Base class for filter labelizing image region based on segmentation. - * - */ - template <class TInputImage, class TOutputImage, class TFilter> - class ITK_EXPORT LabelizeImageFilterBase - : public itk::ImageToImageFilter<TInputImage, TOutputImage> - { - public: - /** typedef for standard classes. */ - typedef LabelizeImageFilterBase Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +/** \class LabelizeImageFilterBase + * \brief Base class for filter labelizing image region based on segmentation. + * + */ +template <class TInputImage, class TOutputImage, class TFilter> +class ITK_EXPORT LabelizeImageFilterBase + : public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** typedef for standard classes. */ + typedef LabelizeImageFilterBase Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** typedef to simplify variables definition and declaration. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; + /** typedef to simplify variables definition and declaration. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; - typedef typename TInputImage::PixelType InputPixelType; - typedef typename TOutputImage::PixelType OutputPixelType; + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TOutputImage::PixelType OutputPixelType; - typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::IndexType IndexType; - typedef itk::PointSet<InputPixelType, 2> PointSetType; - typedef typename PointSetType::Pointer PointSetPointerType; + typedef itk::PointSet<InputPixelType, 2> PointSetType; + typedef typename PointSetType::Pointer PointSetPointerType; - typedef TFilter RegionGrowingFilterType; - typedef typename TFilter::Pointer RegionGrowingFilterPointerType; + typedef TFilter RegionGrowingFilterType; + typedef typename TFilter::Pointer RegionGrowingFilterPointerType; - /** "object factory" management method. */ - itkNewMacro(Self); + /** "object factory" management method. */ + itkNewMacro(Self); - /** Return the class name. */ - itkTypeMacro(LabelizeImageFilterBase, ImageToImageFilter); + /** Return the class name. */ + itkTypeMacro(LabelizeImageFilterBase, ImageToImageFilter); - /** Get lower threshold */ - itkGetMacro(LowerThreshold, InputPixelType); + /** Get lower threshold */ + itkGetMacro(LowerThreshold, InputPixelType); - /** Set lower threshold */ - itkSetMacro(LowerThreshold, InputPixelType); + /** Set lower threshold */ + itkSetMacro(LowerThreshold, InputPixelType); - /** Get upper threshold */ - itkGetMacro(UpperThreshold, InputPixelType); + /** Get upper threshold */ + itkGetMacro(UpperThreshold, InputPixelType); - /** Set upper threshold */ - itkSetMacro(UpperThreshold, InputPixelType); + /** Set upper threshold */ + itkSetMacro(UpperThreshold, InputPixelType); - /** Get Object count*/ - // only set after completion + /** Get Object count*/ + // only set after completion // itkGetConstReferenceMacro(ObjectCount, unsigned long); - itkGetMacro(ObjectCount, unsigned long); + itkGetMacro(ObjectCount, unsigned long); - /** Internal */ - typedef otb::ThresholdImageToPointSetFilter<InputImageType, PointSetType> ThresholdFilterType; - typedef typename ThresholdFilterType::Pointer ThresholdFilterPointerType; + /** Internal */ + typedef otb::ThresholdImageToPointSetFilter<InputImageType, PointSetType> ThresholdFilterType; + typedef typename ThresholdFilterType::Pointer ThresholdFilterPointerType; - typedef otb::MultiplyByScalarImageFilter<InputImageType, OutputImageType> MultiplyFilterType; - typedef typename MultiplyFilterType::Pointer MultiplyFilterPointerType; + typedef otb::MultiplyByScalarImageFilter<InputImageType, OutputImageType> MultiplyFilterType; + typedef typename MultiplyFilterType::Pointer MultiplyFilterPointerType; - typedef itk::AddImageFilter<OutputImageType, OutputImageType, OutputImageType> AddImageFilterType; - typedef typename AddImageFilterType::Pointer AddImageFilterPointerType; + typedef itk::AddImageFilter<OutputImageType, OutputImageType, OutputImageType> AddImageFilterType; + typedef typename AddImageFilterType::Pointer AddImageFilterPointerType; - protected: - LabelizeImageFilterBase(); - virtual ~LabelizeImageFilterBase() {}; - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + LabelizeImageFilterBase(); + virtual ~LabelizeImageFilterBase() {}; + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Main computation method */ - virtual void GenerateData(); + /** Main computation method */ + virtual void GenerateData(); - /** Region growing */ - virtual void RegionGrowing( const IndexType indexSeed) { } + /** Region growing */ + virtual void RegionGrowing( const IndexType indexSeed) { } - /** Instance region growing filter*/ - RegionGrowingFilterPointerType m_RegionGrowingFilter; + /** Instance region growing filter*/ + RegionGrowingFilterPointerType m_RegionGrowingFilter; - /** Lower threshold */ - InputPixelType m_LowerThreshold; + /** Lower threshold */ + InputPixelType m_LowerThreshold; - /** Upper threshold */ - InputPixelType m_UpperThreshold; + /** Upper threshold */ + InputPixelType m_UpperThreshold; - /** Point set to store thresold results */ - PointSetPointerType m_PointSet; + /** Point set to store thresold results */ + PointSetPointerType m_PointSet; - /** Multiply filter*/ - MultiplyFilterPointerType m_MultiplyFilter; + /** Multiply filter*/ + MultiplyFilterPointerType m_MultiplyFilter; - /** Threshold point set filter */ - ThresholdFilterPointerType m_ThresholdPointSetFilter; + /** Threshold point set filter */ + ThresholdFilterPointerType m_ThresholdPointSetFilter; - /** Object counting */ - unsigned long m_ObjectCount; + /** Object counting */ + unsigned long m_ObjectCount; - private: - LabelizeImageFilterBase(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + LabelizeImageFilterBase(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; // end class LabelizeImageFilterBase +}; // end class LabelizeImageFilterBase } // end namespace otb diff --git a/Code/BasicFilters/otbLabelizeImageFilterBase.txx b/Code/BasicFilters/otbLabelizeImageFilterBase.txx index b966f65d4362d5f455e33c8c1d3ea2c7d6ec1996..04a2e4a8a8b2b8ccb1032c00bc2cd6e894458f85 100644 --- a/Code/BasicFilters/otbLabelizeImageFilterBase.txx +++ b/Code/BasicFilters/otbLabelizeImageFilterBase.txx @@ -22,65 +22,65 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage, class TFilter> - LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> - ::LabelizeImageFilterBase() - { - m_LowerThreshold = itk::NumericTraits<InputPixelType>::NonpositiveMin(); - m_UpperThreshold = itk::NumericTraits<InputPixelType>::max(); +/** + * Constructor + */ +template <class TInputImage, class TOutputImage, class TFilter> +LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> +::LabelizeImageFilterBase() +{ + m_LowerThreshold = itk::NumericTraits<InputPixelType>::NonpositiveMin(); + m_UpperThreshold = itk::NumericTraits<InputPixelType>::max(); - m_MultiplyFilter = MultiplyFilterType::New(); - m_MultiplyFilter->SetCoef(0.0); + m_MultiplyFilter = MultiplyFilterType::New(); + m_MultiplyFilter->SetCoef(0.0); - m_ThresholdPointSetFilter = ThresholdFilterType::New(); + m_ThresholdPointSetFilter = ThresholdFilterType::New(); - m_RegionGrowingFilter = RegionGrowingFilterType::New(); - } + m_RegionGrowingFilter = RegionGrowingFilterType::New(); +} - /** Generate data - * - */ - template <class TInputImage, class TOutputImage, class TFilter> - void - LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> - ::GenerateData() +/** Generate data + * + */ +template <class TInputImage, class TOutputImage, class TFilter> +void +LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> +::GenerateData() +{ + // set input for region growing filter + m_RegionGrowingFilter->SetInput(this->GetInput()); + + // create an empty image to store results computing + m_MultiplyFilter->SetInput(this->GetInput()); + m_MultiplyFilter->Update(); + + // Compute points set + m_ThresholdPointSetFilter->SetInput(0, this->GetInput()); + m_ThresholdPointSetFilter->SetLowerThreshold( m_LowerThreshold ); + m_ThresholdPointSetFilter->SetUpperThreshold( m_UpperThreshold ); + m_ThresholdPointSetFilter->Update(); + m_PointSet = m_ThresholdPointSetFilter->GetOutput(); + m_ObjectCount=0; + + // Iterate Point set + typedef typename PointSetType::PointsContainer ContainerType; + ContainerType* pointsContainer = m_PointSet->GetPoints(); + typedef typename ContainerType::Iterator IteratorType; + IteratorType itList = pointsContainer->Begin(); + + typename OutputImageType::Pointer outputImage = m_MultiplyFilter->GetOutput(); + + while ( itList != pointsContainer->End() ) { - // set input for region growing filter - m_RegionGrowingFilter->SetInput(this->GetInput()); - - // create an empty image to store results computing - m_MultiplyFilter->SetInput(this->GetInput()); - m_MultiplyFilter->Update(); - - // Compute points set - m_ThresholdPointSetFilter->SetInput(0, this->GetInput()); - m_ThresholdPointSetFilter->SetLowerThreshold( m_LowerThreshold ); - m_ThresholdPointSetFilter->SetUpperThreshold( m_UpperThreshold ); - m_ThresholdPointSetFilter->Update(); - m_PointSet = m_ThresholdPointSetFilter->GetOutput(); - m_ObjectCount=0; - - // Iterate Point set - typedef typename PointSetType::PointsContainer ContainerType; - ContainerType* pointsContainer = m_PointSet->GetPoints(); - typedef typename ContainerType::Iterator IteratorType; - IteratorType itList = pointsContainer->Begin(); - - typename OutputImageType::Pointer outputImage = m_MultiplyFilter->GetOutput(); - - while( itList != pointsContainer->End() ) - { - typename PointSetType::PointType pCoordinate = (itList.Value()); - typename InputImageType::IndexType index; - - index[0] = static_cast <int> (pCoordinate[0]); - index[1] = static_cast <int> (pCoordinate[1]); - if (outputImage->GetPixel(index) == - itk::NumericTraits<OutputPixelType>::ZeroValue() ) - { + typename PointSetType::PointType pCoordinate = (itList.Value()); + typename InputImageType::IndexType index; + + index[0] = static_cast <int> (pCoordinate[0]); + index[1] = static_cast <int> (pCoordinate[1]); + if (outputImage->GetPixel(index) == + itk::NumericTraits<OutputPixelType>::ZeroValue() ) + { this->RegionGrowing(index); AddImageFilterPointerType addImage = AddImageFilterType::New(); @@ -88,29 +88,29 @@ namespace otb addImage->SetInput2(m_RegionGrowingFilter->GetOutput()); addImage->Update(); outputImage = addImage->GetOutput(); - ++m_ObjectCount; + ++m_ObjectCount; } - ++itList; - } - - this->GraftOutput(outputImage); + ++itList; } - /** PrintSelf Method - * - */ - template <class TInputImage, class TOutputImage, class TFilter> - void - LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); + this->GraftOutput(outputImage); +} - os << indent << "Seeds lower threshold: " << m_LowerThreshold << std::endl; - os << indent << "Seeds upper threshold: " << m_UpperThreshold << std::endl; - os << indent << "ObjectCount: " << m_ObjectCount << std::endl; - os << indent << m_RegionGrowingFilter << std::endl; - } +/** PrintSelf Method + * + */ +template <class TInputImage, class TOutputImage, class TFilter> +void +LabelizeImageFilterBase<TInputImage, TOutputImage, TFilter> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Seeds lower threshold: " << m_LowerThreshold << std::endl; + os << indent << "Seeds upper threshold: " << m_UpperThreshold << std::endl; + os << indent << "ObjectCount: " << m_ObjectCount << std::endl; + os << indent << m_RegionGrowingFilter << std::endl; +} } // end namespace otb #endif diff --git a/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.h b/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.h index 798b0adc06f7844feaaaa61cf9f30c2b9c17cf36..02939111cdbbba50ece7233802942e0ae0719039 100644 --- a/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.h +++ b/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.h @@ -24,99 +24,99 @@ namespace otb { - /** \class LabelizeNeighborhoodConnectedImageFilter - * \brief Labels pixels that are connected to a seed and lie - * within a neighborhood - * - * This class implements base class otb::LabelizeImageFilterBase - * - * First seeds are obtained with a theshold filter - * For each seed, itk::NeighborhoodConnectedImageFilter labels pixel - * Finally, filter produce a regions map - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT LabelizeNeighborhoodConnectedImageFilter - : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> > - { - public: - /** typedef for standard classes. */ - typedef LabelizeNeighborhoodConnectedImageFilter Self; - typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +/** \class LabelizeNeighborhoodConnectedImageFilter + * \brief Labels pixels that are connected to a seed and lie + * within a neighborhood + * + * This class implements base class otb::LabelizeImageFilterBase + * + * First seeds are obtained with a theshold filter + * For each seed, itk::NeighborhoodConnectedImageFilter labels pixel + * Finally, filter produce a regions map + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT LabelizeNeighborhoodConnectedImageFilter + : public otb::LabelizeImageFilterBase<TInputImage, TOutputImage, itk::NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> > +{ +public: + /** typedef for standard classes. */ + typedef LabelizeNeighborhoodConnectedImageFilter Self; + typedef otb::LabelizeImageFilterBase<TInputImage,TOutputImage, itk::NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** typedef to simplify variables definition and declaration. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; + /** typedef to simplify variables definition and declaration. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; - typedef typename TInputImage::PixelType InputPixelType; - typedef typename TInputImage::SizeType InputSizeType; - typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TInputImage::SizeType InputSizeType; + typedef typename TInputImage::IndexType IndexType; - typedef typename TOutputImage::PixelType OutputPixelType; + typedef typename TOutputImage::PixelType OutputPixelType; - /** "object factory" management method. */ - itkNewMacro(Self); + /** "object factory" management method. */ + itkNewMacro(Self); - /** Return the class name. */ - itkTypeMacro(LabelizeNeighborhoodConnectedImageFilter, LabelizeImageFilterBase); + /** Return the class name. */ + itkTypeMacro(LabelizeNeighborhoodConnectedImageFilter, LabelizeImageFilterBase); - /** Get delta lower threshold */ - itkGetMacro(LowerThresholdDelta, InputPixelType); + /** Get delta lower threshold */ + itkGetMacro(LowerThresholdDelta, InputPixelType); - /** Set delta lower threshold */ - itkSetMacro(LowerThresholdDelta, InputPixelType); + /** Set delta lower threshold */ + itkSetMacro(LowerThresholdDelta, InputPixelType); - /** Get delta upper threshold */ - itkGetMacro(UpperThresholdDelta, InputPixelType); + /** Get delta upper threshold */ + itkGetMacro(UpperThresholdDelta, InputPixelType); - /** Set delta upper threshold */ - itkSetMacro(UpperThresholdDelta, InputPixelType); + /** Set delta upper threshold */ + itkSetMacro(UpperThresholdDelta, InputPixelType); - /** Get replace value */ - itkGetMacro(ReplaceValue, OutputPixelType); + /** Get replace value */ + itkGetMacro(ReplaceValue, OutputPixelType); - /** Set replace value */ - itkSetMacro(ReplaceValue, OutputPixelType); + /** Set replace value */ + itkSetMacro(ReplaceValue, OutputPixelType); - /** Get radius */ - const InputSizeType& GetRadius() const - { - return this->m_RegionGrowingFilter->GetRadius(); - } + /** Get radius */ + const InputSizeType& GetRadius() const + { + return this->m_RegionGrowingFilter->GetRadius(); + } - /** Set radius */ - void SetRadius( const InputSizeType radius ) - { - this->m_RegionGrowingFilter->SetRadius(radius); - this->Modified(); - } + /** Set radius */ + void SetRadius( const InputSizeType radius ) + { + this->m_RegionGrowingFilter->SetRadius(radius); + this->Modified(); + } - protected: - LabelizeNeighborhoodConnectedImageFilter(); - virtual ~LabelizeNeighborhoodConnectedImageFilter() {}; - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + LabelizeNeighborhoodConnectedImageFilter(); + virtual ~LabelizeNeighborhoodConnectedImageFilter() {}; + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Region growing */ - virtual void RegionGrowing( const IndexType indexSeed ); + /** Region growing */ + virtual void RegionGrowing( const IndexType indexSeed ); - private: - LabelizeNeighborhoodConnectedImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + LabelizeNeighborhoodConnectedImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - /** Delta + threshold for growing region */ - InputPixelType m_UpperThresholdDelta; + /** Delta + threshold for growing region */ + InputPixelType m_UpperThresholdDelta; - /** Delta - threshold for growing region */ - InputPixelType m_LowerThresholdDelta; + /** Delta - threshold for growing region */ + InputPixelType m_LowerThresholdDelta; - /** Intial replace value*/ - OutputPixelType m_ReplaceValue; + /** Intial replace value*/ + OutputPixelType m_ReplaceValue; - }; // end class LabelizeconnectedThresholdImageFilter +}; // end class LabelizeconnectedThresholdImageFilter } // end namespace otb diff --git a/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.txx b/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.txx index 17c5914511ee9787edc6c033178b4edb083c863e..93cd99aab23997a82d62c35f08619bf1df8a7a73 100644 --- a/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.txx +++ b/Code/BasicFilters/otbLabelizeNeighborhoodConnectedImageFilter.txx @@ -22,50 +22,50 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage> - LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> - ::LabelizeNeighborhoodConnectedImageFilter() - { - m_LowerThresholdDelta = itk::NumericTraits<InputPixelType>::NonpositiveMin(); - m_UpperThresholdDelta = itk::NumericTraits<InputPixelType>::max(); +/** + * Constructor + */ +template <class TInputImage, class TOutputImage> +LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::LabelizeNeighborhoodConnectedImageFilter() +{ + m_LowerThresholdDelta = itk::NumericTraits<InputPixelType>::NonpositiveMin(); + m_UpperThresholdDelta = itk::NumericTraits<InputPixelType>::max(); - m_ReplaceValue = itk::NumericTraits<OutputPixelType>::One; - } + m_ReplaceValue = itk::NumericTraits<OutputPixelType>::One; +} - /** Region growing - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> - ::RegionGrowing( const IndexType indexSeed ) - { - InputPixelType threshold = this->GetInput()->GetPixel(indexSeed); +/** Region growing + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::RegionGrowing( const IndexType indexSeed ) +{ + InputPixelType threshold = this->GetInput()->GetPixel(indexSeed); - this->m_RegionGrowingFilter->SetLower(threshold-m_LowerThresholdDelta); - this->m_RegionGrowingFilter->SetUpper(threshold+m_UpperThresholdDelta); + this->m_RegionGrowingFilter->SetLower(threshold-m_LowerThresholdDelta); + this->m_RegionGrowingFilter->SetUpper(threshold+m_UpperThresholdDelta); - this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); - this->m_RegionGrowingFilter->SetSeed(indexSeed); - m_ReplaceValue++; - } + this->m_RegionGrowingFilter->SetReplaceValue(m_ReplaceValue); + this->m_RegionGrowingFilter->SetSeed(indexSeed); + m_ReplaceValue++; +} - /** PrintSelf Method - * - */ - template <class TInputImage, class TOutputImage> - void - LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "LowerThresholdDelta: " << m_LowerThresholdDelta << std::endl; - os << indent << "UpperThresholdDelta: " << m_UpperThresholdDelta << std::endl; - os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; - } +/** PrintSelf Method + * + */ +template <class TInputImage, class TOutputImage> +void +LabelizeNeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "LowerThresholdDelta: " << m_LowerThresholdDelta << std::endl; + os << indent << "UpperThresholdDelta: " << m_UpperThresholdDelta << std::endl; + os << indent << "ReplaceValue: " << m_ReplaceValue << std::endl; +} } // end namespace otb #endif diff --git a/Code/BasicFilters/otbLeeImageFilter.h b/Code/BasicFilters/otbLeeImageFilter.h index 418939ad742374868ef5cca264bf50d613c8679a..f71e1bb0617b777ee93034eea066aa33657e1fd3 100644 --- a/Code/BasicFilters/otbLeeImageFilter.h +++ b/Code/BasicFilters/otbLeeImageFilter.h @@ -45,10 +45,10 @@ class ITK_EXPORT LeeImageFilter : public itk::ImageToImageFilter< TInputImage, public: /** Extract input and output image dimension */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); diff --git a/Code/BasicFilters/otbLeeImageFilter.txx b/Code/BasicFilters/otbLeeImageFilter.txx index 1a0f15a597546b75c97823b6363e33d2fd5bb7c1..5e371d94357faf93fa434304df0e899909c2f1a0 100644 --- a/Code/BasicFilters/otbLeeImageFilter.txx +++ b/Code/BasicFilters/otbLeeImageFilter.txx @@ -33,140 +33,140 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * - */ - template <class TInputImage, class TOutputImage> - LeeImageFilter<TInputImage, TOutputImage>::LeeImageFilter() - { - m_Radius.Fill(1); - SetNbLooks(1.0); - } +/** + * + */ +template <class TInputImage, class TOutputImage> +LeeImageFilter<TInputImage, TOutputImage>::LeeImageFilter() +{ + m_Radius.Fill(1); + SetNbLooks(1.0); +} - template <class TInputImage, class TOutputImage> - void LeeImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() throw (itk::InvalidRequestedRegionError) - { - // call the superclass' implementation of this method - Superclass::GenerateInputRequestedRegion(); +template <class TInputImage, class TOutputImage> +void LeeImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() throw (itk::InvalidRequestedRegionError) +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); - // get pointers to the input and output - typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); + // get pointers to the input and output + typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); + typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - if ( !inputPtr || !outputPtr ) - { - return; - } + if ( !inputPtr || !outputPtr ) + { + return; + } - // get a copy of the input requested region (should equal the output - // requested region) - typename TInputImage::RegionType inputRequestedRegion; - inputRequestedRegion = inputPtr->GetRequestedRegion(); + // get a copy of the input requested region (should equal the output + // requested region) + typename TInputImage::RegionType inputRequestedRegion; + inputRequestedRegion = inputPtr->GetRequestedRegion(); - // pad the input requested region by the operator radius - inputRequestedRegion.PadByRadius( m_Radius ); + // pad the input requested region by the operator radius + inputRequestedRegion.PadByRadius( m_Radius ); - // crop the input requested region at the input's largest possible region - if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { - inputPtr->SetRequestedRegion( inputRequestedRegion ); - return; - } - else - { - // Couldn't crop the region (requested region is outside the largest - // possible region). Throw an exception. - - // store what we tried to request (prior to trying to crop) - inputPtr->SetRequestedRegion( inputRequestedRegion ); - - // build an exception - itk::InvalidRequestedRegionError e(__FILE__, __LINE__); - itk::OStringStream msg; - msg << static_cast<const char *>(this->GetNameOfClass()) - << "::GenerateInputRequestedRegion()"; - e.SetLocation(msg.str().c_str()); - e.SetDescription("Requested region is (at least partially) outside the largest possible region."); - e.SetDataObject(inputPtr); - throw e; - } + // crop the input requested region at the input's largest possible region + if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) + { + inputPtr->SetRequestedRegion( inputRequestedRegion ); + return; + } + else + { + // Couldn't crop the region (requested region is outside the largest + // possible region). Throw an exception. + + // store what we tried to request (prior to trying to crop) + inputPtr->SetRequestedRegion( inputRequestedRegion ); + + // build an exception + itk::InvalidRequestedRegionError e(__FILE__, __LINE__); + itk::OStringStream msg; + msg << static_cast<const char *>(this->GetNameOfClass()) + << "::GenerateInputRequestedRegion()"; + e.SetLocation(msg.str().c_str()); + e.SetDescription("Requested region is (at least partially) outside the largest possible region."); + e.SetDataObject(inputPtr); + throw e; } +} - template< class TInputImage, class TOutputImage> - void LeeImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - int threadId - ) - { - unsigned int i; - itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; +template< class TInputImage, class TOutputImage> +void LeeImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( + const OutputImageRegionType& outputRegionForThread, + int threadId +) +{ + unsigned int i; + itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; - itk::ConstNeighborhoodIterator<InputImageType> bit; - itk::ImageRegionIterator<OutputImageType> it; + itk::ConstNeighborhoodIterator<InputImageType> bit; + itk::ImageRegionIterator<OutputImageType> it; - // Allocate output - typename OutputImageType::Pointer output = this->GetOutput(); - typename InputImageType::ConstPointer input = this->GetInput(); + // Allocate output + typename OutputImageType::Pointer output = this->GetOutput(); + typename InputImageType::ConstPointer input = this->GetInput(); - // Find the data-set boundary "faces" - typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType>::FaceListType faceList; - typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType>::FaceListType::iterator fit; + // Find the data-set boundary "faces" + typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType>::FaceListType faceList; + typename itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType>::FaceListType::iterator fit; - itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType> bC; - faceList = bC(input, outputRegionForThread, m_Radius); + itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<InputImageType> bC; + faceList = bC(input, outputRegionForThread, m_Radius); - // support progress methods/callbacks - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - // InputRealType pixel; - InputRealType sum; - InputRealType sum2; + // InputRealType pixel; + InputRealType sum; + InputRealType sum2; - double Cr2, Cv2, E_I, I, Var_I, dPixel; + double Cr2, Cv2, E_I, I, Var_I, dPixel; - // dPixel = this->getNbVues(); - dPixel = m_NbLooks; - //Calcul du rapport - Cv2 = 1./(vcl_sqrt(dPixel)); - Cv2 = Cv2*Cv2; + // dPixel = this->getNbVues(); + dPixel = m_NbLooks; + //Calcul du rapport + Cv2 = 1./(vcl_sqrt(dPixel)); + Cv2 = Cv2*Cv2; - // Process each of the boundary faces. These are N-d regions which border - // the edge of the buffer. - for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { - bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, input, *fit); - unsigned int neighborhoodSize = bit.Size(); - it = itk::ImageRegionIterator<OutputImageType>(output, *fit); - bit.OverrideBoundaryCondition(&nbc); - bit.GoToBegin(); + // Process each of the boundary faces. These are N-d regions which border + // the edge of the buffer. + for (fit=faceList.begin(); fit != faceList.end(); ++fit) + { + bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, input, *fit); + unsigned int neighborhoodSize = bit.Size(); + it = itk::ImageRegionIterator<OutputImageType>(output, *fit); + bit.OverrideBoundaryCondition(&nbc); + bit.GoToBegin(); - while ( ! bit.IsAtEnd() ) + while ( ! bit.IsAtEnd() ) { sum = itk::NumericTraits<InputRealType>::Zero; sum2 = itk::NumericTraits<InputRealType>::Zero; //Parcours du voisinage for (i = 0; i < neighborhoodSize; ++i) - { - dPixel = static_cast<double>( bit.GetPixel(i) ); - sum += dPixel; - sum2 += dPixel * dPixel; - } + { + dPixel = static_cast<double>( bit.GetPixel(i) ); + sum += dPixel; + sum2 += dPixel * dPixel; + } E_I = sum / double(neighborhoodSize); Var_I = sum2 / double(neighborhoodSize) - E_I*E_I; I = static_cast<double>( bit.GetCenterPixel() ); - if(E_I==0) - { - dPixel = itk::NumericTraits<OutputPixelType>::Zero; - } + if (E_I==0) + { + dPixel = itk::NumericTraits<OutputPixelType>::Zero; + } else - { - Cr2 = Var_I / (E_I*E_I); - dPixel = E_I + ((I-E_I)*(Cr2))/(Cr2 + Cv2); + { + Cr2 = Var_I / (E_I*E_I); + dPixel = E_I + ((I-E_I)*(Cr2))/(Cr2 + Cv2); - } + } // get the mean value it.Set( static_cast<OutputPixelType>( dPixel ) ); @@ -174,19 +174,19 @@ namespace otb ++it; progress.CompletedPixel(); } - } - } - - /** - * Standard "PrintSelf" method - */ - template <class TInputImage, class TOutput> - void - LeeImageFilter<TInputImage, TOutput>::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf( os, indent ); - os << indent << "Radius: " << m_Radius << std::endl; } +} + +/** + * Standard "PrintSelf" method + */ +template <class TInputImage, class TOutput> +void +LeeImageFilter<TInputImage, TOutput>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf( os, indent ); + os << indent << "Radius: " << m_Radius << std::endl; +} } // end namespace otb diff --git a/Code/BasicFilters/otbLogPolarTransform.h b/Code/BasicFilters/otbLogPolarTransform.h index 177ff8c34b103e685e255394268e7c95cc28f4c0..47ed9da65caa8813d9f0f4f745d112df851bd62c 100644 --- a/Code/BasicFilters/otbLogPolarTransform.h +++ b/Code/BasicFilters/otbLogPolarTransform.h @@ -22,103 +22,103 @@ namespace otb { - /** \class LogPolarTransform - * \brief Implement the log-polar coordinate transform. - * - * The log-polar coordinate system is a polar system where the - * radial coordinate has a logarithmic scale. - * - * Given \f$(\rho,\theta)\f$ the coordinate in the log-polar system, the - * corresponding cartesian coordinates are - * - * \f$ x-xc=exp(\rho)*cos(\theta) \f$ - * \f$ y-yc=exp(\rho)*sin(\theta) \f$ - * - * Where (xc,yc) is the center of the log-polar transform in the cartesian space. - * Please note that this center can NOT be represented in log-polar. - * - * \sa InverseLogPolarTransform - * \ingroup Transform - */ +/** \class LogPolarTransform + * \brief Implement the log-polar coordinate transform. + * + * The log-polar coordinate system is a polar system where the + * radial coordinate has a logarithmic scale. + * + * Given \f$(\rho,\theta)\f$ the coordinate in the log-polar system, the + * corresponding cartesian coordinates are + * + * \f$ x-xc=exp(\rho)*cos(\theta) \f$ + * \f$ y-yc=exp(\rho)*sin(\theta) \f$ + * + * Where (xc,yc) is the center of the log-polar transform in the cartesian space. + * Please note that this center can NOT be represented in log-polar. + * + * \sa InverseLogPolarTransform + * \ingroup Transform + */ template <class TScalarType> class ITK_EXPORT LogPolarTransform - : public itk::Transform<TScalarType,2,2> - { - public: - /** Standard typedef */ - typedef LogPolarTransform Self; - typedef itk::Transform<TScalarType,2,2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory */ - itkNewMacro(Self); - /** Runtime information */ - itkTypeMacro(LogPolarTransform,Transform); - - /** Template related typedefs */ - typedef TScalarType ScalarType; - - /** Superclass related typedefs */ - 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::ParametersType ParametersType; - typedef itk::FixedArray<TScalarType,2> ScaleType; - - /** Set/Get the origin */ - itkSetMacro(Center,InputPointType); - itkGetConstReferenceMacro(Center,InputPointType); - - /** Set/Get the scales */ - itkSetMacro(Scale,ScaleType); - itkGetConstReferenceMacro(Scale,ScaleType); - /** - * Set the transform parameters through the standard interface. - * \param parameters The parameters of the transform. - */ - void SetParameters(const ParametersType ¶meters); - /** - * Get the transform parameters through the standard interface. - * \return The parameters of the transform. - */ - virtual ParametersType& GetParameters(void) const; - /** - * Transform a point. - * \param point The point to transform. - * \return The transformed point. - */ - OutputPointType TransformPoint(const InputPointType &point) const; - /** - * Transform a vector representing a point. - * \param vector The point to transform. - * \return The transformed point. - */ - OutputVectorType TransformVector(const InputVectorType &vector) const; - /** - * Transform a vnl vector representing a point. - * \param vector The point to transform. - * \return The transformed point. - */ - OutputVnlVectorType TransformVector(const InputVnlVectorType &vector) const; - - protected: - /** Constructor */ - LogPolarTransform(); - /** Destructor */ - ~LogPolarTransform(); - /** PrintSelf method */ - void PrintSelf(std::ostream &os,itk::Indent indent) const; - - private: - LogPolarTransform(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - - InputPointType m_Center; - ScaleType m_Scale; - }; + : public itk::Transform<TScalarType,2,2> +{ +public: + /** Standard typedef */ + typedef LogPolarTransform Self; + typedef itk::Transform<TScalarType,2,2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory */ + itkNewMacro(Self); + /** Runtime information */ + itkTypeMacro(LogPolarTransform,Transform); + + /** Template related typedefs */ + typedef TScalarType ScalarType; + + /** Superclass related typedefs */ + 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::ParametersType ParametersType; + typedef itk::FixedArray<TScalarType,2> ScaleType; + + /** Set/Get the origin */ + itkSetMacro(Center,InputPointType); + itkGetConstReferenceMacro(Center,InputPointType); + + /** Set/Get the scales */ + itkSetMacro(Scale,ScaleType); + itkGetConstReferenceMacro(Scale,ScaleType); + /** + * Set the transform parameters through the standard interface. + * \param parameters The parameters of the transform. + */ + void SetParameters(const ParametersType ¶meters); + /** + * Get the transform parameters through the standard interface. + * \return The parameters of the transform. + */ + virtual ParametersType& GetParameters(void) const; + /** + * Transform a point. + * \param point The point to transform. + * \return The transformed point. + */ + OutputPointType TransformPoint(const InputPointType &point) const; + /** + * Transform a vector representing a point. + * \param vector The point to transform. + * \return The transformed point. + */ + OutputVectorType TransformVector(const InputVectorType &vector) const; + /** + * Transform a vnl vector representing a point. + * \param vector The point to transform. + * \return The transformed point. + */ + OutputVnlVectorType TransformVector(const InputVnlVectorType &vector) const; + +protected: + /** Constructor */ + LogPolarTransform(); + /** Destructor */ + ~LogPolarTransform(); + /** PrintSelf method */ + void PrintSelf(std::ostream &os,itk::Indent indent) const; + +private: + LogPolarTransform(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + + InputPointType m_Center; + ScaleType m_Scale; +}; }// end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbLogPolarTransform.txx" diff --git a/Code/BasicFilters/otbLogPolarTransform.txx b/Code/BasicFilters/otbLogPolarTransform.txx index bc04b2d15aa39713f23769a884b00e1515252746..f4e4780c0dc7cc65cc7966f4e58228e93a2763aa 100644 --- a/Code/BasicFilters/otbLogPolarTransform.txx +++ b/Code/BasicFilters/otbLogPolarTransform.txx @@ -30,7 +30,7 @@ namespace otb template <class TScalarType> LogPolarTransform<TScalarType> ::LogPolarTransform() - :Superclass(2,4) + :Superclass(2,4) { m_Center[0]=0.0; m_Center[1]=0.0; @@ -87,7 +87,7 @@ LogPolarTransform<TScalarType> template <class TScalarType> typename LogPolarTransform<TScalarType> ::OutputPointType - LogPolarTransform<TScalarType> +LogPolarTransform<TScalarType> ::TransformPoint(const InputPointType &point) const { OutputPointType result; @@ -132,7 +132,7 @@ LogPolarTransform<TScalarType> ::TransformVector(const InputVnlVectorType &vector) const { OutputVnlVectorType result; -double theta = vector[0]*m_Scale[0]*M_PI/180.0; + double theta = vector[0]*m_Scale[0]*M_PI/180.0; double logRho = vector[1]*m_Scale[1]; result[0]=0.; result[1]=0.; diff --git a/Code/BasicFilters/otbMeanShiftImageFilter.h b/Code/BasicFilters/otbMeanShiftImageFilter.h index 8b5a10122811758758d410096062da2526e47800..e6368be72214e0b88cce63ec4c4fb8509affc3e2 100644 --- a/Code/BasicFilters/otbMeanShiftImageFilter.h +++ b/Code/BasicFilters/otbMeanShiftImageFilter.h @@ -26,194 +26,194 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace MeanShift - { - /** \class ScalarBufferConverter - * \brief Small utilities class used for buffer conversion with EDISON standard. - * This class handles buffer conversion when pixel type is scalar. - **/ - class ScalarBufferConverter +namespace MeanShift +{ +/** \class ScalarBufferConverter + * \brief Small utilities class used for buffer conversion with EDISON standard. + * This class handles buffer conversion when pixel type is scalar. + **/ +class ScalarBufferConverter +{ +public: + /** + * Fill the pixel with the float array values at index, using nbComp values scaled by scale. + */ + template <class TPixel> + static inline void + FloatArrayToPixel(const float * data, unsigned int index, TPixel & pixel, + const unsigned int nbComp, double scale) { - public: - /** - * Fill the pixel with the float array values at index, using nbComp values scaled by scale. - */ - template <class TPixel> - static inline void - FloatArrayToPixel(const float * data, unsigned int index, TPixel & pixel, - const unsigned int nbComp, double scale) - { - pixel = static_cast<TPixel>(scale * data[index]); - } - /** - * Fill the float array data with the pixel values at index, using nbComp values scaled by scale. - */ - template <class TPixel> - static inline void - PixelToFloatArray(float * data, unsigned int index, const TPixel & pixel, double scale) - { - data[index]=static_cast<float>(scale * pixel); - } - }; - } - - /** \class MeanShiftImageFilter - * - * - * Mean shift is a data clustering algorithm ofthen used in image processing and segmentation. - * For a given pixel, the mean shift will build a set of neighboring pixels within a given spatial - * radius (can be set using SetSpatialRadius()) and a color range (can be set using SetRangeRadius()). - * The spatial and color center of this set is then computed and the algorithm iterates with this new spatial - * and color center. - * - * Mean shift can be used for edge-preserving smoothing, or for clustering. The GetOutput() method will allow - * you to get the smoothed image, whereas the - * GetClusteredOuptut() methods returns the clustered output. The GetLabeledClusteredOutput() returns - * a labeled clustered image, and the GetClusterBoundariesOutput() - * an image of the cluster boundaries. - * - * The MinimumRegionSize parameter allows you to prune small clustered regions. - * - * Please note that the filtering part is multi-threaded, while the clustering one is not (this is - * not really noticeable, because the clustering step is really faster - * than the filtering one). - * - * Please also note that if both parts are streamable, only the filtering part will ensure you to get the same - * results than without streaming. In the clustering results, you - * might find region split due to tiling. Morover, the labeled output will not give consistent results when - * streamed. The cluster boundaries might work though. - * - * This filter uses the Edison mean shift algorithm implementation. Please note that data whose precision - * is more than float are casted to float before processing. - * - * The Scale parameter allows you to stretch the data dynamic - * - * For more information on mean shift techniques, one might consider reading the following article: - * - * D. Comaniciu, P. Meer, "Mean Shift: A Robust Approach Toward Feature Space Analysis," IEEE Transactions on - * Pattern Analysis and Machine Intelligence, vol. 24, no. 5, pp. 603-619, May, 2002 - * D. Comaniciu, P. Meer, "Robust analysis of feature spaces: color image segmentation," cvpr, p. 750, 1997 - * IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'97), 1997 - * D. Comaniciu, P. Meer, "Mean Shift Analysis and Applications," iccv, p. 1197, Seventh International Conference - * on Computer Vision (ICCV'99) - Volume 2, 1999 - * - * \sa MeanShiftImageFilter - * \sa MeanShiftVectorImageFilter - * - * \ingroup ImageEnhancement - * \ingroup Streamed - * \ingroup Threaded + pixel = static_cast<TPixel>(scale * data[index]); + } + /** + * Fill the float array data with the pixel values at index, using nbComp values scaled by scale. */ - - template <class TInputImage, class TOutputImage, - class TLabeledOutput = otb::Image<unsigned short,2>, - class TBufferConverter = MeanShift::ScalarBufferConverter> - class ITK_EXPORT MeanShiftImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> - { - public: - /** Standard class typedef */ - typedef MeanShiftImageFilter Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkTypeMacro(MeanShiftImageFilter,ImageToImageFilter); - itkNewMacro(Self); - - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef typename InputImageType::PixelType InputPixelType; - typedef typename InputImageType::PointType PointType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename OutputImageType::RegionType RegionType; - typedef TLabeledOutput LabeledOutputType; - typedef typename LabeledOutputType::Pointer LabeledOutputPointerType; - typedef typename LabeledOutputType::PixelType LabelType; - - /** Typedefs for vectorized output */ - typedef otb::Polygon<InputPixelType> PolygonType; - typedef typename PolygonType::Pointer PolygonPointerType; - typedef otb::ObjectList<PolygonType> PolygonListType; - typedef typename PolygonListType::Pointer PolygonListPointerType; - - /** Typedef for mean-shift modes map */ - typedef std::map<LabelType,InputPixelType> ModeMapType; - - /** Setters / Getters */ - itkSetMacro(SpatialRadius,unsigned int); - itkGetMacro(SpatialRadius,unsigned int); - itkSetMacro(RangeRadius,double); - itkGetMacro(RangeRadius,double); - itkSetMacro(MinimumRegionSize,unsigned int); - itkGetMacro(MinimumRegionSize,unsigned int); - itkSetMacro(Scale,double); - itkGetMacro(Scale,double); - - /** Return the const clustered image output */ - const OutputImageType * GetClusteredOutput() const; - /** Return the clustered image output */ - OutputImageType * GetClusteredOutput(); - /** Return the const labeled clustered image output */ - const LabeledOutputType * GetLabeledClusteredOutput() const; - /** Return the labeled clustered image output */ - LabeledOutputType * GetLabeledClusteredOutput(); - /** Return the const cluster boundaries image output */ - const LabeledOutputType * GetClusterBoundariesOutput() const; - /** Return the cluster boundaries image output */ - LabeledOutputType * GetClusterBoundariesOutput(); - /** Return the const vectorized boundaries output */ - const PolygonListType * GetVectorizedClusterBoundariesOutput() const; - /** Return the mean-shift mode by label */ - const ModeMapType& GetModes() - { - return m_Modes; - } - - protected: - /** This filters use a neighborhood around the pixel, so it needs to redfine the - * input requested region */ - virtual void GenerateInputRequestedRegion(); - /** Threaded generate data (handle the filtering part) */ - virtual void ThreadedGenerateData(const RegionType& outputRegionForThread,int threadId); - /** After threaded generate data (handle the clustering part) */ - virtual void AfterThreadedGenerateData(); - /** Allocate the outputs (need to be reimplemented since outputs have differents type) */ - virtual void AllocateOutputs(); - /** If modified, we have to reset the list of modes */ - virtual void Modified() - { - Superclass::Modified(); - m_Modes.clear(); - } - - /** Constructor */ - MeanShiftImageFilter(); - /** destructor */ - ~MeanShiftImageFilter(){}; - - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - MeanShiftImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Spatial radius for mean shift convergence */ - unsigned int m_SpatialRadius; - /** Range radius for mean shift convergence */ - double m_RangeRadius; - /** Minimum region size in pixels for clustering */ - unsigned int m_MinimumRegionSize; - /** Data scale (used to stretch data range) */ - double m_Scale; - /** A map of the different modes by segmented regions */ - ModeMapType m_Modes; - }; + template <class TPixel> + static inline void + PixelToFloatArray(float * data, unsigned int index, const TPixel & pixel, double scale) + { + data[index]=static_cast<float>(scale * pixel); + } +}; +} + +/** \class MeanShiftImageFilter + * + * + * Mean shift is a data clustering algorithm ofthen used in image processing and segmentation. + * For a given pixel, the mean shift will build a set of neighboring pixels within a given spatial + * radius (can be set using SetSpatialRadius()) and a color range (can be set using SetRangeRadius()). + * The spatial and color center of this set is then computed and the algorithm iterates with this new spatial + * and color center. + * + * Mean shift can be used for edge-preserving smoothing, or for clustering. The GetOutput() method will allow + * you to get the smoothed image, whereas the + * GetClusteredOuptut() methods returns the clustered output. The GetLabeledClusteredOutput() returns + * a labeled clustered image, and the GetClusterBoundariesOutput() + * an image of the cluster boundaries. + * + * The MinimumRegionSize parameter allows you to prune small clustered regions. + * + * Please note that the filtering part is multi-threaded, while the clustering one is not (this is + * not really noticeable, because the clustering step is really faster + * than the filtering one). + * + * Please also note that if both parts are streamable, only the filtering part will ensure you to get the same + * results than without streaming. In the clustering results, you + * might find region split due to tiling. Morover, the labeled output will not give consistent results when + * streamed. The cluster boundaries might work though. + * + * This filter uses the Edison mean shift algorithm implementation. Please note that data whose precision + * is more than float are casted to float before processing. + * + * The Scale parameter allows you to stretch the data dynamic + * + * For more information on mean shift techniques, one might consider reading the following article: + * + * D. Comaniciu, P. Meer, "Mean Shift: A Robust Approach Toward Feature Space Analysis," IEEE Transactions on + * Pattern Analysis and Machine Intelligence, vol. 24, no. 5, pp. 603-619, May, 2002 + * D. Comaniciu, P. Meer, "Robust analysis of feature spaces: color image segmentation," cvpr, p. 750, 1997 + * IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'97), 1997 + * D. Comaniciu, P. Meer, "Mean Shift Analysis and Applications," iccv, p. 1197, Seventh International Conference + * on Computer Vision (ICCV'99) - Volume 2, 1999 + * + * \sa MeanShiftImageFilter + * \sa MeanShiftVectorImageFilter + * + * \ingroup ImageEnhancement + * \ingroup Streamed + * \ingroup Threaded + */ + +template <class TInputImage, class TOutputImage, +class TLabeledOutput = otb::Image<unsigned short,2>, +class TBufferConverter = MeanShift::ScalarBufferConverter> +class ITK_EXPORT MeanShiftImageFilter + : public itk::ImageToImageFilter<TInputImage,TOutputImage> +{ +public: + /** Standard class typedef */ + typedef MeanShiftImageFilter Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkTypeMacro(MeanShiftImageFilter,ImageToImageFilter); + itkNewMacro(Self); + + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::PointType PointType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::RegionType RegionType; + typedef TLabeledOutput LabeledOutputType; + typedef typename LabeledOutputType::Pointer LabeledOutputPointerType; + typedef typename LabeledOutputType::PixelType LabelType; + + /** Typedefs for vectorized output */ + typedef otb::Polygon<InputPixelType> PolygonType; + typedef typename PolygonType::Pointer PolygonPointerType; + typedef otb::ObjectList<PolygonType> PolygonListType; + typedef typename PolygonListType::Pointer PolygonListPointerType; + + /** Typedef for mean-shift modes map */ + typedef std::map<LabelType,InputPixelType> ModeMapType; + + /** Setters / Getters */ + itkSetMacro(SpatialRadius,unsigned int); + itkGetMacro(SpatialRadius,unsigned int); + itkSetMacro(RangeRadius,double); + itkGetMacro(RangeRadius,double); + itkSetMacro(MinimumRegionSize,unsigned int); + itkGetMacro(MinimumRegionSize,unsigned int); + itkSetMacro(Scale,double); + itkGetMacro(Scale,double); + + /** Return the const clustered image output */ + const OutputImageType * GetClusteredOutput() const; + /** Return the clustered image output */ + OutputImageType * GetClusteredOutput(); + /** Return the const labeled clustered image output */ + const LabeledOutputType * GetLabeledClusteredOutput() const; + /** Return the labeled clustered image output */ + LabeledOutputType * GetLabeledClusteredOutput(); + /** Return the const cluster boundaries image output */ + const LabeledOutputType * GetClusterBoundariesOutput() const; + /** Return the cluster boundaries image output */ + LabeledOutputType * GetClusterBoundariesOutput(); + /** Return the const vectorized boundaries output */ + const PolygonListType * GetVectorizedClusterBoundariesOutput() const; + /** Return the mean-shift mode by label */ + const ModeMapType& GetModes() + { + return m_Modes; + } + +protected: + /** This filters use a neighborhood around the pixel, so it needs to redfine the + * input requested region */ + virtual void GenerateInputRequestedRegion(); + /** Threaded generate data (handle the filtering part) */ + virtual void ThreadedGenerateData(const RegionType& outputRegionForThread,int threadId); + /** After threaded generate data (handle the clustering part) */ + virtual void AfterThreadedGenerateData(); + /** Allocate the outputs (need to be reimplemented since outputs have differents type) */ + virtual void AllocateOutputs(); + /** If modified, we have to reset the list of modes */ + virtual void Modified() + { + Superclass::Modified(); + m_Modes.clear(); + } + + /** Constructor */ + MeanShiftImageFilter(); + /** destructor */ + ~MeanShiftImageFilter() {}; + + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + MeanShiftImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Spatial radius for mean shift convergence */ + unsigned int m_SpatialRadius; + /** Range radius for mean shift convergence */ + double m_RangeRadius; + /** Minimum region size in pixels for clustering */ + unsigned int m_MinimumRegionSize; + /** Data scale (used to stretch data range) */ + double m_Scale; + /** A map of the different modes by segmented regions */ + ModeMapType m_Modes; +}; }// end namespace otb diff --git a/Code/BasicFilters/otbMeanShiftImageFilter.txx b/Code/BasicFilters/otbMeanShiftImageFilter.txx index c2cd23c6a3796d3c7cefbd6b3f12d175d7ab81af..24e1dc02b7712a29b3843e43cdcb0d41535a331c 100644 --- a/Code/BasicFilters/otbMeanShiftImageFilter.txx +++ b/Code/BasicFilters/otbMeanShiftImageFilter.txx @@ -50,9 +50,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetClusteredOutput()const { if (this->GetNumberOfOutputs() < 2) - { + { return 0; - } + } return static_cast<const OutputImageType * >(this->itk::ProcessObject::GetOutput(1)); } @@ -62,9 +62,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetClusteredOutput() { if (this->GetNumberOfOutputs() < 2) - { + { return 0; - } + } return static_cast< OutputImageType * >(this->itk::ProcessObject::GetOutput(1)); } @@ -75,9 +75,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetLabeledClusteredOutput()const { if (this->GetNumberOfOutputs() < 3) - { + { return 0; - } + } return static_cast<const LabeledOutputType * >(this->itk::ProcessObject::GetOutput(2)); } @@ -87,9 +87,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetLabeledClusteredOutput() { if (this->GetNumberOfOutputs() < 3) - { + { return 0; - } + } return static_cast< LabeledOutputType * >(this->itk::ProcessObject::GetOutput(2)); } @@ -100,9 +100,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetClusterBoundariesOutput()const { if (this->GetNumberOfOutputs() < 4) - { + { return 0; - } + } return static_cast<const LabeledOutputType * >(this->itk::ProcessObject::GetOutput(3)); } @@ -112,9 +112,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> ::GetClusterBoundariesOutput() { if (this->GetNumberOfOutputs() < 4) - { + { return 0; - } + } return static_cast< LabeledOutputType * >(this->itk::ProcessObject::GetOutput(3)); } @@ -155,9 +155,9 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -169,12 +169,12 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -187,7 +187,7 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } template <class TInputImage,class TOutputImage, class TLabeledOutput, class TBufferConverter> @@ -219,11 +219,11 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> unsigned int index = 0; - for(inputIt.GoToBegin();!inputIt.IsAtEnd();++inputIt) - { + for (inputIt.GoToBegin();!inputIt.IsAtEnd();++inputIt) + { TBufferConverter::PixelToFloatArray(data,index,inputIt.Get(),m_Scale); index+=inputPtr->GetNumberOfComponentsPerPixel(); - } + } edisonProcessor.DefineLInput(data,inputRequestedRegion.GetSize()[1],inputRequestedRegion.GetSize()[0],inputPtr->GetNumberOfComponentsPerPixel()); @@ -236,10 +236,10 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> edisonProcessor.Filter(m_SpatialRadius,m_RangeRadius*m_Scale,MED_SPEEDUP); - if(edisonProcessor.ErrorStatus) - { + if (edisonProcessor.ErrorStatus) + { itkExceptionMacro(<<"Error while running edison!"); - } + } typename OutputImageType::Pointer tmpOutput = OutputImageType::New(); @@ -251,31 +251,31 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> edisonProcessor.GetRawData(data); - if(edisonProcessor.ErrorStatus) - { + if (edisonProcessor.ErrorStatus) + { itkExceptionMacro(<<"Error while running edison!"); - } + } index = 0; - for(tmpIt.GoToBegin();!tmpIt.IsAtEnd();++tmpIt) - { + for (tmpIt.GoToBegin();!tmpIt.IsAtEnd();++tmpIt) + { OutputPixelType pixel; TBufferConverter::FloatArrayToPixel(data,index,pixel,outputPtr->GetNumberOfComponentsPerPixel(),invScale); tmpIt.Set(pixel); index+=outputPtr->GetNumberOfComponentsPerPixel(); - } + } tmp2It.GoToBegin(); outputIt.GoToBegin(); - while(!tmp2It.IsAtEnd() && !outputIt.IsAtEnd()) - { + while (!tmp2It.IsAtEnd() && !outputIt.IsAtEnd()) + { outputIt.Set(tmp2It.Get()); ++tmp2It; ++outputIt; - } + } delete [] data; } @@ -305,11 +305,11 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> unsigned int index = 0; - for(outputIt.GoToBegin();!outputIt.IsAtEnd();++outputIt) - { + for (outputIt.GoToBegin();!outputIt.IsAtEnd();++outputIt) + { TBufferConverter::PixelToFloatArray(data,index,outputIt.Get(),m_Scale); index+=outputPtr->GetNumberOfComponentsPerPixel(); - } + } edisonProcessor.DefineLInput(data,outputRequestedRegion.GetSize()[1],outputRequestedRegion.GetSize()[0],outputPtr->GetNumberOfComponentsPerPixel()); @@ -322,26 +322,26 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> edisonProcessor.FuseRegions(m_RangeRadius*m_Scale,m_MinimumRegionSize); - if(edisonProcessor.ErrorStatus) - { + if (edisonProcessor.ErrorStatus) + { itkExceptionMacro(<<"Error while running edison!"); - } + } edisonProcessor.GetRawData(data); - if(edisonProcessor.ErrorStatus) - { + if (edisonProcessor.ErrorStatus) + { itkExceptionMacro(<<"Error while running edison!"); - } + } index = 0; - for(clusteredOutputIt.GoToBegin();!clusteredOutputIt.IsAtEnd();++clusteredOutputIt) - { + for (clusteredOutputIt.GoToBegin();!clusteredOutputIt.IsAtEnd();++clusteredOutputIt) + { OutputPixelType pixel; TBufferConverter::FloatArrayToPixel(data,index,pixel,clusteredOutputPtr->GetNumberOfComponentsPerPixel(),invScale); clusteredOutputIt.Set(pixel); index+=clusteredOutputPtr->GetNumberOfComponentsPerPixel(); - } + } delete [] data; @@ -351,10 +351,10 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> edisonProcessor.GetRegions(&labels,&modes,&modesPointsCount); - if(edisonProcessor.ErrorStatus) - { + if (edisonProcessor.ErrorStatus) + { itkExceptionMacro(<<"Error while running edison!"); - } + } itk::ImageRegionIteratorWithIndex<LabeledOutputType> lcIt(labeledClusteredOutputPtr,labeledClusteredOutputPtr->GetRequestedRegion()); @@ -362,11 +362,11 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> labeledClusteredOutputPtr->FillBuffer(0); - for(lcIt.GoToBegin();!lcIt.IsAtEnd();++lcIt) - { + for (lcIt.GoToBegin();!lcIt.IsAtEnd();++lcIt) + { lcIt.Set(static_cast<LabelType>(labels[index])); ++index; - } + } clusterBoudariesOutputPtr->FillBuffer(0); @@ -377,24 +377,24 @@ MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,TBufferConverter> typename LabeledOutputType::IndexType boundIndex; - for(LabelType label = 0; label < numRegions;++label) - { + for (LabelType label = 0; label < numRegions;++label) + { OutputPixelType pixel; TBufferConverter::FloatArrayToPixel(modes,label*clusteredOutputPtr->GetNumberOfComponentsPerPixel(), - pixel,clusteredOutputPtr->GetNumberOfComponentsPerPixel(),invScale); + pixel,clusteredOutputPtr->GetNumberOfComponentsPerPixel(),invScale); // Filling the modes map m_Modes[label]=pixel; regionIndeces = regionList->GetRegionIndeces(label); - for(int i = 0; i<regionList->GetRegionCount(label); ++i) - { + for (int i = 0; i<regionList->GetRegionCount(label); ++i) + { boundIndex[0]= regionIndeces[i] % clusterBoudariesOutputPtr->GetRequestedRegion().GetSize()[0]; boundIndex[1]= regionIndeces[i] / clusterBoudariesOutputPtr->GetRequestedRegion().GetSize()[0]; - if(clusterBoudariesOutputPtr->GetBufferedRegion().IsInside(boundIndex)) - { - clusterBoudariesOutputPtr->SetPixel(boundIndex,1); - } + if (clusterBoudariesOutputPtr->GetBufferedRegion().IsInside(boundIndex)) + { + clusterBoudariesOutputPtr->SetPixel(boundIndex,1); } } + } // Free memory delete [] labels; diff --git a/Code/BasicFilters/otbMeanShiftVectorImageFilter.h b/Code/BasicFilters/otbMeanShiftVectorImageFilter.h index d0e542e12d22b2b7703a979e7fcef4996b3e375d..ab76351ac3905de26b130233a76afd00ad6b1db5 100644 --- a/Code/BasicFilters/otbMeanShiftVectorImageFilter.h +++ b/Code/BasicFilters/otbMeanShiftVectorImageFilter.h @@ -22,82 +22,82 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace MeanShift - { - /** \class ScalarBufferConverter - * \brief Small utilities class used for buffer conversion with EDISON standard. - * This class handles buffer conversion when pixel type is scalar. - **/ - class VectorBufferConverter +namespace MeanShift +{ +/** \class ScalarBufferConverter + * \brief Small utilities class used for buffer conversion with EDISON standard. + * This class handles buffer conversion when pixel type is scalar. + **/ +class VectorBufferConverter +{ +public: + /** + * Fill the pixel with the float array values at index, using nbComp values scaled by scale. + */ + template <class TPixel> static inline void FloatArrayToPixel(const float * data, unsigned int index, TPixel & pixel, const unsigned int nbComp, double scale) { - public: - /** - * Fill the pixel with the float array values at index, using nbComp values scaled by scale. - */ - template <class TPixel> static inline void FloatArrayToPixel(const float * data, unsigned int index, TPixel & pixel, const unsigned int nbComp, double scale) - { - pixel.SetSize(nbComp); - for(unsigned int i = 0; i<pixel.Size();++i) + pixel.SetSize(nbComp); + for (unsigned int i = 0; i<pixel.Size();++i) { pixel[i]= static_cast<typename TPixel::ValueType> (scale * data[index+i]); } - } - /** - * Fill the float array data with the pixel values at index, using nbComp values scaled by scale. - */ - template <class TPixel> static inline void PixelToFloatArray(float * data, unsigned int index, const TPixel & pixel,double scale) - { - for(unsigned int i = 0; i<pixel.Size();++i) + } + /** + * Fill the float array data with the pixel values at index, using nbComp values scaled by scale. + */ + template <class TPixel> static inline void PixelToFloatArray(float * data, unsigned int index, const TPixel & pixel,double scale) + { + for (unsigned int i = 0; i<pixel.Size();++i) { data[index+i]=static_cast<float>(scale * pixel[i]); } - } - }; - } + } +}; +} - /** \class MeanShiftVectorImageFilter - * - * This is the implementation of the mean shift clustering and edge-preserving smoothing filter adapted to - * otb::VectorImage or itk::VectorImage. For the full documentation, please refer to the - * base class otb::MeanShiftImageFilter. - * - * \sa MeanShiftImageFilter - * \ingroup ImageEnhancement - * \ingroup Streamed - * \ingroup Threaded - */ - template <class TInputImage, class TOutputImage, class TLabeledOutput = otb::Image<unsigned short,2> > - class MeanShiftVectorImageFilter - : public MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,MeanShift::VectorBufferConverter> - { - public: +/** \class MeanShiftVectorImageFilter + * + * This is the implementation of the mean shift clustering and edge-preserving smoothing filter adapted to + * otb::VectorImage or itk::VectorImage. For the full documentation, please refer to the + * base class otb::MeanShiftImageFilter. + * + * \sa MeanShiftImageFilter + * \ingroup ImageEnhancement + * \ingroup Streamed + * \ingroup Threaded + */ +template <class TInputImage, class TOutputImage, class TLabeledOutput = otb::Image<unsigned short,2> > +class MeanShiftVectorImageFilter + : public MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput,MeanShift::VectorBufferConverter> +{ +public: - /** Standard class typedef */ - typedef MeanShiftVectorImageFilter Self; - typedef MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput, - MeanShift::VectorBufferConverter> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + /** Standard class typedef */ + typedef MeanShiftVectorImageFilter Self; + typedef MeanShiftImageFilter<TInputImage,TOutputImage,TLabeledOutput, + MeanShift::VectorBufferConverter> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Type macro */ - itkTypeMacro(MeanShiftVectorImageFilter,MeanShiftImageFilter); - itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(MeanShiftVectorImageFilter,MeanShiftImageFilter); + itkNewMacro(Self); - protected: - /** Constructor */ - MeanShiftVectorImageFilter(){}; - /** destructor */ - ~MeanShiftVectorImageFilter(){}; +protected: + /** Constructor */ + MeanShiftVectorImageFilter() {}; + /** destructor */ + ~MeanShiftVectorImageFilter() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const + { + Superclass::PrintSelf(os,indent); + } - private: - MeanShiftVectorImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +private: + MeanShiftVectorImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; }// end namespace otb #endif diff --git a/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.h b/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.h index 0162ea3623c7ffbfc79a5029ad9b1b69e39762d9..a39a34c024cd609b6be7fc898625c262ea20957a 100644 --- a/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.h +++ b/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.h @@ -20,7 +20,8 @@ #include "itkImageToImageFilter.h" -namespace otb { +namespace otb +{ /** * \class OpeningClosingMorphologicalFilter * \brief This filter implements an opening grayscale morphological operation @@ -40,7 +41,7 @@ namespace otb { */ template <class TInputImage, class TOutputImage, class TKernel> class ITK_EXPORT OpeningClosingMorphologicalFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { public : /** Standard typedefs */ diff --git a/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.txx b/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.txx index 3d7d960cf130d18533734b82fac34d31dea13a83..3e010b43b7c93df854d7584a7bbdf6b7d1fd3e2d 100644 --- a/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.txx +++ b/Code/BasicFilters/otbOpeningClosingMorphologicalFilter.txx @@ -24,7 +24,8 @@ #include "itkGrayscaleMorphologicalClosingImageFilter.h" #include "itkProgressAccumulator.h" -namespace otb { +namespace otb +{ /** * Constructor */ diff --git a/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.h b/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.h index 135a98564927a4452cceddbfdea1be8499184660..5bfd6243fe8541fc913b2bfa28714c9b717cb8ec 100644 --- a/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.h +++ b/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.h @@ -26,146 +26,146 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class OverlapSaveConvolutionImageFilter - * - * This filter implements the convolution operation between a kernel and an - * image using the overlap save algorithm (http://wikipedia.org/wiki/Overlap-save_method). - * - * This method takes advantages of the FFTW implementation of Fast Fourrier Transform to - * exchange an intensive convolution product in the space domain for a simple term by term - * product in the Fourrier domain. This result in tremendous speed gain when using large kernel - * with exactly the same result as the classical convolution filter. - * - * \note This filter could be threaded but requires additional design due to limited thread-safety - * of the FFTW library. - * - * \note For the moment only constant zero boundary conditions are used in this filter. This could produce - * very different results from the classical convolution filter with zero flux neumann boundary condition, - * especially with large kernels. - * - * \note ITK must be set to use FFTW (double implementation) for this filter to work properly. If not, exception - * will be raised at filter creation. Install fftw and set the variable - * USE_FFTWD to ON in ccmake. - * - * \sa ConvolutionImageFilter - * - * \ingroup ShouldBeThreaded - * \ingroup Streamed - * \ingroup IntensityImageFilters - */ +/** \class OverlapSaveConvolutionImageFilter + * + * This filter implements the convolution operation between a kernel and an + * image using the overlap save algorithm (http://wikipedia.org/wiki/Overlap-save_method). + * + * This method takes advantages of the FFTW implementation of Fast Fourrier Transform to + * exchange an intensive convolution product in the space domain for a simple term by term + * product in the Fourrier domain. This result in tremendous speed gain when using large kernel + * with exactly the same result as the classical convolution filter. + * + * \note This filter could be threaded but requires additional design due to limited thread-safety + * of the FFTW library. + * + * \note For the moment only constant zero boundary conditions are used in this filter. This could produce + * very different results from the classical convolution filter with zero flux neumann boundary condition, + * especially with large kernels. + * + * \note ITK must be set to use FFTW (double implementation) for this filter to work properly. If not, exception + * will be raised at filter creation. Install fftw and set the variable + * USE_FFTWD to ON in ccmake. + * + * \sa ConvolutionImageFilter + * + * \ingroup ShouldBeThreaded + * \ingroup Streamed + * \ingroup IntensityImageFilters + */ template <class TInputImage,class TOutputImage> class ITK_EXPORT OverlapSaveConvolutionImageFilter - : public itk::ImageToImageFilter< TInputImage, TOutputImage > - { - public: - /** Extract dimension from input and output image. */ - itkStaticConstMacro(InputImageDimension, unsigned int,TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, unsigned int,TOutputImage::ImageDimension); - - /** Convenient typedefs for simplifying declarations. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - - /** Standard class typedefs. */ - typedef OverlapSaveConvolutionImageFilter Self; - typedef itk::ImageToImageFilter< InputImageType, OutputImageType> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(OverlapSaveConvolutionImageFilter, ImageToImageFilter); - - /** Image typedef support. */ - typedef typename InputImageType::PixelType InputPixelType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename itk::NumericTraits<InputPixelType>::RealType InputRealType; - typedef typename InputImageType::RegionType InputImageRegionType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename InputImageType::SizeType InputSizeType; - typedef typename itk::Array<InputRealType> ArrayType; - - /** Set the radius of the neighborhood used to compute the mean. */ - virtual void SetRadius (const InputSizeType rad) + : public itk::ImageToImageFilter< TInputImage, TOutputImage > +{ +public: + /** Extract dimension from input and output image. */ + itkStaticConstMacro(InputImageDimension, unsigned int,TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int,TOutputImage::ImageDimension); + + /** Convenient typedefs for simplifying declarations. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + /** Standard class typedefs. */ + typedef OverlapSaveConvolutionImageFilter Self; + typedef itk::ImageToImageFilter< InputImageType, OutputImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(OverlapSaveConvolutionImageFilter, ImageToImageFilter); + + /** Image typedef support. */ + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename itk::NumericTraits<InputPixelType>::RealType InputRealType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename itk::Array<InputRealType> ArrayType; + + /** Set the radius of the neighborhood used to compute the mean. */ + virtual void SetRadius (const InputSizeType rad) { itkDebugMacro("setting radius to " << rad); if (this->m_Radius != rad) - { - this->m_Radius = rad; - unsigned int arraySize=1; - for (unsigned int i=0; i<m_Radius.GetSizeDimension(); i++) { - arraySize *= 2*this->m_Radius[i]+1; - } - this->m_Filter.SetSize(arraySize); - this->m_Filter.Fill(1); - this->Modified(); + this->m_Radius = rad; + unsigned int arraySize=1; + for (unsigned int i=0; i<m_Radius.GetSizeDimension(); i++) + { + arraySize *= 2*this->m_Radius[i]+1; } + this->m_Filter.SetSize(arraySize); + this->m_Filter.Fill(1); + this->Modified(); + } } - /** Get the radius of the neighborhood used to compute the mean */ - itkGetConstReferenceMacro(Radius, InputSizeType); + /** Get the radius of the neighborhood used to compute the mean */ + itkGetConstReferenceMacro(Radius, InputSizeType); - /** Set the input filter */ - void SetFilter(ArrayType filter) + /** Set the input filter */ + void SetFilter(ArrayType filter) { - if((filter.Size()!= m_Filter.Size())) - { - itkExceptionMacro("Error in SetFilter, invalid filter size:"<< filter.Size()<<" instead of 2*(m_Radius[0]+1)*(2*m_Radius[1]+1): "<<m_Filter.Size()); - } + if ((filter.Size()!= m_Filter.Size())) + { + itkExceptionMacro("Error in SetFilter, invalid filter size:"<< filter.Size()<<" instead of 2*(m_Radius[0]+1)*(2*m_Radius[1]+1): "<<m_Filter.Size()); + } else - { - m_Filter = filter; - } + { + m_Filter = filter; + } this->Modified(); - } - /** Get the filter */ - itkGetConstReferenceMacro(Filter,ArrayType); - - /** Set/Get methods for the normalization of the filter */ - itkSetMacro(NormalizeFilter, bool); - itkGetMacro(NormalizeFilter, bool); - itkBooleanMacro(NormalizeFilter); - - /** Since this filter implements a neighborhood operation, it requests a largest input - * region than the output region. - */ - virtual void GenerateInputRequestedRegion() throw(itk::InvalidRequestedRegionError); - - #ifdef ITK_USE_CONCEPT_CHECKING - /** Begin concept checking */ - itkConceptMacro(InputHasNumericTraitsCheck,(itk::Concept::HasNumericTraits<InputPixelType>)); - /** End concept checking */ - #endif - - protected: - /** Constructor */ - OverlapSaveConvolutionImageFilter(); - /** destructor */ - virtual ~OverlapSaveConvolutionImageFilter() {} - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** TODO For the moment this class provide only a GenerateData(), - * due to limited thread-safety of FFTW plan creation. - */ - void GenerateData(); - // void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,int threadId); - - private: - OverlapSaveConvolutionImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Radius of the filter */ - InputSizeType m_Radius; - - /** Filter array */ - ArrayType m_Filter; - - /** Flag for filter normalization */ - bool m_NormalizeFilter; - }; + } + /** Get the filter */ + itkGetConstReferenceMacro(Filter,ArrayType); + + /** Set/Get methods for the normalization of the filter */ + itkSetMacro(NormalizeFilter, bool); + itkGetMacro(NormalizeFilter, bool); + itkBooleanMacro(NormalizeFilter); + + /** Since this filter implements a neighborhood operation, it requests a largest input + * region than the output region. + */ + virtual void GenerateInputRequestedRegion() throw(itk::InvalidRequestedRegionError); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputHasNumericTraitsCheck,(itk::Concept::HasNumericTraits<InputPixelType>)); + /** End concept checking */ +#endif + +protected: + /** Constructor */ + OverlapSaveConvolutionImageFilter(); + /** destructor */ + virtual ~OverlapSaveConvolutionImageFilter() {} + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** TODO For the moment this class provide only a GenerateData(), + * due to limited thread-safety of FFTW plan creation. + */ + void GenerateData(); + // void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,int threadId); + +private: + OverlapSaveConvolutionImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Radius of the filter */ + InputSizeType m_Radius; + + /** Filter array */ + ArrayType m_Filter; + + /** Flag for filter normalization */ + bool m_NormalizeFilter; +}; } // end namespace otb #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.txx b/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.txx index 0366f098b321bb97741b9d41fb4400b87f275928..c593f102989a5e8868ac1a9f2ab0573a25b14961 100644 --- a/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.txx +++ b/Code/BasicFilters/otbOverlapSaveConvolutionImageFilter.txx @@ -37,249 +37,249 @@ namespace otb template <class TInputImage, class TOutputImage> OverlapSaveConvolutionImageFilter<TInputImage, TOutputImage> ::OverlapSaveConvolutionImageFilter() - { - m_Radius.Fill(1); - m_Filter.SetSize(3*3); - m_Filter.Fill(1); - m_NormalizeFilter = false; - } +{ + m_Radius.Fill(1); + m_Filter.SetSize(3*3); + m_Filter.Fill(1); + m_NormalizeFilter = false; +} template <class TInputImage, class TOutputImage> void OverlapSaveConvolutionImageFilter<TInputImage, TOutputImage> ::GenerateInputRequestedRegion() throw (itk::InvalidRequestedRegionError) - { +{ #if defined USE_FFTWD - // call the superclass' implementation of this method - Superclass::GenerateInputRequestedRegion(); - - // get pointers to the input and output - typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - - if ( !inputPtr || !outputPtr ) - { - return; - } - - // get a copy of the input requested region (should equal the output - // requested region) - typename TInputImage::RegionType inputRequestedRegion; - inputRequestedRegion = inputPtr->GetRequestedRegion(); - - // Pad by filter radius - inputRequestedRegion.PadByRadius(m_Radius); - - // crop the input requested region at the input's largest possible region - if(inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion())) - { - inputPtr->SetRequestedRegion(inputRequestedRegion); - return; - } - else - { - // Couldn't crop the region (requested region is outside the largest - // possible region). Throw an exception. + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); - // store what we tried to request (prior to trying to crop) - inputPtr->SetRequestedRegion(inputRequestedRegion); + // get pointers to the input and output + typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); + typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); + if ( !inputPtr || !outputPtr ) + { + return; + } + // get a copy of the input requested region (should equal the output + // requested region) + typename TInputImage::RegionType inputRequestedRegion; + inputRequestedRegion = inputPtr->GetRequestedRegion(); - // build an exception - itk::InvalidRequestedRegionError e(__FILE__, __LINE__); - e.SetLocation(ITK_LOCATION); - e.SetDescription("Requested region is (at least partially) outside the largest possible region."); - e.SetDataObject(inputPtr); - throw e; - } - } + // Pad by filter radius + inputRequestedRegion.PadByRadius(m_Radius); - template< class TInputImage, class TOutputImage> - void - OverlapSaveConvolutionImageFilter< TInputImage, TOutputImage> - /** TODO commented out since multi-threading is not supported for the moment - * ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,int threadId) */ - ::GenerateData() + // crop the input requested region at the input's largest possible region + if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion())) + { + inputPtr->SetRequestedRegion(inputRequestedRegion); + return; + } + else { - // Input/Output pointers - typename OutputImageType::Pointer output = this->GetOutput(); - typename InputImageType::ConstPointer input = this->GetInput(); + // Couldn't crop the region (requested region is outside the largest + // possible region). Throw an exception. + + // store what we tried to request (prior to trying to crop) + inputPtr->SetRequestedRegion(inputRequestedRegion); + + + + // build an exception + itk::InvalidRequestedRegionError e(__FILE__, __LINE__); + e.SetLocation(ITK_LOCATION); + e.SetDescription("Requested region is (at least partially) outside the largest possible region."); + e.SetDataObject(inputPtr); + throw e; + } +} + +template< class TInputImage, class TOutputImage> +void +OverlapSaveConvolutionImageFilter< TInputImage, TOutputImage> +/** TODO commented out since multi-threading is not supported for the moment + * ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,int threadId) */ +::GenerateData() +{ + // Input/Output pointers + typename OutputImageType::Pointer output = this->GetOutput(); + typename InputImageType::ConstPointer input = this->GetInput(); - /** TODO: This is a patch to switch from GenerateData() to ThreadedGenerateData(). Remove these two lines + /** TODO: This is a patch to switch from GenerateData() to ThreadedGenerateData(). Remove these two lines once multi-threading problem is solved */ - this->AllocateOutputs(); - OutputImageRegionType outputRegionForThread = output->GetRequestedRegion(); + this->AllocateOutputs(); + OutputImageRegionType outputRegionForThread = output->GetRequestedRegion(); - // Size of the filter - typename InputImageType::SizeType sizeOfFilter; - sizeOfFilter[0]=2*m_Radius[0]+1; - sizeOfFilter[1]=2*m_Radius[1]+1; + // Size of the filter + typename InputImageType::SizeType sizeOfFilter; + sizeOfFilter[0]=2*m_Radius[0]+1; + sizeOfFilter[1]=2*m_Radius[1]+1; - // Filter normalization - InputRealType norm; + // Filter normalization + InputRealType norm; - // Compute the input region for the given thread - OutputImageRegionType inputRegionForThread = outputRegionForThread; - inputRegionForThread.PadByRadius(m_Radius); + // Compute the input region for the given thread + OutputImageRegionType inputRegionForThread = outputRegionForThread; + inputRegionForThread.PadByRadius(m_Radius); - // Compute the piece region for the input thread. Piece region is different - // from input region on boundaries - typename InputImageType::RegionType pieceRegion = inputRegionForThread; - typename InputImageType::SizeType pieceSize = pieceRegion.GetSize(); - typename InputImageType::IndexType pieceIndex = pieceRegion.GetIndex(); + // Compute the piece region for the input thread. Piece region is different + // from input region on boundaries + typename InputImageType::RegionType pieceRegion = inputRegionForThread; + typename InputImageType::SizeType pieceSize = pieceRegion.GetSize(); + typename InputImageType::IndexType pieceIndex = pieceRegion.GetIndex(); - // Compute the size of the FFT and the size of the piece - unsigned int pieceNbOfPixel = pieceRegion.GetNumberOfPixels(); - unsigned int sizeFFT=(pieceSize[0]/2+1)*pieceSize[1]; + // Compute the size of the FFT and the size of the piece + unsigned int pieceNbOfPixel = pieceRegion.GetNumberOfPixels(); + unsigned int sizeFFT=(pieceSize[0]/2+1)*pieceSize[1]; - // Achieve the computation of the inputRegionForThread - inputRegionForThread.Crop(input->GetLargestPossibleRegion()); - typename InputImageType::IndexType inputIndex = inputRegionForThread.GetIndex(); - typename InputImageType::SizeType inputSize = inputRegionForThread.GetSize(); + // Achieve the computation of the inputRegionForThread + inputRegionForThread.Crop(input->GetLargestPossibleRegion()); + typename InputImageType::IndexType inputIndex = inputRegionForThread.GetIndex(); + typename InputImageType::SizeType inputSize = inputRegionForThread.GetSize(); - //Iterator of input image - itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; - itk::ConstNeighborhoodIterator<InputImageType> bit(m_Radius,input,inputRegionForThread); - bit.OverrideBoundaryCondition(&nbc); - bit.GoToBegin(); + //Iterator of input image + itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; + itk::ConstNeighborhoodIterator<InputImageType> bit(m_Radius,input,inputRegionForThread); + bit.OverrideBoundaryCondition(&nbc); + bit.GoToBegin(); - //Iterator of output image - itk::ImageRegionIteratorWithIndex<OutputImageType> it; - it = itk::ImageRegionIteratorWithIndex<OutputImageType>(output,outputRegionForThread); + //Iterator of output image + itk::ImageRegionIteratorWithIndex<OutputImageType> it; + it = itk::ImageRegionIteratorWithIndex<OutputImageType>(output,outputRegionForThread); - //variables for loops - unsigned int i,j,k,l; + //variables for loops + unsigned int i,j,k,l; - // ITK proxy to the fftw library - typedef typename itk::fftw::Proxy<double> FFTWProxyType; + // ITK proxy to the fftw library + typedef typename itk::fftw::Proxy<double> FFTWProxyType; - //memory allocation - InputPixelType* resampledFilterPiece; - resampledFilterPiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(InputPixelType))); + //memory allocation + InputPixelType* resampledFilterPiece; + resampledFilterPiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(InputPixelType))); - FFTWProxyType::ComplexType* filterPieceFFT; - filterPieceFFT=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); + FFTWProxyType::ComplexType* filterPieceFFT; + filterPieceFFT=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); - InputPixelType *inputPiece; - inputPiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(InputPixelType))); + InputPixelType *inputPiece; + inputPiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(InputPixelType))); - FFTWProxyType::ComplexType* inputPieceFFT; - inputPieceFFT=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); + FFTWProxyType::ComplexType* inputPieceFFT; + inputPieceFFT=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); - // Image piece FFT - FFTWProxyType::PlanType inputPlan=FFTWProxyType::Plan_dft_r2c_2d(pieceSize[1],pieceSize[0],inputPiece,inputPieceFFT,FFTW_MEASURE); + // Image piece FFT + FFTWProxyType::PlanType inputPlan=FFTWProxyType::Plan_dft_r2c_2d(pieceSize[1],pieceSize[0],inputPiece,inputPieceFFT,FFTW_MEASURE); - // left zero padding - unsigned int leftskip = static_cast<unsigned int>(std::max(0L,inputIndex[0]-pieceIndex[0])); - unsigned int topskip = pieceSize[0]*static_cast<unsigned int>(std::max(0L,inputIndex[1]-pieceIndex[1])); + // left zero padding + unsigned int leftskip = static_cast<unsigned int>(std::max(0L,inputIndex[0]-pieceIndex[0])); + unsigned int topskip = pieceSize[0]*static_cast<unsigned int>(std::max(0L,inputIndex[1]-pieceIndex[1])); - // Filling the buffer with image values - for(l = 0;l<inputSize[1];++l) - { - for(k = 0;k<inputSize[0];++k) + // Filling the buffer with image values + for (l = 0;l<inputSize[1];++l) + { + for (k = 0;k<inputSize[0];++k) { inputPiece[topskip+pieceSize[0]*l+k+leftskip]=bit.GetCenterPixel(); ++bit; } - } + } - FFTWProxyType::Execute(inputPlan); + FFTWProxyType::Execute(inputPlan); - // Resampled filter FFT - FFTWProxyType::PlanType filterPlan=FFTWProxyType::Plan_dft_r2c_2d(pieceSize[1],pieceSize[0],resampledFilterPiece,filterPieceFFT,FFTW_MEASURE); + // Resampled filter FFT + FFTWProxyType::PlanType filterPlan=FFTWProxyType::Plan_dft_r2c_2d(pieceSize[1],pieceSize[0],resampledFilterPiece,filterPieceFFT,FFTW_MEASURE); - k=0; - // Filling the buffer with filter values - for(j=0;j<sizeOfFilter[1];j++) - { - for(i=0;i<sizeOfFilter[0];i++) + k=0; + // Filling the buffer with filter values + for (j=0;j<sizeOfFilter[1];j++) + { + for (i=0;i<sizeOfFilter[0];i++) { resampledFilterPiece[i+j*pieceSize[0]]=m_Filter.GetElement(k);//Copy values k++; } - } + } - FFTWProxyType::Execute(filterPlan); + FFTWProxyType::Execute(filterPlan); - // memory allocation for inverse FFT - FFTWProxyType::ComplexType* multipliedFFTarray; - multipliedFFTarray=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); + // memory allocation for inverse FFT + FFTWProxyType::ComplexType* multipliedFFTarray; + multipliedFFTarray=static_cast<FFTWProxyType::ComplexType*>(fftw_malloc(sizeFFT*sizeof(FFTWProxyType::ComplexType))); - FFTWProxyType::PixelType* inverseFFTpiece; - inverseFFTpiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(FFTWProxyType::PixelType))); + FFTWProxyType::PixelType* inverseFFTpiece; + inverseFFTpiece=static_cast<FFTWProxyType::PixelType*>(fftw_malloc(pieceNbOfPixel*sizeof(FFTWProxyType::PixelType))); - // Inverse FFT of the product of FFT (actually do filtering here) - FFTWProxyType::PlanType outputPlan=FFTWProxyType::Plan_dft_c2r_2d(pieceSize[1],pieceSize[0],multipliedFFTarray,inverseFFTpiece,FFTW_MEASURE); + // Inverse FFT of the product of FFT (actually do filtering here) + FFTWProxyType::PlanType outputPlan=FFTWProxyType::Plan_dft_c2r_2d(pieceSize[1],pieceSize[0],multipliedFFTarray,inverseFFTpiece,FFTW_MEASURE); - // Filling the buffer with complex product values - for(k=0;k<sizeFFT;k++) - { - //complex mutiplication - multipliedFFTarray[k][0]=inputPieceFFT[k][0]*filterPieceFFT[k][0]-inputPieceFFT[k][1]*filterPieceFFT[k][1]; - multipliedFFTarray[k][1]=inputPieceFFT[k][0]*filterPieceFFT[k][1]+inputPieceFFT[k][1]*filterPieceFFT[k][0]; - } + // Filling the buffer with complex product values + for (k=0;k<sizeFFT;k++) + { + //complex mutiplication + multipliedFFTarray[k][0]=inputPieceFFT[k][0]*filterPieceFFT[k][0]-inputPieceFFT[k][1]*filterPieceFFT[k][1]; + multipliedFFTarray[k][1]=inputPieceFFT[k][0]*filterPieceFFT[k][1]+inputPieceFFT[k][1]*filterPieceFFT[k][0]; + } - FFTWProxyType::Execute(outputPlan); + FFTWProxyType::Execute(outputPlan); - // Computing the filter normalization + // Computing the filter normalization - if(m_NormalizeFilter) - { - norm = itk::NumericTraits<InputRealType>::Zero; - for(i=0;i<sizeOfFilter[0]*sizeOfFilter[1];i++) + if (m_NormalizeFilter) + { + norm = itk::NumericTraits<InputRealType>::Zero; + for (i=0;i<sizeOfFilter[0]*sizeOfFilter[1];i++) { norm += static_cast<InputRealType>(m_Filter(i)); } - if(norm == 0.0) + if (norm == 0.0) { norm = 1.0; } - else + else { norm = 1/norm; } - } - else - { - norm = 1.0; - } - - // Fill the ouptut image - it.GoToBegin(); - while(!it.IsAtEnd()) - { - typename InputImageType::IndexType index = it.GetIndex(); - unsigned int linearIndex = (index[1]+sizeOfFilter[1]-1-outputRegionForThread.GetIndex()[1])*pieceSize[0]-1+index[0]+sizeOfFilter[0]-outputRegionForThread.GetIndex()[0]; - it.Set( static_cast<OutputPixelType>((inverseFFTpiece[linearIndex]/pieceNbOfPixel)*static_cast<double>(norm) )); - ++it; - } - - // destroy the FFT plans - FFTWProxyType::DestroyPlan(inputPlan); - FFTWProxyType::DestroyPlan(filterPlan); - FFTWProxyType::DestroyPlan(outputPlan); - - //frees memory - fftw_free(resampledFilterPiece); - fftw_free(inputPiece); - fftw_free(filterPieceFFT); - fftw_free(inputPieceFFT); - fftw_free(multipliedFFTarray); - fftw_free(inverseFFTpiece); -#else - itkGenericExceptionMacro(<<"The OverlapSaveConvolutionImageFilter can not operate without the FFTW library (double implementation). Please install it and set it up in the cmake configuration."); -#endif + } + else + { + norm = 1.0; } - /** Standard "PrintSelf" method */ - template <class TInputImage, class TOutput> void OverlapSaveConvolutionImageFilter<TInputImage, TOutput>::PrintSelf(std::ostream& os,itk::Indent indent) const + // Fill the ouptut image + it.GoToBegin(); + while (!it.IsAtEnd()) { - Superclass::PrintSelf( os, indent ); - os << indent << "Radius: " << m_Radius << std::endl; - os << indent << "Normalize filter: "<<m_NormalizeFilter << std::endl; + typename InputImageType::IndexType index = it.GetIndex(); + unsigned int linearIndex = (index[1]+sizeOfFilter[1]-1-outputRegionForThread.GetIndex()[1])*pieceSize[0]-1+index[0]+sizeOfFilter[0]-outputRegionForThread.GetIndex()[0]; + it.Set( static_cast<OutputPixelType>((inverseFFTpiece[linearIndex]/pieceNbOfPixel)*static_cast<double>(norm) )); + ++it; } + + // destroy the FFT plans + FFTWProxyType::DestroyPlan(inputPlan); + FFTWProxyType::DestroyPlan(filterPlan); + FFTWProxyType::DestroyPlan(outputPlan); + + //frees memory + fftw_free(resampledFilterPiece); + fftw_free(inputPiece); + fftw_free(filterPieceFFT); + fftw_free(inputPieceFFT); + fftw_free(multipliedFFTarray); + fftw_free(inverseFFTpiece); +#else + itkGenericExceptionMacro(<<"The OverlapSaveConvolutionImageFilter can not operate without the FFTW library (double implementation). Please install it and set it up in the cmake configuration."); +#endif +} + +/** Standard "PrintSelf" method */ +template <class TInputImage, class TOutput> void OverlapSaveConvolutionImageFilter<TInputImage, TOutput>::PrintSelf(std::ostream& os,itk::Indent indent) const +{ + Superclass::PrintSelf( os, indent ); + os << indent << "Radius: " << m_Radius << std::endl; + os << indent << "Normalize filter: "<<m_NormalizeFilter << std::endl; +} } // end namespace otb #endif diff --git a/Code/BasicFilters/otbPathMeanDistanceFunctor.h b/Code/BasicFilters/otbPathMeanDistanceFunctor.h index d3a420b108cd79c1d7691b11be91864b541a244e..96e724bcdd135d8238397543c66549a61797b9ab 100644 --- a/Code/BasicFilters/otbPathMeanDistanceFunctor.h +++ b/Code/BasicFilters/otbPathMeanDistanceFunctor.h @@ -23,84 +23,84 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class PathMeanDistanceFunctor - * \brief Functor to select path according to the average distance between points - * - * This functor compute the average distance between each point of a path - * and return true is the distance is above the threshold, false otherwise. - * - * \sa UnaryFunctorObjectListBooleanFilter - * - * \ingroup Functor - */ - template <class TInput1> - class PathMeanDistanceFunctor +/** \class PathMeanDistanceFunctor + * \brief Functor to select path according to the average distance between points + * + * This functor compute the average distance between each point of a path + * and return true is the distance is above the threshold, false otherwise. + * + * \sa UnaryFunctorObjectListBooleanFilter + * + * \ingroup Functor + */ +template <class TInput1> +class PathMeanDistanceFunctor +{ +public: + + + void SetThreshold(double threshold ) { - public: - - - void SetThreshold(double threshold ) - { - m_Threshold = threshold; - } - double GetThreshold(void)const - { - return ( m_Threshold ); - } - - PathMeanDistanceFunctor() - { - m_Threshold = 0.2; - }; - ~PathMeanDistanceFunctor() {}; - - inline bool operator()(const TInput1 & input) - { - - double meanDistance = 0.0; - typedef typename TInput1::ObjectType::VertexListType::ConstIterator VertexListConstIteratorType; - typedef typename TInput1::ObjectType::VertexType VertexType; - VertexListConstIteratorType beginIt = input->GetVertexList()->Begin(); - - VertexType v1 = beginIt.Value(); - VertexType v2 = beginIt.Value(); - ++beginIt; - while (beginIt != input->GetVertexList()->End()) - { - v1 = v2; - v2 = beginIt.Value(); - meanDistance+=vcl_sqrt(vcl_pow(v1[0]-v2[0],2)+vcl_pow(v1[1]-v2[1],2)); - ++beginIt; - } - - double nbVertices = static_cast<double>(input->GetVertexList()->Size()); - if (nbVertices>1) - { - meanDistance = meanDistance / (nbVertices-1); - } - else - { - itkGenericExceptionMacro(<<"Object with only one vertex!" ); - } - - /* std::cout << "Num vertex: " << nbVertices << std::endl; - std::cout << "Mean dist: " << meanDistance << std::endl; -*/ - if ( meanDistance > m_Threshold) - { - return true; - } - else - { - return false; - } - } - - - - private: - double m_Threshold; + m_Threshold = threshold; + } + double GetThreshold(void)const + { + return ( m_Threshold ); + } + + PathMeanDistanceFunctor() + { + m_Threshold = 0.2; }; + ~PathMeanDistanceFunctor() {}; + + inline bool operator()(const TInput1 & input) + { + + double meanDistance = 0.0; + typedef typename TInput1::ObjectType::VertexListType::ConstIterator VertexListConstIteratorType; + typedef typename TInput1::ObjectType::VertexType VertexType; + VertexListConstIteratorType beginIt = input->GetVertexList()->Begin(); + + VertexType v1 = beginIt.Value(); + VertexType v2 = beginIt.Value(); + ++beginIt; + while (beginIt != input->GetVertexList()->End()) + { + v1 = v2; + v2 = beginIt.Value(); + meanDistance+=vcl_sqrt(vcl_pow(v1[0]-v2[0],2)+vcl_pow(v1[1]-v2[1],2)); + ++beginIt; + } + + double nbVertices = static_cast<double>(input->GetVertexList()->Size()); + if (nbVertices>1) + { + meanDistance = meanDistance / (nbVertices-1); + } + else + { + itkGenericExceptionMacro(<<"Object with only one vertex!" ); + } + + /* std::cout << "Num vertex: " << nbVertices << std::endl; + std::cout << "Mean dist: " << meanDistance << std::endl; + */ + if ( meanDistance > m_Threshold) + { + return true; + } + else + { + return false; + } + } + + + +private: + double m_Threshold; +}; } diff --git a/Code/BasicFilters/otbPerBandVectorImageFilter.h b/Code/BasicFilters/otbPerBandVectorImageFilter.h index e27c5ba861b4d751c9214eeec2364fe22dcdc9d1..85ab0477290cdab2b4dee5d2c309a84f907c23b6 100644 --- a/Code/BasicFilters/otbPerBandVectorImageFilter.h +++ b/Code/BasicFilters/otbPerBandVectorImageFilter.h @@ -42,9 +42,9 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TFilter> class ITK_EXPORT PerBandVectorImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef PerBandVectorImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -77,7 +77,7 @@ class ITK_EXPORT PerBandVectorImageFilter typedef VectorImageToImageListFilter<InputVectorImageType,InputImageListType> DecompositionFilterType; typedef typename DecompositionFilterType::Pointer DecompositionFilterPointerType; typedef ImageListToImageListApplyFilter<InputImageListType,OutputImageListType,FilterType> - ProcessingFilterType; + ProcessingFilterType; typedef typename ProcessingFilterType::Pointer ProcessingFilterPointerType; typedef ImageListToVectorImageFilter<OutputImageListType,OutputVectorImageType> RecompositionFilterType; typedef typename RecompositionFilterType::Pointer RecompositionFilterPointerType; @@ -100,7 +100,7 @@ protected: PerBandVectorImageFilter(); /** Destructor */ virtual ~PerBandVectorImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/BasicFilters/otbPerBandVectorImageFilter.txx b/Code/BasicFilters/otbPerBandVectorImageFilter.txx index bce104aa1630b818af1c48860c19fdf7ae85a24b..40ee64578ecfde6e92e22cdb9bd59d513f77bd7a 100644 --- a/Code/BasicFilters/otbPerBandVectorImageFilter.txx +++ b/Code/BasicFilters/otbPerBandVectorImageFilter.txx @@ -38,17 +38,17 @@ void PerBandVectorImageFilter<TInputImage,TOutputImage,TFilter> ::GenerateOutputInformation() { - if(this->GetInput()) - { - // Create a false monoband image - typename InputImageType::Pointer dummyInputImage = InputImageType::New(); - dummyInputImage->CopyInformation(this->GetInput()); - dummyInputImage->SetNumberOfComponentsPerPixel(1); - m_Filter->SetInput(dummyInputImage); - m_Filter->UpdateOutputInformation(); - this->GetOutput()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); - this->GetOutput()->SetNumberOfComponentsPerPixel(this->GetInput()->GetNumberOfComponentsPerPixel()); - } + if (this->GetInput()) + { + // Create a false monoband image + typename InputImageType::Pointer dummyInputImage = InputImageType::New(); + dummyInputImage->CopyInformation(this->GetInput()); + dummyInputImage->SetNumberOfComponentsPerPixel(1); + m_Filter->SetInput(dummyInputImage); + m_Filter->UpdateOutputInformation(); + this->GetOutput()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); + this->GetOutput()->SetNumberOfComponentsPerPixel(this->GetInput()->GetNumberOfComponentsPerPixel()); + } } template <class TInputImage, class TOutputImage, class TFilter> diff --git a/Code/BasicFilters/otbPersistentVectorizationImageFilter.h b/Code/BasicFilters/otbPersistentVectorizationImageFilter.h index d3442658d53b3b4290a884d5577f6e3b117e13b5..6b27aede59a6a2e4935f54c79587749b4e4cd71e 100644 --- a/Code/BasicFilters/otbPersistentVectorizationImageFilter.h +++ b/Code/BasicFilters/otbPersistentVectorizationImageFilter.h @@ -27,79 +27,80 @@ #include "otbImageToEdgePathFilter.h" #include "itkMinimumMaximumImageFilter.h" -namespace otb { - - /** \class PersistentVectorizationImageFilter - * \brief Perform vectorization in a persistent way. - * - * This filter allows to vectorize input labeled image while it is streamed - * through it. The GetPathList() method allows to get the vectorized boundaries, - * while the GetOutput() method allows to get the input image itself. - * - * The Reset() method allows to clear the result path list. - * - * \sa PersistentImageFilter - * - */ - template<class TInputImage, class TOutputPath> - class ITK_EXPORT PersistentVectorizationImageFilter : - public PersistentImageFilter<TInputImage, TInputImage> - { - public: - /** Standard Self typedef */ - typedef PersistentVectorizationImageFilter Self; - typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Runtime information support. */ - itkTypeMacro(PersistentVectorizationImageFilter, PersistentImageFilter); - - /** Image related typedefs. */ - // First Input - typedef TInputImage ImageType; - typedef typename TInputImage::Pointer InputImagePointer; - typedef typename TInputImage::RegionType RegionType; - typedef typename TInputImage::SizeType SizeType; - typedef typename TInputImage::IndexType IndexType; - typedef typename TInputImage::PixelType PixelType; - typedef typename TInputImage::InternalPixelType InternalPixelType; - - // Output path type - typedef TOutputPath PathType; - typedef otb::ObjectList<PathType> PathListType; - typedef typename PathListType::Pointer PathListPointerType; - typedef typename PathType::Pointer PathPointerType; - typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType; - typedef typename MinMaxFilterType::Pointer MinMaxFilterPointerType; - typedef otb::ImageToEdgePathFilter<ImageType,PathType> ImageToEdgePathFilterType; - typedef typename ImageToEdgePathFilterType::Pointer ImageToEdgePathFilterPointerType; - - virtual void Reset(void); - virtual void Synthetize(void); - - itkGetObjectMacro(PathList,PathListType); - - protected: - PersistentVectorizationImageFilter(); - ~PersistentVectorizationImageFilter(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; - virtual void GenerateData(); - - private: - PersistentVectorizationImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - // Min max filter (the mini-pipeline) - MinMaxFilterPointerType m_MinMaxFilter; - - // Where to store the vectorized objects - PathListPointerType m_PathList; - - }; // end of class +namespace otb +{ + +/** \class PersistentVectorizationImageFilter + * \brief Perform vectorization in a persistent way. + * + * This filter allows to vectorize input labeled image while it is streamed + * through it. The GetPathList() method allows to get the vectorized boundaries, + * while the GetOutput() method allows to get the input image itself. + * + * The Reset() method allows to clear the result path list. + * + * \sa PersistentImageFilter + * + */ +template<class TInputImage, class TOutputPath> +class ITK_EXPORT PersistentVectorizationImageFilter : + public PersistentImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard Self typedef */ + typedef PersistentVectorizationImageFilter Self; + typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(PersistentVectorizationImageFilter, PersistentImageFilter); + + /** Image related typedefs. */ + // First Input + typedef TInputImage ImageType; + typedef typename TInputImage::Pointer InputImagePointer; + typedef typename TInputImage::RegionType RegionType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType PixelType; + typedef typename TInputImage::InternalPixelType InternalPixelType; + + // Output path type + typedef TOutputPath PathType; + typedef otb::ObjectList<PathType> PathListType; + typedef typename PathListType::Pointer PathListPointerType; + typedef typename PathType::Pointer PathPointerType; + typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType; + typedef typename MinMaxFilterType::Pointer MinMaxFilterPointerType; + typedef otb::ImageToEdgePathFilter<ImageType,PathType> ImageToEdgePathFilterType; + typedef typename ImageToEdgePathFilterType::Pointer ImageToEdgePathFilterPointerType; + + virtual void Reset(void); + virtual void Synthetize(void); + + itkGetObjectMacro(PathList,PathListType); + +protected: + PersistentVectorizationImageFilter(); + ~PersistentVectorizationImageFilter() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; + virtual void GenerateData(); + +private: + PersistentVectorizationImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + // Min max filter (the mini-pipeline) + MinMaxFilterPointerType m_MinMaxFilter; + + // Where to store the vectorized objects + PathListPointerType m_PathList; + +}; // end of class } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/BasicFilters/otbPersistentVectorizationImageFilter.txx b/Code/BasicFilters/otbPersistentVectorizationImageFilter.txx index 4eb1c9a52943d458b5f446efe1017ce15a1a7030..0b53372bfa0f6c87d4da2af4000902eebf08ed0b 100644 --- a/Code/BasicFilters/otbPersistentVectorizationImageFilter.txx +++ b/Code/BasicFilters/otbPersistentVectorizationImageFilter.txx @@ -25,7 +25,8 @@ #include "itkProgressReporter.h" -namespace otb { +namespace otb +{ template<class TInputImage, class TOutputPath> PersistentVectorizationImageFilter<TInputImage, TOutputPath> @@ -63,14 +64,14 @@ PersistentVectorizationImageFilter<TInputImage, TOutputPath> - for(PixelType label = m_MinMaxFilter->GetMinimum()+1; label<=m_MinMaxFilter->GetMaximum(); ++label) - { - ImageToEdgePathFilterPointerType edgeFilter = ImageToEdgePathFilterType::New(); - edgeFilter->SetInput(m_MinMaxFilter->GetOutput()); - edgeFilter->SetForegroundValue(label); - edgeFilter->Update(); - m_PathList->PushBack(edgeFilter->GetOutput()); - } + for (PixelType label = m_MinMaxFilter->GetMinimum()+1; label<=m_MinMaxFilter->GetMaximum(); ++label) + { + ImageToEdgePathFilterPointerType edgeFilter = ImageToEdgePathFilterType::New(); + edgeFilter->SetInput(m_MinMaxFilter->GetOutput()); + edgeFilter->SetForegroundValue(label); + edgeFilter->Update(); + m_PathList->PushBack(edgeFilter->GetOutput()); + } } template<class TInputImage, class TOutputPath> diff --git a/Code/BasicFilters/otbPointSetDensityFunction.h b/Code/BasicFilters/otbPointSetDensityFunction.h index 0e2d78c28b9c4718741a4875b145133583345193..e28a7aca6a8848d5c81927be57b9c6c0b4d46af1 100644 --- a/Code/BasicFilters/otbPointSetDensityFunction.h +++ b/Code/BasicFilters/otbPointSetDensityFunction.h @@ -32,7 +32,7 @@ namespace otb * \ingroup PointSetFunctions */ template <class TPointSet, class TOutput> - class ITK_EXPORT PointSetDensityFunction : public PointSetFunction< TPointSet , TOutput > +class ITK_EXPORT PointSetDensityFunction : public PointSetFunction< TPointSet , TOutput > { public: /** Standard class typedefs. */ @@ -41,46 +41,46 @@ public: typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - + /** Run-time type information (and related methods). */ itkTypeMacro(PointSetDensityFunction, PointSetFunction); - + /** Method for creation through the object factory. */ - itkNewMacro(Self); + itkNewMacro(Self); /** PointSet Type typedef Support*/ typedef TPointSet PointSetType; typedef typename Superclass::InputType InputType; typedef typename PointSetType::Pointer PointSetPointerType; - + /** TOutput typedef suppoty*/ typedef TOutput OutputType; /** Set/Get the number of scales*/ itkSetMacro(Radius,unsigned int); itkGetMacro(Radius,unsigned int); - + /** Evaluate Method */ virtual OutputType Evaluate(const InputType& input ) const; - + protected: PointSetDensityFunction(); - ~PointSetDensityFunction(){}; + ~PointSetDensityFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; - + private: PointSetDensityFunction( const Self& ); //purposely not implemented void operator=( const Self& ); //purposely not implemented - + unsigned int m_Radius; }; } // end namespace otb -#ifndef OTB_MANUAL_INSTANTIATION +#ifndef OTB_MANUAL_INSTANTIATION #include "otbPointSetDensityFunction.txx" #endif diff --git a/Code/BasicFilters/otbPointSetDensityFunction.txx b/Code/BasicFilters/otbPointSetDensityFunction.txx index 45b01f5a5dc77a0a8078af96154b686715c67f09..a03d952ff843744d5fa161cbdbe38cbddb902bbb 100644 --- a/Code/BasicFilters/otbPointSetDensityFunction.txx +++ b/Code/BasicFilters/otbPointSetDensityFunction.txx @@ -40,40 +40,40 @@ PointSetDensityFunction< TPointSet, TOutput> /** * */ -template <class TPointSet, class TOutput > +template <class TPointSet, class TOutput > typename PointSetDensityFunction< TPointSet, TOutput> ::OutputType PointSetDensityFunction< TPointSet, TOutput> ::Evaluate(const InputType& input ) const { - + typename otb::Image<OutputType,2>::IndexType index; index[0] = input[0]; index[1] = input[1]; - + int accu = 0; double surface = M_PI*vcl_pow(2.,static_cast<double>(m_Radius)); - - if(this->GetPointSet()->GetNumberOfPoints() != 0) + + if (this->GetPointSet()->GetNumberOfPoints() != 0) + { + typedef typename TPointSet::PointsContainer::ConstIterator iteratorType; + iteratorType it = this->GetPointSet()->GetPoints()->Begin(); + + while ( it != this->GetPointSet()->GetPoints()->End()) { - typedef typename TPointSet::PointsContainer::ConstIterator iteratorType; - iteratorType it = this->GetPointSet()->GetPoints()->Begin(); - - while( it != this->GetPointSet()->GetPoints()->End()) - { - float distX2 =( index[0]-it.Value()[0])*( index[0]-it.Value()[0]); - float distY2 =( index[1]-it.Value()[1])*( index[1]-it.Value()[1]); - float dist = vcl_sqrt(distX2 + distY2); - - if(dist <= m_Radius) - accu++; - - ++it; - } + float distX2 =( index[0]-it.Value()[0])*( index[0]-it.Value()[0]); + float distY2 =( index[1]-it.Value()[1])*( index[1]-it.Value()[1]); + float dist = vcl_sqrt(distX2 + distY2); + + if (dist <= m_Radius) + accu++; + + ++it; } + } else return 0.; - + return static_cast<float>(accu/surface); } @@ -81,7 +81,7 @@ PointSetDensityFunction< TPointSet, TOutput> /** * */ -template <class TPointSet, class TOutput > +template <class TPointSet, class TOutput > void PointSetDensityFunction< TPointSet, TOutput> ::PrintSelf(std::ostream& os, itk::Indent indent) const diff --git a/Code/BasicFilters/otbPointSetFunction.h b/Code/BasicFilters/otbPointSetFunction.h index 399d8a45a3e73f1d807c1776f864dfb612eb62bc..480362d98e166fd013566169805d6426b980319f 100644 --- a/Code/BasicFilters/otbPointSetFunction.h +++ b/Code/BasicFilters/otbPointSetFunction.h @@ -32,38 +32,38 @@ namespace otb * \ingroup SpatialFunctions */ template <class TPointSet, class TOutput> - class ITK_EXPORT PointSetFunction : - public itk::SpatialFunction< TOutput , 2/* TODO : change 2 by PointType::PointDimension*/, typename TPointSet::PointType > +class ITK_EXPORT PointSetFunction : + public itk::SpatialFunction< TOutput , 2/* TODO : change 2 by PointType::PointDimension*/, typename TPointSet::PointType > { public: /** Standard class typedefs. */ -typedef PointSetFunction Self; - typedef itk::SpatialFunction< TOutput, 2 , typename TPointSet::PointType > Superclass; - + typedef PointSetFunction Self; + typedef itk::SpatialFunction< TOutput, 2 , typename TPointSet::PointType > Superclass; + /** Run-time type information (and related methods). */ itkTypeMacro(PointSetFunction, itk::SpatialFunction); - + /** PointSet Type typedef Support*/ typedef TPointSet PointSetType; typedef typename PointSetType::Pointer PointSetPointerType; - + /** TOutput typedef suppoty*/ typedef TOutput OutputType; - + /** Set the input image (reimplemented since we need to set the detector input) */ itkGetConstObjectMacro(PointSet,PointSetType); void SetPointSet( PointSetType* PointSet) - { - m_PointSet = PointSet; - } - + { + m_PointSet = PointSet; + } + protected: PointSetFunction(); - ~PointSetFunction(){}; + ~PointSetFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; - + private: PointSetFunction( const Self& ); //purposely not implemented @@ -76,7 +76,7 @@ private: } // end namespace otb -#ifndef OTB_MANUAL_INSTANTIATION +#ifndef OTB_MANUAL_INSTANTIATION #include "otbPointSetFunction.txx" #endif diff --git a/Code/BasicFilters/otbPointSetFunction.txx b/Code/BasicFilters/otbPointSetFunction.txx index a11425eb0496175e3ab112c310e432d0105169fe..73638b63089965b00d367aa03bb1a525e11fe8ba 100644 --- a/Code/BasicFilters/otbPointSetFunction.txx +++ b/Code/BasicFilters/otbPointSetFunction.txx @@ -40,19 +40,19 @@ PointSetFunction< TPointSet, TOutput> /** * */ -template <class TPointSet, class TOutput > +template <class TPointSet, class TOutput > void PointSetFunction< TPointSet, TOutput> ::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os,indent); - } +} // /** // * SetDetector method // */ -// template <class TPointSet, class TOutput > +// template <class TPointSet, class TOutput > // void // PointSetFunction< TPointSet, TOutput> // ::SetPointSet(PointSetType* PointSet) const @@ -63,7 +63,7 @@ PointSetFunction< TPointSet, TOutput> // /** // * GetDetector method // */ -// template <class TPointSet, class TOutput > +// template <class TPointSet, class TOutput > // const // typename PointSetFunction< TPointSet,TOutput> // ::PointSetType * diff --git a/Code/BasicFilters/otbPointSetToDensityImageFilter.h b/Code/BasicFilters/otbPointSetToDensityImageFilter.h index 9a7e0f0bd6cb47505e4a10e193cb2e228363ba1b..0cf17a5960338cfca586ad3870cb49300101e15d 100644 --- a/Code/BasicFilters/otbPointSetToDensityImageFilter.h +++ b/Code/BasicFilters/otbPointSetToDensityImageFilter.h @@ -32,81 +32,81 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputPointSet , class TOutputImage> - class ITK_EXPORT PointSetToDensityImageFilter - : public itk::PointSetToImageFilter<TInputPointSet, TOutputImage > - { - - public: - - /** Standard class typedefs. */ - typedef PointSetToDensityImageFilter Self; - typedef itk::PointSetToImageFilter<TInputPointSet, TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(PointSetToDensityImageFilter,itk::PointSetToImageFilter); - - - - /** typedefs parameters support */ - typedef TInputPointSet PointSetType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::PixelType PixelType; - typedef typename OutputImageType::IndexType IndexType; - - /** typedef filter support*/ - typedef otb::PointSetDensityFunction<PointSetType , PixelType> PointSetDensityFunctionType; - typedef typename PointSetDensityFunctionType::InputType InputType; - typedef typename PointSetDensityFunctionType::Pointer PointSetDensityFunctionPointerType; - - - /** Set/Get Radius*/ - itkGetMacro(Radius, unsigned int); - itkSetMacro(Radius, unsigned int); - - /** PointSet Set/Get*/ - // itkSetObjectMacro(PointSet,PointSetType); - //itkGetObjectMacro(PointSet,PointSetType); - - - protected: - - /** - * Constructor. - */ - PointSetToDensityImageFilter(); - /** - * Destructor. - */ - virtual ~PointSetToDensityImageFilter(); - /** - * Standard PrintSelf method. - */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Main computation method. - */ - virtual void GenerateData(); - /** - * Main computation method. - */ - virtual void GenerateOutputInformation(); - - - private: - - PointSetToDensityImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - unsigned int m_Radius; - typename PointSetType::Pointer m_PointSet; - }; +template <class TInputPointSet , class TOutputImage> +class ITK_EXPORT PointSetToDensityImageFilter + : public itk::PointSetToImageFilter<TInputPointSet, TOutputImage > +{ + +public: + + /** Standard class typedefs. */ + typedef PointSetToDensityImageFilter Self; + typedef itk::PointSetToImageFilter<TInputPointSet, TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(PointSetToDensityImageFilter,itk::PointSetToImageFilter); + + + + /** typedefs parameters support */ + typedef TInputPointSet PointSetType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::PixelType PixelType; + typedef typename OutputImageType::IndexType IndexType; + + /** typedef filter support*/ + typedef otb::PointSetDensityFunction<PointSetType , PixelType> PointSetDensityFunctionType; + typedef typename PointSetDensityFunctionType::InputType InputType; + typedef typename PointSetDensityFunctionType::Pointer PointSetDensityFunctionPointerType; + + + /** Set/Get Radius*/ + itkGetMacro(Radius, unsigned int); + itkSetMacro(Radius, unsigned int); + + /** PointSet Set/Get*/ + // itkSetObjectMacro(PointSet,PointSetType); + //itkGetObjectMacro(PointSet,PointSetType); + + +protected: + + /** + * Constructor. + */ + PointSetToDensityImageFilter(); + /** + * Destructor. + */ + virtual ~PointSetToDensityImageFilter(); + /** + * Standard PrintSelf method. + */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Main computation method. + */ + virtual void GenerateData(); + /** + * Main computation method. + */ + virtual void GenerateOutputInformation(); + + +private: + + PointSetToDensityImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + unsigned int m_Radius; + typename PointSetType::Pointer m_PointSet; +}; } #ifndef OTB_MANUAL_INSTANTIATION #include "otbPointSetToDensityImageFilter.txx" diff --git a/Code/BasicFilters/otbPointSetToDensityImageFilter.txx b/Code/BasicFilters/otbPointSetToDensityImageFilter.txx index b1c304410ec4f59551f06789b3935b9e14da9e3e..28faafb753e5f40f94582750bb2147d1b4ec547e 100644 --- a/Code/BasicFilters/otbPointSetToDensityImageFilter.txx +++ b/Code/BasicFilters/otbPointSetToDensityImageFilter.txx @@ -24,97 +24,97 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /**--------------------------------------------------------- - * Constructor - ----------------------------------------------------------*/ - template <class TInputPointSet , class TOutputImage > - PointSetToDensityImageFilter< TInputPointSet , TOutputImage > - ::PointSetToDensityImageFilter() - { - m_Radius = 1; - } +/**--------------------------------------------------------- + * Constructor + ----------------------------------------------------------*/ +template <class TInputPointSet , class TOutputImage > +PointSetToDensityImageFilter< TInputPointSet , TOutputImage > +::PointSetToDensityImageFilter() +{ + m_Radius = 1; +} - /*--------------------------------------------------------- - * Destructor.c - ----------------------------------------------------------*/ - template <class TInputPointSet , class TOutputImage > - PointSetToDensityImageFilter< TInputPointSet , TOutputImage > - ::~PointSetToDensityImageFilter() - {} +/*--------------------------------------------------------- + * Destructor.c + ----------------------------------------------------------*/ +template <class TInputPointSet , class TOutputImage > +PointSetToDensityImageFilter< TInputPointSet , TOutputImage > +::~PointSetToDensityImageFilter() +{} - /*------------------------------------------------------- - * Generate Data - --------------------------------------------------------*/ - template <class TInputPointSet , class TOutputImage > - void - PointSetToDensityImageFilter< TInputPointSet , TOutputImage> - ::GenerateData(void) +/*------------------------------------------------------- + * Generate Data + --------------------------------------------------------*/ +template <class TInputPointSet , class TOutputImage > +void +PointSetToDensityImageFilter< TInputPointSet , TOutputImage> +::GenerateData(void) +{ + this->AllocateOutputs(); + + PointSetDensityFunctionPointerType densityComputeFunction = PointSetDensityFunctionType::New(); + densityComputeFunction->SetPointSet(const_cast<PointSetType*>(this->GetInput())); + densityComputeFunction->SetRadius(m_Radius); + + /** Point*/ + InputType pCenter; + IndexType index; + itk::ImageRegionIterator<OutputImageType> itOut(this->GetOutput(), + this->GetOutput()->GetLargestPossibleRegion()); + itOut.GoToBegin(); + + while (!itOut.IsAtEnd()) { - this->AllocateOutputs(); - - PointSetDensityFunctionPointerType densityComputeFunction = PointSetDensityFunctionType::New(); - densityComputeFunction->SetPointSet(const_cast<PointSetType*>(this->GetInput())); - densityComputeFunction->SetRadius(m_Radius); - - /** Point*/ - InputType pCenter; - IndexType index; - itk::ImageRegionIterator<OutputImageType> itOut(this->GetOutput(), - this->GetOutput()->GetLargestPossibleRegion()); - itOut.GoToBegin(); - - while(!itOut.IsAtEnd()) - { - index = itOut.GetIndex(); - pCenter[0] = index[0]; - pCenter[1] = index[1]; - - itOut.Set(densityComputeFunction->Evaluate(pCenter)); - ++itOut; - } - }/** End of GenerateData()*/ + index = itOut.GetIndex(); + pCenter[0] = index[0]; + pCenter[1] = index[1]; + + itOut.Set(densityComputeFunction->Evaluate(pCenter)); + ++itOut; + } +}/** End of GenerateData()*/ /*------------------------------------------------------- * Generate Data --------------------------------------------------------*/ - template <class TInputPointSet , class TOutputImage > - void - PointSetToDensityImageFilter< TInputPointSet , TOutputImage> - ::GenerateOutputInformation(void) - { - //Superclass::GenerateOutputInformation(); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); +template <class TInputPointSet , class TOutputImage > +void +PointSetToDensityImageFilter< TInputPointSet , TOutputImage> +::GenerateOutputInformation(void) +{ + //Superclass::GenerateOutputInformation(); + typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - if ( !outputPtr ) - { + if ( !outputPtr ) + { return; - } - + } + typename OutputImageType::RegionType region; IndexType start ; start.Fill(0); - + region.SetSize(this->GetSize()); region.SetIndex(start); - + outputPtr->SetOrigin(this->GetOrigin()); outputPtr->SetSpacing(this->GetSpacing()); outputPtr->SetRegions( region ); - - - }/** End of GenerateoutputInformation*/ - - - /*---------------------------------------------------------------- - PrintSelf - -----------------------------------------------------------------*/ - template <class TInputPointSet , class TOutputImage > - void - PointSetToDensityImageFilter< TInputPointSet , TOutputImage > - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } + + +}/** End of GenerateoutputInformation*/ + + +/*---------------------------------------------------------------- + PrintSelf + -----------------------------------------------------------------*/ +template <class TInputPointSet , class TOutputImage > +void +PointSetToDensityImageFilter< TInputPointSet , TOutputImage > +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } diff --git a/Code/BasicFilters/otbPolygonCompacityFunctor.h b/Code/BasicFilters/otbPolygonCompacityFunctor.h index 8b3319b54f2beaeff057f49a8fdcdccf015130e2..3f667bc141d421980da8e83fe3a662c9d944a886 100644 --- a/Code/BasicFilters/otbPolygonCompacityFunctor.h +++ b/Code/BasicFilters/otbPolygonCompacityFunctor.h @@ -23,62 +23,62 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class PolygonCompacityFunctor - * \brief Select polygons according to their compacity - * - * This functor compute the compacity of a polygon - * and return true is the distance is above the threshold, false otherwise. - * - * The compacity is defined as: - * - * \f$ 4\pi \frac{S}{L}\f$ - * - * where \f$ S \f$ is the surface (obtained by the method GetSurface() ) - * and \f$ L \f$ the perimeter (obtained by the method GetLength() ). - * - * \ingroup Functor - */ - template <class TInput1> - class PolygonCompacityFunctor +/** \class PolygonCompacityFunctor + * \brief Select polygons according to their compacity + * +* This functor compute the compacity of a polygon +* and return true is the distance is above the threshold, false otherwise. +* +* The compacity is defined as: +* +* \f$ 4\pi \frac{S}{L}\f$ +* +* where \f$ S \f$ is the surface (obtained by the method GetSurface() ) +* and \f$ L \f$ the perimeter (obtained by the method GetLength() ). + * + * \ingroup Functor + */ +template <class TInput1> +class PolygonCompacityFunctor +{ +public: + + + void SetThreshold(double threshold ) + { + m_Threshold = threshold; + } + double GetThreshold(void)const + { + return ( m_Threshold ); + } + + PolygonCompacityFunctor() { - public: - - - void SetThreshold(double threshold ) - { - m_Threshold = threshold; - } - double GetThreshold(void)const - { - return ( m_Threshold ); - } - - PolygonCompacityFunctor() - { - m_Threshold = 0.2; - }; - ~PolygonCompacityFunctor() {}; - - inline bool operator()(const TInput1 & input) - { - double circularityRatio = 4*M_PI*input->GetSurface() - / M_SQUARE(input->GetLength()); - - if (circularityRatio > m_Threshold) - { - return true; - } - else - { - return false; - } - } - - - - private: - double m_Threshold; + m_Threshold = 0.2; }; + ~PolygonCompacityFunctor() {}; + + inline bool operator()(const TInput1 & input) + { + double circularityRatio = 4*M_PI*input->GetSurface() + / M_SQUARE(input->GetLength()); + + if (circularityRatio > m_Threshold) + { + return true; + } + else + { + return false; + } + } + + + +private: + double m_Threshold; +}; } diff --git a/Code/BasicFilters/otbPrintableImageFilter.h b/Code/BasicFilters/otbPrintableImageFilter.h index 9ca4e9831035a8404fd2493203037ff41f165738..80d2687c227b93a5ffde71579a53d4105d771aff 100644 --- a/Code/BasicFilters/otbPrintableImageFilter.h +++ b/Code/BasicFilters/otbPrintableImageFilter.h @@ -26,49 +26,50 @@ #include "otbVectorRescaleIntensityImageFilter.h" #include "otbMultiChannelExtractROI.h" -namespace otb { - /** - * \class PrintableImageFilter - * \brief This class is a helper class to turn a vector image to a generic 8 bytes RGB image. - * - * It is useful for publications for instance. - **/ - - template <class TInputImage> +namespace otb +{ +/** + * \class PrintableImageFilter + * \brief This class is a helper class to turn a vector image to a generic 8 bytes RGB image. + * + * It is useful for publications for instance. + **/ + +template <class TInputImage> class ITK_EXPORT PrintableImageFilter : - public itk::ImageToImageFilter<TInputImage, otb::VectorImage<unsigned char,2> > - { - public: - typedef PrintableImageFilter Self; - typedef itk::ImageToImageFilter - <TInputImage, otb::VectorImage<unsigned char,2> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + public itk::ImageToImageFilter<TInputImage, otb::VectorImage<unsigned char,2> > +{ +public: + typedef PrintableImageFilter Self; + typedef itk::ImageToImageFilter + <TInputImage, otb::VectorImage<unsigned char,2> > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; typedef TInputImage InputImageType; typedef typename InputImageType::PixelType InputPixelType; typedef unsigned char OutputPixelType; - typedef otb::VectorImage<OutputPixelType,2> OutputImageType; + typedef otb::VectorImage<OutputPixelType,2> OutputImageType; - typedef otb::VectorRescaleIntensityImageFilter - <InputImageType,OutputImageType> VectorRescalerType; - typedef otb::MultiChannelExtractROI - <OutputPixelType,OutputPixelType> ChannelExtractorType; - typedef typename ChannelExtractorType::ChannelsType ChannelsType; + typedef otb::VectorRescaleIntensityImageFilter + <InputImageType,OutputImageType> VectorRescalerType; + typedef otb::MultiChannelExtractROI + <OutputPixelType,OutputPixelType> ChannelExtractorType; + typedef typename ChannelExtractorType::ChannelsType ChannelsType; - /** Method for creation through object factory */ - itkNewMacro(Self); + /** Method for creation through object factory */ + itkNewMacro(Self); - /** Run-time type information */ - itkTypeMacro(PrintableImageFilter, - itk::ImageToImageFilter); + /** Run-time type information */ + itkTypeMacro(PrintableImageFilter, + itk::ImageToImageFilter); - /** Display */ - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + /** Display */ + void PrintSelf( std::ostream& os, itk::Indent indent ) const; - void SetChannel( unsigned int channel); - const ChannelsType GetChannels(void) const; + void SetChannel( unsigned int channel); + const ChannelsType GetChannels(void) const; otbSetObjectMemberMacro(Rescaler,AutomaticInputMinMaxComputation,bool); otbGetObjectMemberMacro(Rescaler,AutomaticInputMinMaxComputation,bool); @@ -77,20 +78,20 @@ class ITK_EXPORT PrintableImageFilter : otbSetObjectMemberMacro(Rescaler,InputMaximum,InputPixelType); otbGetObjectMemberMacro(Rescaler,InputMaximum,InputPixelType); - protected: +protected: - PrintableImageFilter(); + PrintableImageFilter(); - void GenerateData(); + void GenerateData(); - private: +private: - PrintableImageFilter(Self&); // intentionally not implemented - void operator=(const Self&); // intentionally not implemented + PrintableImageFilter(Self&); // intentionally not implemented + void operator=(const Self&); // intentionally not implemented - typename VectorRescalerType::Pointer m_Rescaler; - typename ChannelExtractorType::Pointer m_Extractor; - }; + typename VectorRescalerType::Pointer m_Rescaler; + typename ChannelExtractorType::Pointer m_Extractor; +}; } // end namespace otb diff --git a/Code/BasicFilters/otbPrintableImageFilter.txx b/Code/BasicFilters/otbPrintableImageFilter.txx index e65efcd6c04f07ec852d69176f92faf9e65cb42b..d094287d5a6210194ef46ee79ad719f5bcfaafdf 100644 --- a/Code/BasicFilters/otbPrintableImageFilter.txx +++ b/Code/BasicFilters/otbPrintableImageFilter.txx @@ -27,71 +27,72 @@ namespace otb { - template <class TInputImage> - PrintableImageFilter<TInputImage> - ::PrintableImageFilter() - { +template <class TInputImage> +PrintableImageFilter<TInputImage> +::PrintableImageFilter() +{ - m_Rescaler = VectorRescalerType::New(); - m_Extractor = ChannelExtractorType::New(); + m_Rescaler = VectorRescalerType::New(); + m_Extractor = ChannelExtractorType::New(); - m_Extractor->SetInput( m_Rescaler->GetOutput() ); + m_Extractor->SetInput( m_Rescaler->GetOutput() ); - } +} - template <class TInputImage> - void - PrintableImageFilter<TInputImage> - ::SetChannel(unsigned int channel) - { - m_Extractor->SetChannel(channel); - this->Modified(); - } +template <class TInputImage> +void +PrintableImageFilter<TInputImage> +::SetChannel(unsigned int channel) +{ + m_Extractor->SetChannel(channel); + this->Modified(); +} + +template <class TInputImage> +const typename PrintableImageFilter<TInputImage>::ChannelsType +PrintableImageFilter<TInputImage> +::GetChannels() const +{ + return m_Extractor->GetChannels(); +} - template <class TInputImage> - const typename PrintableImageFilter<TInputImage>::ChannelsType - PrintableImageFilter<TInputImage> - ::GetChannels() const - { - return m_Extractor->GetChannels(); - } +template <class TInputImage> +void +PrintableImageFilter<TInputImage> +::GenerateData() +{ - template <class TInputImage> - void - PrintableImageFilter<TInputImage> - ::GenerateData() + if (m_Extractor->GetNbChannels() == 0) { - - if(m_Extractor->GetNbChannels() == 0){ - m_Extractor->SetChannel(2); - m_Extractor->SetChannel(3); - m_Extractor->SetChannel(4); - } - - typename TInputImage::PixelType minimum,maximum; - minimum.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel()); - maximum.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel()); - minimum.Fill(0); - maximum.Fill(255); - - m_Rescaler->SetInput(this->GetInput()); - m_Rescaler->SetOutputMinimum(minimum); - m_Rescaler->SetOutputMaximum(maximum); - m_Rescaler->SetClampThreshold(0.01); - - m_Extractor->GraftOutput( this->GetOutput() ); - m_Extractor->Update(); - this->GraftOutput( m_Extractor->GetOutput() ); + m_Extractor->SetChannel(2); + m_Extractor->SetChannel(3); + m_Extractor->SetChannel(4); } - template <class TInputImage> - void - PrintableImageFilter<TInputImage> - ::PrintSelf( std::ostream& os, itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - } + typename TInputImage::PixelType minimum,maximum; + minimum.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel()); + maximum.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel()); + minimum.Fill(0); + maximum.Fill(255); + + m_Rescaler->SetInput(this->GetInput()); + m_Rescaler->SetOutputMinimum(minimum); + m_Rescaler->SetOutputMaximum(maximum); + m_Rescaler->SetClampThreshold(0.01); + + m_Extractor->GraftOutput( this->GetOutput() ); + m_Extractor->Update(); + this->GraftOutput( m_Extractor->GetOutput() ); +} + +template <class TInputImage> +void +PrintableImageFilter<TInputImage> +::PrintSelf( std::ostream& os, itk::Indent indent ) const +{ + Superclass::PrintSelf(os,indent); +} } // end namespace otb diff --git a/Code/BasicFilters/otbProlateInterpolateImageFunction.h b/Code/BasicFilters/otbProlateInterpolateImageFunction.h index c5c64e001a6c3ed5c564a380c7ba44ef5f2f6025..b3435b5691b4c32186964ab8b2d3722889069c17 100644 --- a/Code/BasicFilters/otbProlateInterpolateImageFunction.h +++ b/Code/BasicFilters/otbProlateInterpolateImageFunction.h @@ -28,64 +28,79 @@ namespace otb namespace Function { - /** \class ProlateFunction - * - * \brief Prolate function give the value of the prolate profile following - * one of the 2 image dimension. - * - */ +/** \class ProlateFunction + * + * \brief Prolate function give the value of the prolate profile following + * one of the 2 image dimension. + * + */ template<class TInput, class TOutput> class ProlateFunction { - public: - ProlateFunction(){ m_Radius = 1; }; - ~ProlateFunction(){}; +public: + ProlateFunction() + { + m_Radius = 1; + }; + ~ProlateFunction() {}; typedef std::vector<double> VectorType; // Accessors definitions - void SetRadius(unsigned int rad){ m_Radius = rad; } - unsigned int GetRadius() const { return m_Radius; } - unsigned int GetOriginalProfileSize() const { return m_OriginalProfileSize; } - VectorType GetOriginalProfile() const { return m_OriginalProfile;} + void SetRadius(unsigned int rad) + { + m_Radius = rad; + } + unsigned int GetRadius() const + { + return m_Radius; + } + unsigned int GetOriginalProfileSize() const + { + return m_OriginalProfileSize; + } + VectorType GetOriginalProfile() const + { + return m_OriginalProfile; + } double ComputeEnergy(double resampleRatio); inline TOutput operator()( const TInput & A ) const - { - TOutput val = itk::NumericTraits< TOutput >::Zero; - if ( A != itk::NumericTraits< TInput >::Zero && vcl_abs(A) != static_cast<TInput>(m_Radius) && m_Radius!=0 ) { - double ival = static_cast<double>(m_OriginalProfileSize)*static_cast<double>(vcl_abs(A))/static_cast<double>(m_Radius); - double ivalFloor = vcl_floor(ival); - double left = ival - ivalFloor; - - if ( ivalFloor < m_OriginalProfileSize-1 ) - { - val = left*m_OriginalProfile[static_cast<unsigned int>(ivalFloor)] + (1-left)*m_OriginalProfile[static_cast<unsigned int>(ivalFloor)+1]; - } - else - { - itkGenericExceptionMacro(<<"Out of Profile limits ("<<ivalFloor<<" -1 > 721)"); - - } - } + TOutput val = itk::NumericTraits< TOutput >::Zero; + if ( A != itk::NumericTraits< TInput >::Zero && vcl_abs(A) != static_cast<TInput>(m_Radius) && m_Radius!=0 ) + { + double ival = static_cast<double>(m_OriginalProfileSize)*static_cast<double>(vcl_abs(A))/static_cast<double>(m_Radius); + double ivalFloor = vcl_floor(ival); + double left = ival - ivalFloor; + + if ( ivalFloor < m_OriginalProfileSize-1 ) + { + val = left*m_OriginalProfile[static_cast<unsigned int>(ivalFloor)] + (1-left)*m_OriginalProfile[static_cast<unsigned int>(ivalFloor)+1]; + } else - { - if ( A == itk::NumericTraits< TInput >::Zero || m_Radius==0) { - val = m_OriginalProfile[0]; + itkGenericExceptionMacro(<<"Out of Profile limits ("<<ivalFloor<<" -1 > 721)"); + } + } else + { + if ( A == itk::NumericTraits< TInput >::Zero || m_Radius==0) + { + val = m_OriginalProfile[0]; + } + else { if ( vcl_abs(A) == static_cast<TInput>(m_Radius) ) - { - val = m_OriginalProfile[m_OriginalProfileSize-1]; - } + { + val = m_OriginalProfile[m_OriginalProfileSize-1]; + } } - } - return val; } + return val; + } - private: +private: /** Useless, only to be compatible with the GenericInterpolateImage. */ unsigned int m_Radius; /** Length of the original profil. */ @@ -106,57 +121,63 @@ class ProlateFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT ProlateInterpolateImageFunction : -public GenericInterpolateImageFunction< TInputImage, - ITK_TYPENAME Function::ProlateFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public GenericInterpolateImageFunction< TInputImage, + ITK_TYPENAME Function::ProlateFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef ProlateInterpolateImageFunction Self; + typedef GenericInterpolateImageFunction<TInputImage, + Function::ProlateFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ProlateInterpolateImageFunction, GenericInterpolateImageFunction); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + typedef TInputInterpolator InputInterpolatorType; + typedef TOutputInterpolator OutputInterpolatorType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef Function::ProlateFunction<InputInterpolatorType, OutputInterpolatorType> FunctionType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + typedef typename std::vector<double> VectorType; + + unsigned int GetOriginalProfileSize() const { - public: - /** Standard class typedefs. */ - typedef ProlateInterpolateImageFunction Self; - typedef GenericInterpolateImageFunction<TInputImage, - Function::ProlateFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(ProlateInterpolateImageFunction, GenericInterpolateImageFunction); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - typedef TInputInterpolator InputInterpolatorType; - typedef TOutputInterpolator OutputInterpolatorType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef Function::ProlateFunction<InputInterpolatorType, OutputInterpolatorType> FunctionType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - typedef typename std::vector<double> VectorType; - - unsigned int GetOriginalProfileSize() const { return this->GetFunction().GetOriginalProfileSize; }; - VectorType GetOriginalProfile() const { return this->GetFunction().GetOriginalProfile();}; - - protected: - ProlateInterpolateImageFunction(); - ~ProlateInterpolateImageFunction(); - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - ProlateInterpolateImageFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + return this->GetFunction().GetOriginalProfileSize; }; + VectorType GetOriginalProfile() const + { + return this->GetFunction().GetOriginalProfile(); + }; + +protected: + ProlateInterpolateImageFunction(); + ~ProlateInterpolateImageFunction(); + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + ProlateInterpolateImageFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // end namespace otb diff --git a/Code/BasicFilters/otbProlateInterpolateImageFunction.txx b/Code/BasicFilters/otbProlateInterpolateImageFunction.txx index 05ae6c8d89ef5fe3584d7ee0ff3d0a48ed592ba8..19b0f0eca8aaf46611ebad35aa477af59dea5936 100644 --- a/Code/BasicFilters/otbProlateInterpolateImageFunction.txx +++ b/Code/BasicFilters/otbProlateInterpolateImageFunction.txx @@ -24,78 +24,79 @@ namespace otb { namespace Function { - template<class TInput, class TOutput> - const unsigned int - ProlateFunction<TInput, TOutput> - ::m_OriginalProfileSize = 721; - - - template<class TInput, class TOutput> - const double - ProlateFunction<TInput, TOutput> - ::m_OriginalProfile[721] = { - 0.00125, 0.00124999, 0.00124998, 0.00124997, 0.00124995, 0.00124992, 0.00124989, 0.00124985, 0.0012498, 0.00124975, 0.00124969, 0.00124962, - 0.00124955, 0.00124948, 0.00124939, 0.0012493, 0.00124921, 0.00124911, 0.001249, 0.00124888, 0.00124876, 0.00124864, 0.0012485, 0.00124837, - 0.00124822, 0.00124807, 0.00124791, 0.00124775, 0.00124758, 0.0012474, 0.00124722, 0.00124703, 0.00124684, 0.00124664, 0.00124643, 0.00124622, - 0.001246, 0.00124578, 0.00124555, 0.00124531, 0.00124507, 0.00124482, 0.00124456, 0.0012443, 0.00124403, 0.00124376, 0.00124348, 0.00124319, - 0.0012429, 0.0012426, 0.0012423, 0.00124199, 0.00124167, 0.00124135, 0.00124102, 0.00124069, 0.00124035, 0.00124, 0.00123965, 0.00123929, - 0.00123892, 0.00123855, 0.00123817, 0.00123779, 0.0012374, 0.001237, 0.0012366, 0.00123619, 0.00123578, 0.00123536, 0.00123494, 0.0012345, - 0.00123407, 0.00123362, 0.00123317, 0.00123272, 0.00123225, 0.00123179, 0.00123131, 0.00123083, 0.00123035, 0.00122985, 0.00122936, 0.00122885, - 0.00122834, 0.00122783, 0.0012273, 0.00122678, 0.00122624, 0.0012257, 0.00122516, 0.0012246, 0.00122405, 0.00122348, 0.00122291, 0.00122234, - 0.00122175, 0.00122117, 0.00122057, 0.00121997, 0.00121937, 0.00121876, 0.00121814, 0.00121752, 0.00121689, 0.00121625, 0.00121561, 0.00121497, - 0.00121431, 0.00121366, 0.00121299, 0.00121232, 0.00121165, 0.00121096, 0.00121028, 0.00120958, 0.00120888, 0.00120818, 0.00120747, 0.00120675, - 0.00120603, 0.0012053, 0.00120457, 0.00120383, 0.00120308, 0.00120233, 0.00120157, 0.00120081, 0.00120004, 0.00119927, 0.00119849, 0.0011977, - 0.00119691, 0.00119611, 0.00119531, 0.0011945, 0.00119368, 0.00119286, 0.00119204, 0.00119121, 0.00119037, 0.00118953, 0.00118868, 0.00118782, - 0.00118696, 0.0011861, 0.00118523, 0.00118435, 0.00118347, 0.00118258, 0.00118169, 0.00118079, 0.00117988, 0.00117897, 0.00117805, 0.00117713, - 0.00117621, 0.00117527, 0.00117433, 0.00117339, 0.00117244, 0.00117149, 0.00117053, 0.00116956, 0.00116859, 0.00116761, 0.00116663, 0.00116564, - 0.00116465, 0.00116365, 0.00116265, 0.00116164, 0.00116062, 0.0011596, 0.00115858, 0.00115754, 0.00115651, 0.00115547, 0.00115442, 0.00115337, - 0.00115231, 0.00115124, 0.00115018, 0.0011491, 0.00114802, 0.00114694, 0.00114585, 0.00114475, 0.00114365, 0.00114255, 0.00114143, 0.00114032, - 0.0011392, 0.00113807, 0.00113694, 0.0011358, 0.00113466, 0.00113351, 0.00113236, 0.0011312, 0.00113003, 0.00112887, 0.00112769, 0.00112651, - 0.00112533, 0.00112414, 0.00112295, 0.00112175, 0.00112054, 0.00111933, 0.00111812, 0.0011169, 0.00111567, 0.00111444, 0.00111321, 0.00111197, - 0.00111072, 0.00110947, 0.00110822, 0.00110696, 0.00110569, 0.00110442, 0.00110315, 0.00110187, 0.00110059, 0.0010993, 0.001098, 0.0010967, - 0.0010954, 0.00109409, 0.00109277, 0.00109146, 0.00109013, 0.0010888, 0.00108747, 0.00108613, 0.00108479, 0.00108344, 0.00108209, 0.00108073, - 0.00107937, 0.001078, 0.00107663, 0.00107526, 0.00107387, 0.00107249, 0.0010711, 0.0010697, 0.0010683, 0.0010669, 0.00106549, 0.00106408, - 0.00106266, 0.00106124, 0.00105981, 0.00105838, 0.00105694, 0.0010555, 0.00105405, 0.0010526, 0.00105115, 0.00104969, 0.00104823, 0.00104676, - 0.00104528, 0.00104381, 0.00104233, 0.00104084, 0.00103935, 0.00103785, 0.00103636, 0.00103485, 0.00103334, 0.00103183, 0.00103031, 0.00102879, - 0.00102727, 0.00102574, 0.0010242, 0.00102267, 0.00102112, 0.00101958, 0.00101803, 0.00101647, 0.00101491, 0.00101335, 0.00101178, 0.00101021, - 0.00100863, 0.00100705, 0.00100547, 0.00100388, 0.00100228, 0.00100069, 0.000999085, 0.00099748, 0.000995871, 0.000994258, 0.00099264, 0.000991019, - 0.000989394, 0.000987764, 0.000986131, 0.000984494, 0.000982852, 0.000981207, 0.000979558, 0.000977905, 0.000976248, 0.000974587, 0.000972922, 0.000971254, - 0.000969581, 0.000967905, 0.000966225, 0.000964541, 0.000962853, 0.000961162, 0.000959466, 0.000957767, 0.000956065, 0.000954358, 0.000952648, 0.000950934, - 0.000949217, 0.000947495, 0.00094577, 0.000944042, 0.00094231, 0.000940574, 0.000938834, 0.000937092, 0.000935345, 0.000933595, 0.000931841, 0.000930084, - 0.000928323, 0.000926559, 0.000924792, 0.000923021, 0.000921246, 0.000919468, 0.000917686, 0.000915902, 0.000914113, 0.000912322, 0.000910527, 0.000908728, - 0.000906927, 0.000905122, 0.000903314, 0.000901502, 0.000899687, 0.000897869, 0.000896048, 0.000894223, 0.000892395, 0.000890564, 0.00088873, 0.000886892, - 0.000885052, 0.000883208, 0.000881361, 0.000879511, 0.000877658, 0.000875802, 0.000873943, 0.000872081, 0.000870216, 0.000868347, 0.000866476, 0.000864602, - 0.000862724, 0.000860844, 0.000858961, 0.000857075, 0.000855186, 0.000853294, 0.000851399, 0.000849502, 0.000847601, 0.000845698, 0.000843791, 0.000841882, - 0.000839971, 0.000838056, 0.000836139, 0.000834219, 0.000832296, 0.000830371, 0.000828442, 0.000826511, 0.000824578, 0.000822642, 0.000820703, 0.000818761, - 0.000816817, 0.000814871, 0.000812922, 0.00081097, 0.000809016, 0.000807059, 0.000805099, 0.000803138, 0.000801173, 0.000799207, 0.000797237, 0.000795266, - 0.000793292, 0.000791315, 0.000789337, 0.000787355, 0.000785372, 0.000783386, 0.000781398, 0.000779407, 0.000777415, 0.00077542, 0.000773422, 0.000771423, - 0.000769421, 0.000767417, 0.000765411, 0.000763403, 0.000761393, 0.00075938, 0.000757365, 0.000755349, 0.00075333, 0.000751309, 0.000749286, 0.000747261, - 0.000745234, 0.000743205, 0.000741173, 0.00073914, 0.000737105, 0.000735069, 0.00073303, 0.000730989, 0.000728946, 0.000726902, 0.000724855, 0.000722807, - 0.000720757, 0.000718705, 0.000716652, 0.000714596, 0.000712539, 0.00071048, 0.000708419, 0.000706357, 0.000704293, 0.000702227, 0.00070016, 0.000698091, - 0.00069602, 0.000693948, 0.000691874, 0.000689798, 0.000687721, 0.000685643, 0.000683563, 0.000681481, 0.000679398, 0.000677313, 0.000675227, 0.00067314, - 0.000671051, 0.000668961, 0.000666869, 0.000664776, 0.000662681, 0.000660586, 0.000658489, 0.00065639, 0.00065429, 0.000652189, 0.000650087, 0.000647984, - 0.000645879, 0.000643773, 0.000641666, 0.000639558, 0.000637448, 0.000635337, 0.000633226, 0.000631113, 0.000628999, 0.000626884, 0.000624768, 0.000622651, - 0.000620533, 0.000618414, 0.000616293, 0.000614172, 0.00061205, 0.000609927, 0.000607803, 0.000605679, 0.000603553, 0.000601426, 0.000599299, 0.000597171, - 0.000595042, 0.000592912, 0.000590781, 0.000588649, 0.000586517, 0.000584384, 0.000582251, 0.000580116, 0.000577981, 0.000575845, 0.000573709, 0.000571572, - 0.000569434, 0.000567296, 0.000565157, 0.000563018, 0.000560878, 0.000558738, 0.000556597, 0.000554455, 0.000552313, 0.000550171, 0.000548028, 0.000545884, - 0.000543741, 0.000541596, 0.000539452, 0.000537307, 0.000535162, 0.000533016, 0.00053087, 0.000528724, 0.000526578, 0.000524431, 0.000522284, 0.000520137, - 0.000517989, 0.000515842, 0.000513694, 0.000511546, 0.000509398, 0.000507249, 0.000505101, 0.000502953, 0.000500804, 0.000498655, 0.000496507, 0.000494358, - 0.000492209, 0.000490061, 0.000487912, 0.000485763, 0.000483615, 0.000481466, 0.000479318, 0.00047717, 0.000475021, 0.000472873, 0.000470725, 0.000468578, - 0.00046643, 0.000464283, 0.000462136, 0.000459989, 0.000457842, 0.000455696, 0.00045355, 0.000451404, 0.000449259, 0.000447114, 0.000444969, 0.000442825, - 0.000440681, 0.000438537, 0.000436394, 0.000434251, 0.000432109, 0.000429967, 0.000427826, 0.000425685, 0.000423545, 0.000421405, 0.000419266, 0.000417127, - 0.000414989, 0.000412852, 0.000410715, 0.000408579, 0.000406443, 0.000404308, 0.000402174, 0.000400041, 0.000397908, 0.000395776, 0.000393645, 0.000391514, - 0.000389385, 0.000387256, 0.000385128, 0.000383, 0.000380874, 0.000378748, 0.000376624, 0.0003745, 0.000372377, 0.000370255, 0.000368134, 0.000366014, - 0.000363895, 0.000361777, 0.00035966, 0.000357544, 0.000355429, 0.000353315, 0.000351202, 0.000349091, 0.00034698, 0.000344871, 0.000342762, 0.000340655, - 0.000338549, 0.000336444, 0.00033434, 0.000332238, 0.000330137, 0.000328037, 0.000325938, 0.000323841, 0.000321745, 0.00031965, 0.000317556, 0.000315464, - 0.000313374, 0.000311284, 0.000309196, 0.00030711, 0.000305025, 0.000302941, 0.000300859, 0.000298778, 0.000296699, 0.000294621, 0.000292544, 0.00029047, - 0.000288397, 0.000286325, 0.000284255, 0.000282186, 0.00028012, 0.000278054, 0.000275991, 0.000273929, 0.000271869, 0.00026981, 0.000267753, 0.000265698, - 0.000263645, 0.000261593, 0.000259543, 0.000257495, 0.000255449, 0.000253404, 0.000251362, 0.000249321, 0.000247282, 0.000245245, 0.00024321, 0.000241176, - 0.000239145, 0.000237116, 0.000235088, 0.000233062, 0.000231039, 0.000229017, 0.000226998, 0.00022498, 0.000222965, 0.000220951, 0.00021894, 0.00021693, - 0.000214923, 0.000212918, 0.000210915, 0.000208914, 0.000206915, 0.000204919, 0.000202924, 0.000200932, 0.000198942, 0.000196955, 0.000194969, 0.000192986, - 0.000191005, 0.000189026, 0.00018705, 0.000185076, 0.000183104, 0.000181135, 0.000179167, 0.000177203, 0.00017524, 0.000173281, 0.000171323, 0.000169368, - 0.000167415, 0.000165465, 0.000163517, 0.000161572, 0.000159629, 0.000157689, 0.000155752, 0.000153816, 0.000151884, 0.000149954, 0.000148026, 0.000146101, - 0.000144179 - }; +template<class TInput, class TOutput> +const unsigned int +ProlateFunction<TInput, TOutput> +::m_OriginalProfileSize = 721; + + +template<class TInput, class TOutput> +const double +ProlateFunction<TInput, TOutput> +::m_OriginalProfile[721] = +{ + 0.00125, 0.00124999, 0.00124998, 0.00124997, 0.00124995, 0.00124992, 0.00124989, 0.00124985, 0.0012498, 0.00124975, 0.00124969, 0.00124962, + 0.00124955, 0.00124948, 0.00124939, 0.0012493, 0.00124921, 0.00124911, 0.001249, 0.00124888, 0.00124876, 0.00124864, 0.0012485, 0.00124837, + 0.00124822, 0.00124807, 0.00124791, 0.00124775, 0.00124758, 0.0012474, 0.00124722, 0.00124703, 0.00124684, 0.00124664, 0.00124643, 0.00124622, + 0.001246, 0.00124578, 0.00124555, 0.00124531, 0.00124507, 0.00124482, 0.00124456, 0.0012443, 0.00124403, 0.00124376, 0.00124348, 0.00124319, + 0.0012429, 0.0012426, 0.0012423, 0.00124199, 0.00124167, 0.00124135, 0.00124102, 0.00124069, 0.00124035, 0.00124, 0.00123965, 0.00123929, + 0.00123892, 0.00123855, 0.00123817, 0.00123779, 0.0012374, 0.001237, 0.0012366, 0.00123619, 0.00123578, 0.00123536, 0.00123494, 0.0012345, + 0.00123407, 0.00123362, 0.00123317, 0.00123272, 0.00123225, 0.00123179, 0.00123131, 0.00123083, 0.00123035, 0.00122985, 0.00122936, 0.00122885, + 0.00122834, 0.00122783, 0.0012273, 0.00122678, 0.00122624, 0.0012257, 0.00122516, 0.0012246, 0.00122405, 0.00122348, 0.00122291, 0.00122234, + 0.00122175, 0.00122117, 0.00122057, 0.00121997, 0.00121937, 0.00121876, 0.00121814, 0.00121752, 0.00121689, 0.00121625, 0.00121561, 0.00121497, + 0.00121431, 0.00121366, 0.00121299, 0.00121232, 0.00121165, 0.00121096, 0.00121028, 0.00120958, 0.00120888, 0.00120818, 0.00120747, 0.00120675, + 0.00120603, 0.0012053, 0.00120457, 0.00120383, 0.00120308, 0.00120233, 0.00120157, 0.00120081, 0.00120004, 0.00119927, 0.00119849, 0.0011977, + 0.00119691, 0.00119611, 0.00119531, 0.0011945, 0.00119368, 0.00119286, 0.00119204, 0.00119121, 0.00119037, 0.00118953, 0.00118868, 0.00118782, + 0.00118696, 0.0011861, 0.00118523, 0.00118435, 0.00118347, 0.00118258, 0.00118169, 0.00118079, 0.00117988, 0.00117897, 0.00117805, 0.00117713, + 0.00117621, 0.00117527, 0.00117433, 0.00117339, 0.00117244, 0.00117149, 0.00117053, 0.00116956, 0.00116859, 0.00116761, 0.00116663, 0.00116564, + 0.00116465, 0.00116365, 0.00116265, 0.00116164, 0.00116062, 0.0011596, 0.00115858, 0.00115754, 0.00115651, 0.00115547, 0.00115442, 0.00115337, + 0.00115231, 0.00115124, 0.00115018, 0.0011491, 0.00114802, 0.00114694, 0.00114585, 0.00114475, 0.00114365, 0.00114255, 0.00114143, 0.00114032, + 0.0011392, 0.00113807, 0.00113694, 0.0011358, 0.00113466, 0.00113351, 0.00113236, 0.0011312, 0.00113003, 0.00112887, 0.00112769, 0.00112651, + 0.00112533, 0.00112414, 0.00112295, 0.00112175, 0.00112054, 0.00111933, 0.00111812, 0.0011169, 0.00111567, 0.00111444, 0.00111321, 0.00111197, + 0.00111072, 0.00110947, 0.00110822, 0.00110696, 0.00110569, 0.00110442, 0.00110315, 0.00110187, 0.00110059, 0.0010993, 0.001098, 0.0010967, + 0.0010954, 0.00109409, 0.00109277, 0.00109146, 0.00109013, 0.0010888, 0.00108747, 0.00108613, 0.00108479, 0.00108344, 0.00108209, 0.00108073, + 0.00107937, 0.001078, 0.00107663, 0.00107526, 0.00107387, 0.00107249, 0.0010711, 0.0010697, 0.0010683, 0.0010669, 0.00106549, 0.00106408, + 0.00106266, 0.00106124, 0.00105981, 0.00105838, 0.00105694, 0.0010555, 0.00105405, 0.0010526, 0.00105115, 0.00104969, 0.00104823, 0.00104676, + 0.00104528, 0.00104381, 0.00104233, 0.00104084, 0.00103935, 0.00103785, 0.00103636, 0.00103485, 0.00103334, 0.00103183, 0.00103031, 0.00102879, + 0.00102727, 0.00102574, 0.0010242, 0.00102267, 0.00102112, 0.00101958, 0.00101803, 0.00101647, 0.00101491, 0.00101335, 0.00101178, 0.00101021, + 0.00100863, 0.00100705, 0.00100547, 0.00100388, 0.00100228, 0.00100069, 0.000999085, 0.00099748, 0.000995871, 0.000994258, 0.00099264, 0.000991019, + 0.000989394, 0.000987764, 0.000986131, 0.000984494, 0.000982852, 0.000981207, 0.000979558, 0.000977905, 0.000976248, 0.000974587, 0.000972922, 0.000971254, + 0.000969581, 0.000967905, 0.000966225, 0.000964541, 0.000962853, 0.000961162, 0.000959466, 0.000957767, 0.000956065, 0.000954358, 0.000952648, 0.000950934, + 0.000949217, 0.000947495, 0.00094577, 0.000944042, 0.00094231, 0.000940574, 0.000938834, 0.000937092, 0.000935345, 0.000933595, 0.000931841, 0.000930084, + 0.000928323, 0.000926559, 0.000924792, 0.000923021, 0.000921246, 0.000919468, 0.000917686, 0.000915902, 0.000914113, 0.000912322, 0.000910527, 0.000908728, + 0.000906927, 0.000905122, 0.000903314, 0.000901502, 0.000899687, 0.000897869, 0.000896048, 0.000894223, 0.000892395, 0.000890564, 0.00088873, 0.000886892, + 0.000885052, 0.000883208, 0.000881361, 0.000879511, 0.000877658, 0.000875802, 0.000873943, 0.000872081, 0.000870216, 0.000868347, 0.000866476, 0.000864602, + 0.000862724, 0.000860844, 0.000858961, 0.000857075, 0.000855186, 0.000853294, 0.000851399, 0.000849502, 0.000847601, 0.000845698, 0.000843791, 0.000841882, + 0.000839971, 0.000838056, 0.000836139, 0.000834219, 0.000832296, 0.000830371, 0.000828442, 0.000826511, 0.000824578, 0.000822642, 0.000820703, 0.000818761, + 0.000816817, 0.000814871, 0.000812922, 0.00081097, 0.000809016, 0.000807059, 0.000805099, 0.000803138, 0.000801173, 0.000799207, 0.000797237, 0.000795266, + 0.000793292, 0.000791315, 0.000789337, 0.000787355, 0.000785372, 0.000783386, 0.000781398, 0.000779407, 0.000777415, 0.00077542, 0.000773422, 0.000771423, + 0.000769421, 0.000767417, 0.000765411, 0.000763403, 0.000761393, 0.00075938, 0.000757365, 0.000755349, 0.00075333, 0.000751309, 0.000749286, 0.000747261, + 0.000745234, 0.000743205, 0.000741173, 0.00073914, 0.000737105, 0.000735069, 0.00073303, 0.000730989, 0.000728946, 0.000726902, 0.000724855, 0.000722807, + 0.000720757, 0.000718705, 0.000716652, 0.000714596, 0.000712539, 0.00071048, 0.000708419, 0.000706357, 0.000704293, 0.000702227, 0.00070016, 0.000698091, + 0.00069602, 0.000693948, 0.000691874, 0.000689798, 0.000687721, 0.000685643, 0.000683563, 0.000681481, 0.000679398, 0.000677313, 0.000675227, 0.00067314, + 0.000671051, 0.000668961, 0.000666869, 0.000664776, 0.000662681, 0.000660586, 0.000658489, 0.00065639, 0.00065429, 0.000652189, 0.000650087, 0.000647984, + 0.000645879, 0.000643773, 0.000641666, 0.000639558, 0.000637448, 0.000635337, 0.000633226, 0.000631113, 0.000628999, 0.000626884, 0.000624768, 0.000622651, + 0.000620533, 0.000618414, 0.000616293, 0.000614172, 0.00061205, 0.000609927, 0.000607803, 0.000605679, 0.000603553, 0.000601426, 0.000599299, 0.000597171, + 0.000595042, 0.000592912, 0.000590781, 0.000588649, 0.000586517, 0.000584384, 0.000582251, 0.000580116, 0.000577981, 0.000575845, 0.000573709, 0.000571572, + 0.000569434, 0.000567296, 0.000565157, 0.000563018, 0.000560878, 0.000558738, 0.000556597, 0.000554455, 0.000552313, 0.000550171, 0.000548028, 0.000545884, + 0.000543741, 0.000541596, 0.000539452, 0.000537307, 0.000535162, 0.000533016, 0.00053087, 0.000528724, 0.000526578, 0.000524431, 0.000522284, 0.000520137, + 0.000517989, 0.000515842, 0.000513694, 0.000511546, 0.000509398, 0.000507249, 0.000505101, 0.000502953, 0.000500804, 0.000498655, 0.000496507, 0.000494358, + 0.000492209, 0.000490061, 0.000487912, 0.000485763, 0.000483615, 0.000481466, 0.000479318, 0.00047717, 0.000475021, 0.000472873, 0.000470725, 0.000468578, + 0.00046643, 0.000464283, 0.000462136, 0.000459989, 0.000457842, 0.000455696, 0.00045355, 0.000451404, 0.000449259, 0.000447114, 0.000444969, 0.000442825, + 0.000440681, 0.000438537, 0.000436394, 0.000434251, 0.000432109, 0.000429967, 0.000427826, 0.000425685, 0.000423545, 0.000421405, 0.000419266, 0.000417127, + 0.000414989, 0.000412852, 0.000410715, 0.000408579, 0.000406443, 0.000404308, 0.000402174, 0.000400041, 0.000397908, 0.000395776, 0.000393645, 0.000391514, + 0.000389385, 0.000387256, 0.000385128, 0.000383, 0.000380874, 0.000378748, 0.000376624, 0.0003745, 0.000372377, 0.000370255, 0.000368134, 0.000366014, + 0.000363895, 0.000361777, 0.00035966, 0.000357544, 0.000355429, 0.000353315, 0.000351202, 0.000349091, 0.00034698, 0.000344871, 0.000342762, 0.000340655, + 0.000338549, 0.000336444, 0.00033434, 0.000332238, 0.000330137, 0.000328037, 0.000325938, 0.000323841, 0.000321745, 0.00031965, 0.000317556, 0.000315464, + 0.000313374, 0.000311284, 0.000309196, 0.00030711, 0.000305025, 0.000302941, 0.000300859, 0.000298778, 0.000296699, 0.000294621, 0.000292544, 0.00029047, + 0.000288397, 0.000286325, 0.000284255, 0.000282186, 0.00028012, 0.000278054, 0.000275991, 0.000273929, 0.000271869, 0.00026981, 0.000267753, 0.000265698, + 0.000263645, 0.000261593, 0.000259543, 0.000257495, 0.000255449, 0.000253404, 0.000251362, 0.000249321, 0.000247282, 0.000245245, 0.00024321, 0.000241176, + 0.000239145, 0.000237116, 0.000235088, 0.000233062, 0.000231039, 0.000229017, 0.000226998, 0.00022498, 0.000222965, 0.000220951, 0.00021894, 0.00021693, + 0.000214923, 0.000212918, 0.000210915, 0.000208914, 0.000206915, 0.000204919, 0.000202924, 0.000200932, 0.000198942, 0.000196955, 0.000194969, 0.000192986, + 0.000191005, 0.000189026, 0.00018705, 0.000185076, 0.000183104, 0.000181135, 0.000179167, 0.000177203, 0.00017524, 0.000173281, 0.000171323, 0.000169368, + 0.000167415, 0.000165465, 0.000163517, 0.000161572, 0.000159629, 0.000157689, 0.000155752, 0.000153816, 0.000151884, 0.000149954, 0.000148026, 0.000146101, + 0.000144179 +}; template<class TInput, class TOutput> double @@ -106,10 +107,10 @@ ProlateFunction<TInput, TOutput> resampledProfile.fill(0); for (unsigned int i = 0; i<m_Radius+1; i++) - { - unsigned int ival = static_cast<unsigned int>(static_cast<double>(m_OriginalProfileSize*i)/static_cast<double>(m_Radius+1)); - resampledProfile[i] = m_OriginalProfile[ival]; - } + { + unsigned int ival = static_cast<unsigned int>(static_cast<double>(m_OriginalProfileSize*i)/static_cast<double>(m_Radius+1)); + resampledProfile[i] = m_OriginalProfile[ival]; + } vnl_fft_1d<double> v1d(1024); v1d.fwd_transform(resampledProfile); @@ -119,21 +120,21 @@ ProlateFunction<TInput, TOutput> double energy = 0.; // First part of spectrum for (unsigned int j = 0; j<sampleNb+1; j++) - { - energy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); - } + { + energy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); + } // Last part of spectrum for (unsigned int j = 1023; j>1023-sampleNb; j--) - { - energy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); - } + { + energy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); + } double totalEnergy = energy; // Middle part for (unsigned int j = sampleNb+1; j<1023-sampleNb+1; j++) - { - totalEnergy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); - } + { + totalEnergy += std::abs(resampledProfile[j])*std::abs(resampledProfile[j]); + } std::cout<<"SampleNb: "<<sampleNb<<", energy: "<<energy<<", total energy: "<<totalEnergy<<std::endl; diff --git a/Code/BasicFilters/otbQuaternaryFunctorImageFilter.h b/Code/BasicFilters/otbQuaternaryFunctorImageFilter.h index 5fd8d7b6eba4370fe8c4b52944e4ced65f3ec4ad..b8c4276d99bdf4a57e254fb36d12f9228534d4fc 100644 --- a/Code/BasicFilters/otbQuaternaryFunctorImageFilter.h +++ b/Code/BasicFilters/otbQuaternaryFunctorImageFilter.h @@ -39,10 +39,10 @@ namespace otb * \ingroup IntensityImageFilters Multithreaded */ template <class TInputImage1, class TInputImage2, - class TInputImage3, class TInputImage4, - class TOutputImage, class TFunction > +class TInputImage3, class TInputImage4, +class TOutputImage, class TFunction > class ITK_EXPORT QuaternaryFunctorImageFilter : - public itk::InPlaceImageFilter<TInputImage1,TOutputImage> + public itk::InPlaceImageFilter<TInputImage1,TOutputImage> { public: /** Standard class typedefs. */ @@ -96,16 +96,19 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer). */ - FunctorType& GetFunctor(void) { return m_Functor; }; + FunctorType& GetFunctor(void) + { + return m_Functor; + }; /** Get the functor object. The functor is returned by reference. * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ const FunctorType& GetFunctor() const - { + { return m_Functor; - }; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -114,13 +117,13 @@ public: * (or the compiler's default implementation of operator==() being * appropriate). */ void SetFunctor(const FunctorType& functor) + { + if (! (functor == m_Functor) ) { - if (! (functor == m_Functor) ) - { - m_Functor = functor; - this->Modified(); - } + m_Functor = functor; + this->Modified(); } + } /** Image dimensions */ itkStaticConstMacro(Input1ImageDimension, unsigned int, diff --git a/Code/BasicFilters/otbQuaternaryFunctorImageFilter.txx b/Code/BasicFilters/otbQuaternaryFunctorImageFilter.txx index c46d534dc6851f1b0423da47da53e9742f4de2c6..09998363a653d54d55a3bae968527a10bf400c79 100644 --- a/Code/BasicFilters/otbQuaternaryFunctorImageFilter.txx +++ b/Code/BasicFilters/otbQuaternaryFunctorImageFilter.txx @@ -33,7 +33,7 @@ namespace otb * Constructor */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::QuaternaryFunctorImageFilter() { @@ -45,7 +45,7 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 * Connect one of the operands for pixel-wise addition */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::SetInput1( const TInputImage1 *image1 ) @@ -59,7 +59,7 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 * Connect one of the operands for pixel-wise addition */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::SetInput2( const TInputImage2 *image2 ) @@ -74,7 +74,7 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 * Connect one of the operands for pixel-wise addition */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::SetInput3( const TInputImage3 *image3 ) @@ -88,7 +88,7 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 * Connect one of the operands for pixel-wise addition */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::SetInput4( const TInputImage4 *image4 ) @@ -101,35 +101,35 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 * BeforeThreadedGenerateData function. Validate inputs */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::BeforeThreadedGenerateData() { Input1ImagePointer inputPtr1 - = dynamic_cast<const TInputImage1*>((itk::ProcessObject::GetInput(0))); + = dynamic_cast<const TInputImage1*>((itk::ProcessObject::GetInput(0))); Input2ImagePointer inputPtr2 - = dynamic_cast<const TInputImage2*>((itk::ProcessObject::GetInput(1))); + = dynamic_cast<const TInputImage2*>((itk::ProcessObject::GetInput(1))); Input3ImagePointer inputPtr3 - = dynamic_cast<const TInputImage3*>((itk::ProcessObject::GetInput(2))); + = dynamic_cast<const TInputImage3*>((itk::ProcessObject::GetInput(2))); Input4ImagePointer inputPtr4 - = dynamic_cast<const TInputImage4*>((itk::ProcessObject::GetInput(3))); + = dynamic_cast<const TInputImage4*>((itk::ProcessObject::GetInput(3))); if (inputPtr1.IsNull() || inputPtr2.IsNull() || inputPtr3.IsNull() ||inputPtr4.IsNull()) - { - itkExceptionMacro(<< "At least one input is missing." - << " Input1 is " << inputPtr1.GetPointer() << ", " - << " Input2 is " << inputPtr2.GetPointer() << ", " - << " Input3 is " << inputPtr3.GetPointer() << ", " - << " Input4 is " << inputPtr4.GetPointer()); - - } + { + itkExceptionMacro(<< "At least one input is missing." + << " Input1 is " << inputPtr1.GetPointer() << ", " + << " Input2 is " << inputPtr2.GetPointer() << ", " + << " Input3 is " << inputPtr3.GetPointer() << ", " + << " Input4 is " << inputPtr4.GetPointer()); + + } } /** * ThreadedGenerateData function. Performs the pixel-wise addition */ template < class TInputImage1, class TInputImage2,class TInputImage3, - class TInputImage4, class TOutputImage, class TFunction > +class TInputImage4, class TOutputImage, class TFunction > void QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4,TOutputImage,TFunction> ::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, @@ -139,13 +139,13 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 // ImageToImageFilter::GetInput(int) always returns a pointer to a // TInputImage1 so it cannot be used for the second or third input. Input1ImagePointer inputPtr1 - = dynamic_cast<const TInputImage1*>((itk::ProcessObject::GetInput(0))); + = dynamic_cast<const TInputImage1*>((itk::ProcessObject::GetInput(0))); Input2ImagePointer inputPtr2 - = dynamic_cast<const TInputImage2*>((itk::ProcessObject::GetInput(1))); + = dynamic_cast<const TInputImage2*>((itk::ProcessObject::GetInput(1))); Input3ImagePointer inputPtr3 - = dynamic_cast<const TInputImage3*>((itk::ProcessObject::GetInput(2))); + = dynamic_cast<const TInputImage3*>((itk::ProcessObject::GetInput(2))); Input4ImagePointer inputPtr4 - = dynamic_cast<const TInputImage4*>((itk::ProcessObject::GetInput(3))); + = dynamic_cast<const TInputImage4*>((itk::ProcessObject::GetInput(3))); OutputImagePointer outputPtr = this->GetOutput(0); itk::ImageRegionConstIterator<TInputImage1> inputIt1(inputPtr1, outputRegionForThread); @@ -162,8 +162,8 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 outputIt.GoToBegin(); - while( !inputIt1.IsAtEnd() ) - { + while ( !inputIt1.IsAtEnd() ) + { outputIt.Set( m_Functor(inputIt1.Get(), inputIt2.Get(), inputIt3.Get(), inputIt4.Get()) ); ++inputIt1; ++inputIt2; @@ -171,7 +171,7 @@ QuaternaryFunctorImageFilter<TInputImage1,TInputImage2,TInputImage3,TInputImage4 ++inputIt4; ++outputIt; progress.CompletedPixel(); // potential exception thrown here - } + } } } // end namespace otb diff --git a/Code/BasicFilters/otbRationalQuotientResampleImageFilter.h b/Code/BasicFilters/otbRationalQuotientResampleImageFilter.h index acc08fb26137abda104367e4f520ad83c32572a5..78001e75bb2bde3edba6a92f97f53f4c83757b84 100644 --- a/Code/BasicFilters/otbRationalQuotientResampleImageFilter.h +++ b/Code/BasicFilters/otbRationalQuotientResampleImageFilter.h @@ -24,129 +24,133 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class RationalQuotientResampleImageFilter - * \brief This class is a composite filter, allowing user to resample - * an input image by rational quotient factor, for example *1.5 - * - * Combining an expand filter, then a shrink filter, - * denominator is applied as expand factor, whereas - * numerator is applied as shrink factor. +/** \class RationalQuotientResampleImageFilter + * \brief This class is a composite filter, allowing user to resample + * an input image by rational quotient factor, for example *1.5 + * + * Combining an expand filter, then a shrink filter, + * denominator is applied as expand factor, whereas + * numerator is applied as shrink factor. + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT RationalQuotientResampleImageFilter + : public itk::ImageToImageFilter<TInputImage,TOutputImage> +{ +public: + /** Standard typedefs */ + typedef RationalQuotientResampleImageFilter Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Creation through object factory macro */ + itkNewMacro(Self); + + /** Type macro */ + itkTypeMacro(RationalQuotientResampleImageFilter, ImageToImageFilter); + + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension ); + + /** Display */ + void PrintSelf( std::ostream& os, itk::Indent indent ) const; + + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + + /** Set numerator factors + * \param numerator The factor for expand filter, same for each dimension + */ + virtual void SetNumeratorFactors(const unsigned int numerator); + + /** Set numerator factors + * \param numerators Tab of expand filter factors, along each dimension */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT RationalQuotientResampleImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> - { - public: - /** Standard typedefs */ - typedef RationalQuotientResampleImageFilter Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Creation through object factory macro */ - itkNewMacro(Self); - - /** Type macro */ - itkTypeMacro(RationalQuotientResampleImageFilter, ImageToImageFilter); - - itkStaticConstMacro(ImageDimension, unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension ); - - /** Display */ - void PrintSelf( std::ostream& os, itk::Indent indent ) const; - - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - - /** Set numerator factors - * \param numerator The factor for expand filter, same for each dimension - */ - virtual void SetNumeratorFactors(const unsigned int numerator); - - /** Set numerator factors - * \param numerators Tab of expand filter factors, along each dimension - */ - virtual void SetNumeratorFactors( const unsigned int* numerators); - - /** Set numerator factors - * \param i Indice of dimension - * \param numerator The factor for expand filter - */ - virtual void SetNumeratorFactors( const unsigned int i, - const unsigned int numerator); - - /** Get numerator factors - * \return tab of numerator factors - */ - virtual const unsigned int* GetNumeratorFactors() const - { return m_Numerators;} - - /** Set denominator factors - * \param denominator The factor for shrink filter, same along each dimension - */ - virtual void SetDenominatorFactors(const unsigned int denominator); - - /** Set denominator factors - * \param denominators Tab of shrink filter factors, along each dimension + virtual void SetNumeratorFactors( const unsigned int* numerators); + + /** Set numerator factors + * \param i Indice of dimension + * \param numerator The factor for expand filter + */ + virtual void SetNumeratorFactors( const unsigned int i, + const unsigned int numerator); + + /** Get numerator factors + * \return tab of numerator factors + */ + virtual const unsigned int* GetNumeratorFactors() const + { + return m_Numerators; + } + + /** Set denominator factors + * \param denominator The factor for shrink filter, same along each dimension + */ + virtual void SetDenominatorFactors(const unsigned int denominator); + + /** Set denominator factors + * \param denominators Tab of shrink filter factors, along each dimension */ - virtual void SetDenominatorFactors(const unsigned int* denominators); + virtual void SetDenominatorFactors(const unsigned int* denominators); - /** Set denominator factors - * \param i Indice of dimension - * \param denominator The factor for shrink filter - */ - virtual void SetDenominatorFactors(const unsigned int i, - const unsigned int denominator); + /** Set denominator factors + * \param i Indice of dimension + * \param denominator The factor for shrink filter + */ + virtual void SetDenominatorFactors(const unsigned int i, + const unsigned int denominator); - /** Get denominator factors - * \return tab of denominator factors + /** Get denominator factors + * \return tab of denominator factors */ - virtual const unsigned int* GetDenominatorFactors() const - { return m_Denominators;} + virtual const unsigned int* GetDenominatorFactors() const + { + return m_Denominators; + } - protected: +protected: - /** Internal filters typedefs */ - typedef itk::ShrinkImageFilter<InputImageType, OutputImageType> + /** Internal filters typedefs */ + typedef itk::ShrinkImageFilter<InputImageType, OutputImageType> ShrinkFilterType; - typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; + typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; - typedef itk::ExpandImageFilter<InputImageType, OutputImageType> + typedef itk::ExpandImageFilter<InputImageType, OutputImageType> ExpandFilterType; - typedef typename ExpandFilterType::Pointer ExpandFilterPointerType; + typedef typename ExpandFilterType::Pointer ExpandFilterPointerType; - /** Actually process the input */ - virtual void GenerateData(); + /** Actually process the input */ + virtual void GenerateData(); - /** Constructor */ - RationalQuotientResampleImageFilter(); + /** Constructor */ + RationalQuotientResampleImageFilter(); - /** Expand filter */ - ExpandFilterPointerType m_ExpandFilter; + /** Expand filter */ + ExpandFilterPointerType m_ExpandFilter; - /** Shrink filter */ - ShrinkFilterPointerType m_ShrinkFilter; + /** Shrink filter */ + ShrinkFilterPointerType m_ShrinkFilter; - /** Destructor */ - virtual ~RationalQuotientResampleImageFilter() {} + /** Destructor */ + virtual ~RationalQuotientResampleImageFilter() {} - /** Numerator factors*/ - unsigned int m_Numerators[ImageDimension]; + /** Numerator factors*/ + unsigned int m_Numerators[ImageDimension]; - /** Denominator factors*/ - unsigned int m_Denominators[ImageDimension]; + /** Denominator factors*/ + unsigned int m_Denominators[ImageDimension]; - private: +private: - RationalQuotientResampleImageFilter(Self&); // intentionally not implemented - void operator=(const Self&); // intentionally not implemented + RationalQuotientResampleImageFilter(Self&); // intentionally not implemented + void operator=(const Self&); // intentionally not implemented - }; +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbRationalQuotientResampleImageFilter.txx" diff --git a/Code/BasicFilters/otbRationalQuotientResampleImageFilter.txx b/Code/BasicFilters/otbRationalQuotientResampleImageFilter.txx index f769683eedff9ea1e9fc68f3c9423a642405b0d3..42ad125ad9953d23c4f45ef3ae677995585f6a07 100644 --- a/Code/BasicFilters/otbRationalQuotientResampleImageFilter.txx +++ b/Code/BasicFilters/otbRationalQuotientResampleImageFilter.txx @@ -23,168 +23,168 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage> - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>::RationalQuotientResampleImageFilter() +/** + * Constructor + */ +template <class TInputImage, class TOutputImage> +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>::RationalQuotientResampleImageFilter() +{ + // Default rational quotient = 1:1 + unsigned int dimension = 0; + for (dimension=0; dimension != ImageDimension; dimension++) { - // Default rational quotient = 1:1 - unsigned int dimension = 0; - for (dimension=0; dimension != ImageDimension; dimension++) - { - m_Numerators[dimension]=1; - m_Denominators[dimension]=1; - } + m_Numerators[dimension]=1; + m_Denominators[dimension]=1; + } - // Internal filter - m_ExpandFilter = ExpandFilterType::New(); - m_ShrinkFilter = ShrinkFilterType::New(); + // Internal filter + m_ExpandFilter = ExpandFilterType::New(); + m_ShrinkFilter = ShrinkFilterType::New(); - m_ShrinkFilter->SetInput(m_ExpandFilter->GetOutput()); + m_ShrinkFilter->SetInput(m_ExpandFilter->GetOutput()); - } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage,TOutputImage> - ::GenerateData() - { - m_ExpandFilter->SetInput(this->GetInput()); +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage,TOutputImage> +::GenerateData() +{ + m_ExpandFilter->SetInput(this->GetInput()); - // Set expand factors as the numerator - m_ExpandFilter->SetExpandFactors(m_Numerators); + // Set expand factors as the numerator + m_ExpandFilter->SetExpandFactors(m_Numerators); - // Set shrink factors as the denominator - m_ShrinkFilter->SetShrinkFactors(m_Denominators); + // Set shrink factors as the denominator + m_ShrinkFilter->SetShrinkFactors(m_Denominators); - m_ShrinkFilter->GraftOutput(this->GetOutput()); + m_ShrinkFilter->GraftOutput(this->GetOutput()); - m_ShrinkFilter->Update(); - this->GraftOutput(m_ShrinkFilter->GetOutput()); - } + m_ShrinkFilter->Update(); + this->GraftOutput(m_ShrinkFilter->GetOutput()); +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - PrintSelf( std::ostream& os, itk::Indent indent ) const +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +PrintSelf( std::ostream& os, itk::Indent indent ) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Rational quotient factor (numerator:denominator) : "; + unsigned int dimension = 0; + for (dimension=0; dimension != ImageDimension; dimension++) { - Superclass::PrintSelf(os, indent); - os << indent << "Rational quotient factor (numerator:denominator) : "; - unsigned int dimension = 0; - for(dimension=0; dimension != ImageDimension; dimension++) - { - os << m_Numerators[dimension] << ":" << m_Denominators[dimension] << " "; - } - os << std::endl; + os << m_Numerators[dimension] << ":" << m_Denominators[dimension] << " "; } + os << std::endl; +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetDenominatorFactors( const unsigned int denominator) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetDenominatorFactors( const unsigned int denominator) +{ + unsigned int dimension = 0; + for (dimension=0; dimension!=ImageDimension; dimension++) { - unsigned int dimension = 0; - for (dimension=0; dimension!=ImageDimension; dimension++) - { - if (denominator < 1) + if (denominator < 1) { m_Denominators[dimension]=1; } - else + else { m_Denominators[dimension] = denominator; } - } } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetDenominatorFactors( const unsigned int* denominators) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetDenominatorFactors( const unsigned int* denominators) +{ + unsigned int dimension = 0; + for (dimension=0; dimension!=ImageDimension; dimension++) { - unsigned int dimension = 0; - for (dimension=0; dimension!=ImageDimension; dimension++) - { - if (denominators[dimension] < 1) + if (denominators[dimension] < 1) { m_Denominators[dimension] = 1; } - else + else { m_Denominators[dimension] = denominators[dimension]; } - } } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetDenominatorFactors( const unsigned int i, const unsigned int denominator) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetDenominatorFactors( const unsigned int i, const unsigned int denominator) +{ + if (denominator < 1) { - if (denominator < 1) - { - m_Denominators[i]=1; - } - else - { - m_Denominators[i] = denominator; - } + m_Denominators[i]=1; } + else + { + m_Denominators[i] = denominator; + } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetNumeratorFactors( const unsigned int numerator) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetNumeratorFactors( const unsigned int numerator) +{ + unsigned int dimension = 0; + for (dimension=0; dimension!=ImageDimension; dimension++) { - unsigned int dimension = 0; - for (dimension=0; dimension!=ImageDimension; dimension++) - { - if (numerator < 1) + if (numerator < 1) { m_Numerators[dimension]=1; } - else + else { m_Numerators[dimension] = numerator; } - } } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetNumeratorFactors( const unsigned int* numerators) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetNumeratorFactors( const unsigned int* numerators) +{ + unsigned int dimension = 0; + for (dimension=0; dimension!=ImageDimension; dimension++) { - unsigned int dimension = 0; - for (dimension=0; dimension!=ImageDimension; dimension++) - { - if (numerators[dimension] < 1) + if (numerators[dimension] < 1) { m_Numerators[dimension] = 1; } - else + else { m_Numerators[dimension] = numerators[dimension]; } - } } +} - template <class TInputImage, class TOutputImage> - void - RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: - SetNumeratorFactors( const unsigned int i, const unsigned int numerator) +template <class TInputImage, class TOutputImage> +void +RationalQuotientResampleImageFilter<TInputImage, TOutputImage>:: +SetNumeratorFactors( const unsigned int i, const unsigned int numerator) +{ + if (numerator < 1) { - if (numerator < 1) - { - m_Numerators[i]=1; - } - else - { - m_Numerators[i] = numerator; - } + m_Numerators[i]=1; + } + else + { + m_Numerators[i] = numerator; } +} } // End namespace otb diff --git a/Code/BasicFilters/otbScalarImageTextureFunctor.h b/Code/BasicFilters/otbScalarImageTextureFunctor.h index 4237e64fd4bb078b9ecf89e0b325bcd214ecdce1..3de9a3d679d7301a71dda7d402474b52e9151679 100644 --- a/Code/BasicFilters/otbScalarImageTextureFunctor.h +++ b/Code/BasicFilters/otbScalarImageTextureFunctor.h @@ -34,53 +34,59 @@ namespace Functor template <class TNeighIter, class TInputImage, class TOutput> class ScalarImageTextureFunctor { - public: +public: ScalarImageTextureFunctor() - { - m_FeatureIndex=0; - }; + { + m_FeatureIndex=0; + }; ~ScalarImageTextureFunctor() { }; - void SetFeatureIndex(int i){ m_FeatureIndex = i;}; - int GetFeatureIndex(){ return m_FeatureIndex; }; + void SetFeatureIndex(int i) + { + m_FeatureIndex = i; + }; + int GetFeatureIndex() + { + return m_FeatureIndex; + }; typedef TInputImage InputImageType; typedef typename itk::Statistics::ScalarImageTextureCalculator< InputImageType> TextureCalcType; inline TOutput operator()(const TNeighIter & it) - { - unsigned int neighborhoodSize = it.Size(); + { + unsigned int neighborhoodSize = it.Size(); - typename TextureCalcType::Pointer textureFilter = TextureCalcType::New(); - typename InputImageType::Pointer image = InputImageType::New(); + typename TextureCalcType::Pointer textureFilter = TextureCalcType::New(); + typename InputImageType::Pointer image = InputImageType::New(); - typename InputImageType::IndexType index; - index.Fill(0); - typename InputImageType::RegionType region; + typename InputImageType::IndexType index; + index.Fill(0); + typename InputImageType::RegionType region; - region = it.GetBoundingBoxAsImageRegion(); - region.SetIndex(index); + region = it.GetBoundingBoxAsImageRegion(); + region.SetIndex(index); - image->SetRegions( region ); - image->Allocate(); + image->SetRegions( region ); + image->Allocate(); - typedef itk::ImageRegionIterator< InputImageType > IteratorType; - IteratorType inputIt( image, image->GetLargestPossibleRegion() ); - inputIt.GoToBegin(); - for (unsigned int i = 0; i < neighborhoodSize; ++i) - { - inputIt.Set(it.GetPixel(i)); - ++inputIt; - } + typedef itk::ImageRegionIterator< InputImageType > IteratorType; + IteratorType inputIt( image, image->GetLargestPossibleRegion() ); + inputIt.GoToBegin(); + for (unsigned int i = 0; i < neighborhoodSize; ++i) + { + inputIt.Set(it.GetPixel(i)); + ++inputIt; + } - textureFilter->FastCalculationsOn(); - textureFilter->SetInput(image); - textureFilter->Compute(); + textureFilter->FastCalculationsOn(); + textureFilter->SetInput(image); + textureFilter->Compute(); - return (static_cast<TOutput>(textureFilter->GetFeatureMeans()->at(m_FeatureIndex))); + return (static_cast<TOutput>(textureFilter->GetFeatureMeans()->at(m_FeatureIndex))); - } - private: + } +private: int m_FeatureIndex; }; diff --git a/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.h b/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.h index c37f0586d2abf0dfbbc22aa04ecce4f14326a885..0d912bf92a42891460a3c4fdff130cea1b1c94eb 100644 --- a/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.h +++ b/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.h @@ -22,9 +22,11 @@ #include "itkRGBPixel.h" #include "itkScalarToRGBPixelFunctor.h" -namespace otb { +namespace otb +{ -namespace Functor { +namespace Functor +{ /** * \class ScalarToRainbowRGBPixelFunctor @@ -39,7 +41,7 @@ namespace Functor { */ template< class TScalar > class ITK_EXPORT ScalarToRainbowRGBPixelFunctor : - public itk::Functor::ScalarToRGBPixelFunctor<TScalar> + public itk::Functor::ScalarToRGBPixelFunctor<TScalar> { public: ScalarToRainbowRGBPixelFunctor(); @@ -63,7 +65,7 @@ public: this->m_Minimum = min; } - protected: +protected: RGBPixelType HSVToRGB(double h, double s, double v) const; private: diff --git a/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.txx b/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.txx index c59f76079934dbd00a9f81f529d407577c74871b..79db11cff890e839f48df649426c0eee3f2c52bf 100644 --- a/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.txx +++ b/Code/BasicFilters/otbScalarToRainbowRGBPixelFunctor.txx @@ -21,9 +21,11 @@ #include "otbScalarToRainbowRGBPixelFunctor.h" -namespace otb { +namespace otb +{ -namespace Functor { +namespace Functor +{ template <class TScalar> ScalarToRainbowRGBPixelFunctor<TScalar> @@ -69,7 +71,7 @@ ScalarToRainbowRGBPixelFunctor<TScalar> template <class TScalar> typename ScalarToRainbowRGBPixelFunctor<TScalar>::RGBPixelType ScalarToRainbowRGBPixelFunctor<TScalar> - ::HSVToRGB(double h, double s, double v) const +::HSVToRGB(double h, double s, double v) const { const double onethird = 1.0 / 3.0; const double onesixth = 1.0 / 6.0; @@ -79,41 +81,41 @@ ScalarToRainbowRGBPixelFunctor<TScalar> // compute RGB from HSV if (h > onesixth && h <= onethird) // green/red - { + { g = 1.0; r = (onethird - h) / onesixth; b = 0.0; - } + } else if (h > onethird && h <= 0.5) // green/blue - { + { g = 1.0; b = (h - onethird) / onesixth; r = 0.0; - } + } else if (h > 0.5 && h <= twothird) // blue/green - { + { b = 1.0; g = (twothird - h) / onesixth; r = 0.0; - } + } else if (h > twothird && h <= fivesixth) // blue/red - { + { b = 1.0; r = (h - twothird) / onesixth; g = 0.0; - } + } else if (h > fivesixth && h <= 1.0) // red/blue - { + { r = 1.0; b = (1.0 - h) / onesixth; g = 0.0; - } + } else // red/green - { + { r = 1.0; g = h / onesixth; b = 0.0; - } + } // add Saturation to the equation. r = (s * r + (1.0 - s)); diff --git a/Code/BasicFilters/otbScalarVectorImageTextureFunctor.h b/Code/BasicFilters/otbScalarVectorImageTextureFunctor.h index 5b6f944f5867635aa9b36d523813e2d6022ed157..d79ab0d8bcce10c9a9b80148e55240fc75c6fea7 100644 --- a/Code/BasicFilters/otbScalarVectorImageTextureFunctor.h +++ b/Code/BasicFilters/otbScalarVectorImageTextureFunctor.h @@ -36,63 +36,69 @@ namespace Functor template <class TNeighIter, class TInputImage, class TOutput> class ScalarVectorImageTextureFunctor { - public: +public: ScalarVectorImageTextureFunctor() - { - m_FeatureIndex.clear(); - }; + { + m_FeatureIndex.clear(); + }; ~ScalarVectorImageTextureFunctor() { }; typedef std::vector<int> IndexSelectFeaturesType; typedef TInputImage InputImageType; typedef typename itk::Statistics::ScalarImageTextureCalculator< InputImageType> TextureCalcType; - void SetFeatureIndex(const IndexSelectFeaturesType & listIndex){ m_FeatureIndex = listIndex;}; - const IndexSelectFeaturesType & GetFeatureIndex(){ return m_FeatureIndex; }; + void SetFeatureIndex(const IndexSelectFeaturesType & listIndex) + { + m_FeatureIndex = listIndex; + }; + const IndexSelectFeaturesType & GetFeatureIndex() + { + return m_FeatureIndex; + }; inline TOutput operator()(const TNeighIter & it) - { - unsigned int neighborhoodSize = it.Size(); + { + unsigned int neighborhoodSize = it.Size(); - typename TextureCalcType::Pointer textureFilter = TextureCalcType::New(); - typename InputImageType::Pointer image = InputImageType::New(); + typename TextureCalcType::Pointer textureFilter = TextureCalcType::New(); + typename InputImageType::Pointer image = InputImageType::New(); - typename InputImageType::IndexType index; - index.Fill(0); - typename InputImageType::RegionType region; + typename InputImageType::IndexType index; + index.Fill(0); + typename InputImageType::RegionType region; - region = it.GetBoundingBoxAsImageRegion(); - region.SetIndex(index); + region = it.GetBoundingBoxAsImageRegion(); + region.SetIndex(index); - image->SetRegions( region ); - image->Allocate(); + image->SetRegions( region ); + image->Allocate(); - typedef itk::ImageRegionIterator< InputImageType > IteratorrrType; - IteratorrrType inputIt( image, image->GetLargestPossibleRegion() ); - inputIt.GoToBegin(); - for (unsigned int i = 0; i < neighborhoodSize; ++i) - { - inputIt.Set(it.GetPixel(i)); - ++inputIt; - } + typedef itk::ImageRegionIterator< InputImageType > IteratorrrType; + IteratorrrType inputIt( image, image->GetLargestPossibleRegion() ); + inputIt.GoToBegin(); + for (unsigned int i = 0; i < neighborhoodSize; ++i) + { + inputIt.Set(it.GetPixel(i)); + ++inputIt; + } - textureFilter->FastCalculationsOn(); - textureFilter->SetInput(image); - textureFilter->Compute(); + textureFilter->FastCalculationsOn(); + textureFilter->SetInput(image); + textureFilter->Compute(); - TOutput resultvalue; - resultvalue.SetSize(m_FeatureIndex.size()); - resultvalue.AllocateElements(m_FeatureIndex.size()); + TOutput resultvalue; + resultvalue.SetSize(m_FeatureIndex.size()); + resultvalue.AllocateElements(m_FeatureIndex.size()); - for(unsigned int cpt=0; cpt < m_FeatureIndex.size(); cpt++) - { - resultvalue[cpt] = textureFilter->GetFeatureMeans()->at(m_FeatureIndex[cpt]); - } + for (unsigned int cpt=0; cpt < m_FeatureIndex.size(); cpt++) + { + resultvalue[cpt] = textureFilter->GetFeatureMeans()->at(m_FeatureIndex[cpt]); + } - return (static_cast<TOutput>(resultvalue)); + return (static_cast<TOutput>(resultvalue)); - } - private: + } +private: IndexSelectFeaturesType m_FeatureIndex; }; diff --git a/Code/BasicFilters/otbSimplifyPathFunctor.h b/Code/BasicFilters/otbSimplifyPathFunctor.h index b16824a0ffbbbd866e786f444cfe9712744b3108..ccc383e4d10150b1781d473aea084add796e3e1b 100644 --- a/Code/BasicFilters/otbSimplifyPathFunctor.h +++ b/Code/BasicFilters/otbSimplifyPathFunctor.h @@ -23,112 +23,112 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SimplifyPathFunctor - * \brief This filter performs a simplification of the input path. - * - * It reduces the number of vertices in each path, according to a tolerance criterion. It aims at - * removing aligned vertices while keeping sharp angular points. - * - * In order to ensure the unicity of its output, each path is considered first from begin to end, then - * from begin to the first vertex before the end. At each step, the consistency of the path is checked : - * the equation of the line passing by the first and last vertices is computed. Then, for each - * vertices between them, the euclidean distance to this line is computed. If for one vertex, this distance - * is upper than the tolerance threshold, the path is considered to be inconsistent and no vertices can be removed. - * - * If the path is considered consistent (which will occure at least with a 2 vertices path), - * only the beginning and ending - * vertices are kept and a new search iteration begin at its end. - * - * This filter is part of the road extraction framework. - * - * \sa UnaryFunctorObjectListFilter - * - * \ingroup Functor - */ - template <class TInput, class TOutput> - class SimplifyPathFunctor - { - public: +/** \class SimplifyPathFunctor +* \brief This filter performs a simplification of the input path. +* +* It reduces the number of vertices in each path, according to a tolerance criterion. It aims at +* removing aligned vertices while keeping sharp angular points. +* +* In order to ensure the unicity of its output, each path is considered first from begin to end, then +* from begin to the first vertex before the end. At each step, the consistency of the path is checked : +* the equation of the line passing by the first and last vertices is computed. Then, for each +* vertices between them, the euclidean distance to this line is computed. If for one vertex, this distance +* is upper than the tolerance threshold, the path is considered to be inconsistent and no vertices can be removed. +* +* If the path is considered consistent (which will occure at least with a 2 vertices path), +* only the beginning and ending +* vertices are kept and a new search iteration begin at its end. +* +* This filter is part of the road extraction framework. +* +* \sa UnaryFunctorObjectListFilter +* + * \ingroup Functor + */ +template <class TInput, class TOutput> +class SimplifyPathFunctor +{ +public: - typedef typename TInput::ObjectType::VertexListType::ConstIterator VertexListConstIteratorType; - typedef typename TInput::ObjectType::VertexListType::ConstPointer VertexListConstPointerType; - typedef TOutput OutputPathPointerType; - typedef typename OutputPathPointerType::ObjectType OutputPathType; + typedef typename TInput::ObjectType::VertexListType::ConstIterator VertexListConstIteratorType; + typedef typename TInput::ObjectType::VertexListType::ConstPointer VertexListConstPointerType; + typedef TOutput OutputPathPointerType; + typedef typename OutputPathPointerType::ObjectType OutputPathType; - void SetTolerance(double Tolerance ) - { - m_Tolerance = Tolerance; - } - double GetTolerance(void)const - { - return ( m_Tolerance ); - } + void SetTolerance(double Tolerance ) + { + m_Tolerance = Tolerance; + } + double GetTolerance(void)const + { + return ( m_Tolerance ); + } - SimplifyPathFunctor() - { - m_Tolerance = 1.0; - }; - ~SimplifyPathFunctor() {}; + SimplifyPathFunctor() + { + m_Tolerance = 1.0; + }; + ~SimplifyPathFunctor() {}; - inline OutputPathPointerType operator()(const TInput & input) - { + inline OutputPathPointerType operator()(const TInput & input) + { - OutputPathPointerType newPath = OutputPathType::New(); - newPath->Initialize(); - // Getting the verices list of the current input paths - VertexListConstPointerType vertexList = input->GetVertexList(); - VertexListConstIteratorType beginIt = vertexList->Begin(); - VertexListConstIteratorType beforeTheEndIt = --(vertexList->End()); + OutputPathPointerType newPath = OutputPathType::New(); + newPath->Initialize(); + // Getting the verices list of the current input paths + VertexListConstPointerType vertexList = input->GetVertexList(); + VertexListConstIteratorType beginIt = vertexList->Begin(); + VertexListConstIteratorType beforeTheEndIt = --(vertexList->End()); - // Add the first vertex - newPath->AddVertex(beginIt.Value()); + // Add the first vertex + newPath->AddVertex(beginIt.Value()); - while ( beginIt != beforeTheEndIt) - { - VertexListConstIteratorType endIt = beforeTheEndIt; + while ( beginIt != beforeTheEndIt) + { + VertexListConstIteratorType endIt = beforeTheEndIt; // while the segment is not consistent, decrement endIt - while (!this->TestPathConsistency(vertexList,beginIt, endIt)) - { - --endIt; - } + while (!this->TestPathConsistency(vertexList,beginIt, endIt)) + { + --endIt; + } // Add the final vertex - newPath->AddVertex(endIt.Value()); - beginIt=endIt; - } - return newPath; + newPath->AddVertex(endIt.Value()); + beginIt=endIt; + } + return newPath; - } + } - private: - double m_Tolerance; +private: + double m_Tolerance; - bool TestPathConsistency(VertexListConstPointerType vertexList, - VertexListConstIteratorType begin, - VertexListConstIteratorType end) - { - VertexListConstIteratorType segmentIt = begin; - ++segmentIt; + bool TestPathConsistency(VertexListConstPointerType vertexList, + VertexListConstIteratorType begin, + VertexListConstIteratorType end) + { + VertexListConstIteratorType segmentIt = begin; + ++segmentIt; //Compute the distance of a point to a segment based on the cross product - while (segmentIt != end) - { - double crossProduct = (end.Value()[0]-begin.Value()[0])*(segmentIt.Value()[1]-begin.Value()[1]) - - (end.Value()[1]-begin.Value()[1])*(segmentIt.Value()[0]-begin.Value()[0]); - double lenghtSeg = (end.Value()[0]-begin.Value()[0])*(end.Value()[0]-begin.Value()[0]) - +(end.Value()[1]-begin.Value()[1])*(end.Value()[1]-begin.Value()[1]); - if (lenghtSeg == 0) return false; - double distsq = crossProduct*crossProduct/lenghtSeg; - if (distsq > static_cast<double>(m_Tolerance) ) - { - return false; - } - ++segmentIt; - } - return true; + while (segmentIt != end) + { + double crossProduct = (end.Value()[0]-begin.Value()[0])*(segmentIt.Value()[1]-begin.Value()[1]) + - (end.Value()[1]-begin.Value()[1])*(segmentIt.Value()[0]-begin.Value()[0]); + double lenghtSeg = (end.Value()[0]-begin.Value()[0])*(end.Value()[0]-begin.Value()[0]) + +(end.Value()[1]-begin.Value()[1])*(end.Value()[1]-begin.Value()[1]); + if (lenghtSeg == 0) return false; + double distsq = crossProduct*crossProduct/lenghtSeg; + if (distsq > static_cast<double>(m_Tolerance) ) + { + return false; } + ++segmentIt; + } + return true; + } - }; +}; } diff --git a/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.h b/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.h index 2522bca9339e76dfe879c327b5a33cbf202f4062..cc11746ac7ef5d26b0be9cce9ebd1e940e47f1fc 100644 --- a/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.h +++ b/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.h @@ -139,7 +139,7 @@ protected: SpatialObjectToImageDrawingFilter(); ~SpatialObjectToImageDrawingFilter(); - virtual void GenerateOutputInformation(){}; // do nothing + virtual void GenerateOutputInformation() {}; // do nothing virtual void GenerateData(); diff --git a/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.txx b/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.txx index 0691ee1a91c25373ec18a85ae330ce83dcddf515..2778b3d4880c35a4fe8624553722028e5adf6741 100644 --- a/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.txx +++ b/Code/BasicFilters/otbSpatialObjectToImageDrawingFilter.txx @@ -36,10 +36,10 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> m_Size.Fill(0); for (unsigned int i = 0; i < OutputImageDimension; i++) - { + { m_Spacing[i] = 1.0; m_Origin[i] = 0.; - } + } m_InsideValue = 0; m_OutsideValue = 0; @@ -63,7 +63,7 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(0, - const_cast< InputSpatialObjectType * >( input ) ); + const_cast< InputSpatialObjectType * >( input ) ); } @@ -75,7 +75,7 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(index, - const_cast< TInputSpatialObject *>( object ) ); + const_cast< TInputSpatialObject *>( object ) ); } @@ -87,12 +87,12 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> ::GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<const TInputSpatialObject * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** Get the input Spatial Object */ @@ -102,7 +102,7 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> ::GetInput(unsigned int idx) { return static_cast< const TInputSpatialObject * > - (this->itk::ProcessObject::GetInput(idx)); + (this->itk::ProcessObject::GetInput(idx)); } @@ -114,20 +114,20 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<TOutputImage::ImageDimension; i++) - { + { if ( (double)spacing[i] != m_Spacing[i] ) - { + { break; - } } + } if ( i < TOutputImage::ImageDimension ) - { + { for (i=0; i<TOutputImage::ImageDimension; i++) - { + { m_Spacing[i] = spacing[i]; - } - this->Modified(); } + this->Modified(); + } } //---------------------------------------------------------------------------- @@ -138,19 +138,19 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<OutputImageDimension; i++) - { + { if ( spacing[i] != m_Spacing[i] ) - { + { break; - } } + } if ( i < OutputImageDimension ) - { + { for (i=0; i<OutputImageDimension; i++) - { + { m_Spacing[i] = spacing[i]; - } } + } } template <class TInputSpatialObject, class TOutputImage> @@ -160,19 +160,19 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<OutputImageDimension; i++) - { + { if ( (double)spacing[i] != m_Spacing[i] ) - { + { break; - } } + } if ( i < OutputImageDimension ) - { + { for (i=0; i<OutputImageDimension; i++) - { + { m_Spacing[i] = spacing[i]; - } } + } } template <class TInputSpatialObject, class TOutputImage> @@ -192,20 +192,20 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<TOutputImage::ImageDimension; i++) - { + { if ( (double)origin[i] != m_Origin[i] ) - { + { break; - } } + } if ( i < TOutputImage::ImageDimension ) - { + { for (i=0; i<TOutputImage::ImageDimension; i++) - { + { m_Origin[i] = origin[i]; - } - this->Modified(); } + this->Modified(); + } } //---------------------------------------------------------------------------- @@ -216,20 +216,20 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<OutputImageDimension; i++) - { + { if ( origin[i] != m_Origin[i] ) - { + { break; - } } + } if ( i < OutputImageDimension ) - { + { for (i=0; i<OutputImageDimension; i++) - { + { m_Origin[i] = origin[i]; - } - this->Modified(); } + this->Modified(); + } } template <class TInputSpatialObject, class TOutputImage> @@ -239,20 +239,20 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> { unsigned int i; for (i=0; i<OutputImageDimension; i++) - { + { if ( (double)origin[i] != m_Origin[i] ) - { + { break; - } } + } if ( i < OutputImageDimension ) - { + { for (i=0; i<OutputImageDimension; i++) - { + { m_Origin[i] = origin[i]; - } - this->Modified(); } + this->Modified(); + } } template <class TInputSpatialObject, class TOutputImage> @@ -279,59 +279,59 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> OutputImagePointer OutputImage = this->GetOutput(); // Generate the image - SizeType size; - double origine[ObjectDimension]; - InputObject->ComputeBoundingBox(); - bool originspecified = false; - if (!strcmp(InputObject->GetNameOfClass(),"GroupSpatialObject")) - { + SizeType size; + double origine[ObjectDimension]; + InputObject->ComputeBoundingBox(); + bool originspecified = false; + if (!strcmp(InputObject->GetNameOfClass(),"GroupSpatialObject")) + { - ChildrenType children; - children=InputObject->GetChildren(0); - IteratorType iter = children->begin(); - IteratorType end = children->end(); - double minimum[ObjectDimension]; + ChildrenType children; + children=InputObject->GetChildren(0); + IteratorType iter = children->begin(); + IteratorType end = children->end(); + double minimum[ObjectDimension]; - (*iter)->ComputeBoundingBox(); - for(i=0;i<ObjectDimension;i++) - { - minimum[i]=(*iter)->GetBoundingBox()->GetMinimum()[i]; - } + (*iter)->ComputeBoundingBox(); + for (i=0;i<ObjectDimension;i++) + { + minimum[i]=(*iter)->GetBoundingBox()->GetMinimum()[i]; + } - while(iter != end) + while (iter != end) + { + (*iter)->ComputeBoundingBox(); + for (i=0;i<ObjectDimension;i++) + { + if ((*iter)->GetBoundingBox()->GetMinimum()[i] < minimum[i]) { - (*iter)->ComputeBoundingBox(); - for(i=0;i<ObjectDimension;i++) - { - if ((*iter)->GetBoundingBox()->GetMinimum()[i] < minimum[i]) - { - minimum[i]=(*iter)->GetBoundingBox()->GetMinimum()[i]; - } - } - iter++; + minimum[i]=(*iter)->GetBoundingBox()->GetMinimum()[i]; } + } + iter++; + } - for(i=0;i<ObjectDimension;i++) + for (i=0;i<ObjectDimension;i++) { - size[i] = (long unsigned int) (InputObject->GetBoundingBox()->GetMaximum()[i] - minimum[i])+1; - origine[i]=(long int) minimum[i]; - originspecified=true; + size[i] = (long unsigned int) (InputObject->GetBoundingBox()->GetMaximum()[i] - minimum[i])+1; + origine[i]=(long int) minimum[i]; + originspecified=true; - } + } - printf("minx= %6.3f,miny= %6.3f,maxx= %6.3f,maxy= %6.3f \n",minimum[0],minimum[1],InputObject->GetBoundingBox()->GetMaximum()[0],InputObject->GetBoundingBox()->GetMaximum()[1]); + printf("minx= %6.3f,miny= %6.3f,maxx= %6.3f,maxy= %6.3f \n",minimum[0],minimum[1],InputObject->GetBoundingBox()->GetMaximum()[0],InputObject->GetBoundingBox()->GetMaximum()[1]); } else { - for(i=0;i<ObjectDimension;i++) - { - size[i] = (long int)(InputObject->GetBoundingBox()->GetMaximum()[i] - - InputObject->GetBoundingBox()->GetMinimum()[i]); - } + for (i=0;i<ObjectDimension;i++) + { + size[i] = (long int)(InputObject->GetBoundingBox()->GetMaximum()[i] + - InputObject->GetBoundingBox()->GetMinimum()[i]); + } } @@ -345,22 +345,22 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> bool specified = false; for (i = 0; i < OutputImageDimension; i++) - { + { if (m_Size[i] != 0) - { + { specified = true; break; - } } + } if (specified) - { + { region.SetSize( m_Size ); - } + } else - { + { region.SetSize ( size ); - } + } region.SetIndex( index ); OutputImage->SetLargestPossibleRegion( region); // @@ -372,26 +372,26 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> specified = false; for (i = 0; i < OutputImageDimension; i++) - { + { if (m_Spacing[i] != 0) - { + { specified = true; break; - } } + } if (specified) - { + { OutputImage->SetSpacing(this->m_Spacing); // set spacing - } + } else - { + { OutputImage->SetSpacing(InputObject->GetIndexToObjectTransform()->GetScaleComponent()); // set spacing - } + } if (originspecified) { - OutputImage->SetOrigin(origine); // and origin + OutputImage->SetOrigin(origine); // and origin } else OutputImage->SetOrigin(m_Origin); @@ -403,42 +403,42 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> itk::Point<double,ObjectDimension> point; - while(!it.IsAtEnd()) - { + while (!it.IsAtEnd()) + { // ValueAt requires the point to be in physical coordinate i.e - for(unsigned int i=0;i<ObjectDimension;i++) - { + for (unsigned int i=0;i<ObjectDimension;i++) + { point[i]=(int) (it.GetIndex()[i]*m_Spacing[i])+m_Origin[i]; - } + } double val =0; InputObject->ValueAt(point,val,99999); - if( m_InsideValue != 0 - || m_OutsideValue != 0 ) + if ( m_InsideValue != 0 + || m_OutsideValue != 0 ) + { + if ( val) { - if( val) + if (m_UseObjectValue) { - if(m_UseObjectValue) - { it.Set(static_cast<ValueType>(val)); - } + } else - { + { it.Set(m_InsideValue); - } } + } else - { + { it.Set(m_OutsideValue); - } } + } else - { + { it.Set(static_cast<ValueType>(val)); - } - ++it; } + ++it; + } itkDebugMacro(<< "SpatialObjectToImageDrawingFilter::Update() finished"); @@ -455,14 +455,14 @@ SpatialObjectToImageDrawingFilter<TInputSpatialObject,TOutputImage> os << indent << "Children depth : " << m_ChildrenDepth << std::endl; os << indent << "Inside Value : " << m_InsideValue << std::endl; os << indent << "Outside Value : " << m_OutsideValue << std::endl; - if(m_UseObjectValue) - { + if (m_UseObjectValue) + { os << indent << "Using Object Value : ON" << std::endl; - } + } else - { + { os << indent << "Using Object Value : OFF" << std::endl; - } + } } diff --git a/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.h b/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.h index b1306b2631d0b3af13d2c6c28bd945ae40706400..e102b93fd29fcdb83668ff013a91a21fee939d1f 100644 --- a/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.h +++ b/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.h @@ -47,9 +47,9 @@ namespace otb */ template <class TInputImage,class TOutputImage> class ITK_EXPORT SpectralAngleDistanceImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef SpectralAngleDistanceImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -80,7 +80,7 @@ protected: SpectralAngleDistanceImageFilter(); /** Destructor */ virtual ~SpectralAngleDistanceImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** SpectralAngleDistanceImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() routine diff --git a/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.txx b/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.txx index ebbd1becc01b21b98d6288415fec977c3de31951..a41212e896fee16b9c0837461b2bd6d76fb640f2 100644 --- a/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.txx +++ b/Code/BasicFilters/otbSpectralAngleDistanceImageFilter.txx @@ -43,9 +43,9 @@ SpectralAngleDistanceImageFilter<TInputImage,TOutputImage> ::BeforeThreadedGenerateData() { if ( this->GetInput()->GetNumberOfComponentsPerPixel() == 1 ) - { - itkExceptionMacro(<<"Not valid input image : mono channel image not supported."); - } + { + itkExceptionMacro(<<"Not valid input image : mono channel image not supported."); + } } @@ -56,9 +56,9 @@ SpectralAngleDistanceImageFilter<TInputImage,TOutputImage> { if (m_ReferencePixel == 0) - { - itkExceptionMacro(<<"Reference pixel is not set!"); - } + { + itkExceptionMacro(<<"Reference pixel is not set!"); + } InputImageConstPointerType inputPtr = this->GetInput(); OutputImagePointerType outputPtr = this->GetOutput(); @@ -66,10 +66,10 @@ SpectralAngleDistanceImageFilter<TInputImage,TOutputImage> //inputPtr->UpdateOutputInformation(); // Check if the reference pixel size matches the input image number of components. if (m_ReferencePixel.GetSize() != inputPtr->GetNumberOfComponentsPerPixel()) - { - itkExceptionMacro(<<"Reference pixel size ("<<m_ReferencePixel.GetSize()<<" and input image pixel size (" - <<inputPtr->GetNumberOfComponentsPerPixel()<<") don't match!"); - } + { + itkExceptionMacro(<<"Reference pixel size ("<<m_ReferencePixel.GetSize()<<" and input image pixel size (" + <<inputPtr->GetNumberOfComponentsPerPixel()<<") don't match!"); + } // Define the portion of the input to walk for this thread, using @@ -86,40 +86,40 @@ SpectralAngleDistanceImageFilter<TInputImage,TOutputImage> inputIt.GoToBegin(); outputIt.GoToBegin(); - while(!inputIt.IsAtEnd() && !outputIt.IsAtEnd()) - { - double dist=0.0; - double scalarProd=0.0; - double normProd=0.0; - double normProd1=0.0; - double normProd2=0.0; - InputPixelType pixel = inputIt.Get(); - for (unsigned int i=0; i<pixel.Size(); i++) + while (!inputIt.IsAtEnd() && !outputIt.IsAtEnd()) { - scalarProd += pixel[i]*m_ReferencePixel[i]; - normProd1 += pixel[i]*pixel[i]; - normProd2 += m_ReferencePixel[i]*m_ReferencePixel[i]; - } - normProd = normProd1 * normProd2; + double dist=0.0; + double scalarProd=0.0; + double normProd=0.0; + double normProd1=0.0; + double normProd2=0.0; + InputPixelType pixel = inputIt.Get(); + for (unsigned int i=0; i<pixel.Size(); i++) + { + scalarProd += pixel[i]*m_ReferencePixel[i]; + normProd1 += pixel[i]*pixel[i]; + normProd2 += m_ReferencePixel[i]*m_ReferencePixel[i]; + } + normProd = normProd1 * normProd2; - if ( normProd == 0.0) - { - dist = 0.0; - } - else - { - dist = vcl_acos(scalarProd/vcl_sqrt(normProd)); - } - //------ This part was supressed since the filter must perform only the spectral angle computation --- - // Spectral angle normalisation - // dist = dist/(M_PI/2); - //square ponderation - // dist = vcl_sqrt(dist); - outputIt.Set(static_cast<OutputPixelType>(dist)); + if ( normProd == 0.0) + { + dist = 0.0; + } + else + { + dist = vcl_acos(scalarProd/vcl_sqrt(normProd)); + } + //------ This part was supressed since the filter must perform only the spectral angle computation --- + // Spectral angle normalisation + // dist = dist/(M_PI/2); + //square ponderation + // dist = vcl_sqrt(dist); + outputIt.Set(static_cast<OutputPixelType>(dist)); ++inputIt; ++outputIt; progress.CompletedPixel(); // potential exception thrown here - } + } } /** * PrintSelf Method diff --git a/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.h b/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.h index aafcaaf173dd89265420a34f9d5b6e86341ba88b..f1c782c057cce2b9c8a6980aceb2a43b8c3b6c6a 100644 --- a/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.h +++ b/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.h @@ -30,150 +30,160 @@ #include "itkVariableLengthVector.h" #include "otbPersistentFilterStreamingDecorator.h" -namespace otb { - - /** \class PersistentMatrixTransposeMatrixImageFilter - * \brief Compute \f[X^T.Y \f]. Allow a padding of ones. - * - * \f[X\f] and \f[Y\f] are the input images. - * The padding has the effect of adding a component filled with ones to the image - * - * This filter persists its temporary data. It means that if you Update it n times on n different - * requested regions, the output statistics will be the result for the whole set of n regions. - * - * To reset the temporary data, one should call the Reset() function. - * - * To get the statistics once the regions have been processed via the pipeline, use the Synthetize() method. - * - * \sa StreamingTraits - * \sa StatisticsImageFilter - * \ingroup MathematicalStatisticsImageFilters +namespace otb +{ + +/** \class PersistentMatrixTransposeMatrixImageFilter + * \brief Compute \f[X^T.Y \f]. Allow a padding of ones. + * + * \f[X\f] and \f[Y\f] are the input images. + * The padding has the effect of adding a component filled with ones to the image + * + * This filter persists its temporary data. It means that if you Update it n times on n different + * requested regions, the output statistics will be the result for the whole set of n regions. + * + * To reset the temporary data, one should call the Reset() function. + * + * To get the statistics once the regions have been processed via the pipeline, use the Synthetize() method. + * + * \sa StreamingTraits + * \sa StatisticsImageFilter + * \ingroup MathematicalStatisticsImageFilters + */ +template<class TInputImage, class TInputImage2> +class ITK_EXPORT PersistentMatrixTransposeMatrixImageFilter : + public PersistentImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard Self typedef */ + typedef PersistentMatrixTransposeMatrixImageFilter Self; + typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(PersistentMatrixTransposeMatrixImageFilter, PersistentImageFilter); + + /** Image related typedefs. */ + // First Input + typedef TInputImage ImageType; + typedef typename TInputImage::Pointer InputImagePointer; + typedef typename TInputImage::RegionType RegionType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType PixelType; + typedef typename TInputImage::InternalPixelType InternalPixelType; + + typedef typename TInputImage2::IndexType IndexType2; + typedef typename TInputImage2::PixelType PixelType2; + typedef typename TInputImage2::InternalPixelType InternalPixelType2; + + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + + itkSetMacro(UsePadFirstInput,bool); + itkGetMacro(UsePadFirstInput,bool); + itkSetMacro(UsePadSecondInput,bool); + itkGetMacro(UsePadSecondInput,bool); + + /** Image related typedefs. */ + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension ); + + /** Type to use for computations. */ + // First Input + typedef double RealType; + typedef itk::VariableLengthVector<RealType> RealPixelType; + + + /** Smart Pointer type to a DataObject. */ + typedef typename itk::DataObject::Pointer DataObjectPointer; + + /** Type of DataObjects used for scalar outputs */ + typedef typename itk::Array<long> ArrayLongPixelType; + typedef typename itk::VariableSizeMatrix<RealType> MatrixType; + typedef typename std::vector<MatrixType> ArrayMatrixType; + typedef typename std::vector<RealPixelType> ArrayRealPixelType; + typedef typename std::vector<PixelType> ArrayPixelType; + typedef itk::SimpleDataObjectDecorator<RealPixelType> RealPixelObjectType; + typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; + typedef itk::SimpleDataObjectDecorator<MatrixType> MatrixObjectType; + + + /** Return the computed transpose(Image1)*Image2. */ + MatrixType GetResult() const + { + return this->GetResultOutput()->Get(); + }; + MatrixObjectType* GetResultOutput(); + const MatrixObjectType* GetResultOutput() const; + + + /** Make a DataObject of the correct type to be used as the specified + * output. */ - template<class TInputImage, class TInputImage2> - class ITK_EXPORT PersistentMatrixTransposeMatrixImageFilter : - public PersistentImageFilter<TInputImage, TInputImage> - { - public: - /** Standard Self typedef */ - typedef PersistentMatrixTransposeMatrixImageFilter Self; - typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Runtime information support. */ - itkTypeMacro(PersistentMatrixTransposeMatrixImageFilter, PersistentImageFilter); - - /** Image related typedefs. */ - // First Input - typedef TInputImage ImageType; - typedef typename TInputImage::Pointer InputImagePointer; - typedef typename TInputImage::RegionType RegionType; - typedef typename TInputImage::SizeType SizeType; - typedef typename TInputImage::IndexType IndexType; - typedef typename TInputImage::PixelType PixelType; - typedef typename TInputImage::InternalPixelType InternalPixelType; - - typedef typename TInputImage2::IndexType IndexType2; - typedef typename TInputImage2::PixelType PixelType2; - typedef typename TInputImage2::InternalPixelType InternalPixelType2; - - itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); - - itkSetMacro(UsePadFirstInput,bool); - itkGetMacro(UsePadFirstInput,bool); - itkSetMacro(UsePadSecondInput,bool); - itkGetMacro(UsePadSecondInput,bool); - - /** Image related typedefs. */ - itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension ); - - /** Type to use for computations. */ - // First Input - typedef double RealType; - typedef itk::VariableLengthVector<RealType> RealPixelType; - - - /** Smart Pointer type to a DataObject. */ - typedef typename itk::DataObject::Pointer DataObjectPointer; - - /** Type of DataObjects used for scalar outputs */ - typedef typename itk::Array<long> ArrayLongPixelType; - typedef typename itk::VariableSizeMatrix<RealType> MatrixType; - typedef typename std::vector<MatrixType> ArrayMatrixType; - typedef typename std::vector<RealPixelType> ArrayRealPixelType; - typedef typename std::vector<PixelType> ArrayPixelType; - typedef itk::SimpleDataObjectDecorator<RealPixelType> RealPixelObjectType; - typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; - typedef itk::SimpleDataObjectDecorator<MatrixType> MatrixObjectType; - - - /** Return the computed transpose(Image1)*Image2. */ - MatrixType GetResult() const { return this->GetResultOutput()->Get(); }; - MatrixObjectType* GetResultOutput(); - const MatrixObjectType* GetResultOutput() const; - - - /** Make a DataObject of the correct type to be used as the specified - * output. - */ - virtual DataObjectPointer MakeOutput(unsigned int idx); - - /** Pass the input through unmodified. Do this by Grafting in the - * AllocateOutputs method. - */ - void AllocateOutputs(); - void GenerateOutputInformation(); - // Override since the filter needs all the data for the algorithm - virtual void GenerateInputRequestedRegion(); - virtual void Reset(void); - virtual void Synthetize(void); - - /** Input wrapper */ - void SetFirstInput(const TInputImage *input1){ this->SetInput(0, input1 ); }; - void SetSecondInput(const TInputImage2 *input2){ this->SetInput(1, input2 ); }; - - const TInputImage* GetFirstInput() + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** Pass the input through unmodified. Do this by Grafting in the + * AllocateOutputs method. + */ + void AllocateOutputs(); + void GenerateOutputInformation(); + // Override since the filter needs all the data for the algorithm + virtual void GenerateInputRequestedRegion(); + virtual void Reset(void); + virtual void Synthetize(void); + + /** Input wrapper */ + void SetFirstInput(const TInputImage *input1) { - if( this->GetNumberOfInputs() < 1 ) - { - return 0; - } + this->SetInput(0, input1 ); + }; + void SetSecondInput(const TInputImage2 *input2) + { + this->SetInput(1, input2 ); + }; + + const TInputImage* GetFirstInput() + { + if ( this->GetNumberOfInputs() < 1 ) + { + return 0; + } else return( static_cast<const TInputImage *>(this->itk::ProcessObject::GetInput(0)) ); } - const TInputImage2* GetSecondInput() + const TInputImage2* GetSecondInput() { - if( this->GetNumberOfInputs() < 2 ) - { - return 0; - } + if ( this->GetNumberOfInputs() < 2 ) + { + return 0; + } else return( static_cast<const TInputImage2 *>(this->itk::ProcessObject::GetInput(1)) ); } - protected: - PersistentMatrixTransposeMatrixImageFilter(); - ~PersistentMatrixTransposeMatrixImageFilter(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Multi-thread version GenerateData. */ - virtual void ThreadedGenerateData (const RegionType& outputRegionForThread,int threadId); +protected: + PersistentMatrixTransposeMatrixImageFilter(); + ~PersistentMatrixTransposeMatrixImageFilter() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Multi-thread version GenerateData. */ + virtual void ThreadedGenerateData (const RegionType& outputRegionForThread,int threadId); - private: - PersistentMatrixTransposeMatrixImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + PersistentMatrixTransposeMatrixImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - ArrayMatrixType m_ThreadSum; - bool m_UsePadFirstInput; - bool m_UsePadSecondInput; + ArrayMatrixType m_ThreadSum; + bool m_UsePadFirstInput; + bool m_UsePadSecondInput; - /** Nulber Of Component per Pixel. Change for padding */ - unsigned int m_NumberOfComponents1; - unsigned int m_NumberOfComponents2; - }; // end of class + /** Nulber Of Component per Pixel. Change for padding */ + unsigned int m_NumberOfComponents1; + unsigned int m_NumberOfComponents2; +}; // end of class /**===========================================================================*/ @@ -199,14 +209,14 @@ namespace otb { template<class TInputImage1, class TInputImage2> class ITK_EXPORT StreamingMatrixTransposeMatrixImageFilter : - public PersistentFilterStreamingDecorator - < PersistentMatrixTransposeMatrixImageFilter<TInputImage1, TInputImage2> > + public PersistentFilterStreamingDecorator + < PersistentMatrixTransposeMatrixImageFilter<TInputImage1, TInputImage2> > { public: /** Standard Self typedef */ typedef StreamingMatrixTransposeMatrixImageFilter Self; typedef PersistentFilterStreamingDecorator - < PersistentMatrixTransposeMatrixImageFilter<TInputImage1, TInputImage2> > Superclass; + < PersistentMatrixTransposeMatrixImageFilter<TInputImage1, TInputImage2> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -225,49 +235,49 @@ public: /** Interfaces to the embedded filter */ void SetFirstInput(InputImage1Type * input1) - { - this->GetFilter()->SetFirstInput(input1); - } + { + this->GetFilter()->SetFirstInput(input1); + } void SetSecondInput(InputImage2Type * input2) - { - this->GetFilter()->SetSecondInput(input2); - } + { + this->GetFilter()->SetSecondInput(input2); + } void SetUsePadFirstInput(bool pad) - { - this->GetFilter()->SetUsePadFirstInput(pad); - } + { + this->GetFilter()->SetUsePadFirstInput(pad); + } void SetUsePadSecondInput(bool pad) - { - this->GetFilter()->SetUsePadSecondInput(pad); - } + { + this->GetFilter()->SetUsePadSecondInput(pad); + } bool GetUsePadFirstInput(void) - { - return this->GetFilter()->GetUsePadFirstInput(); - } + { + return this->GetFilter()->GetUsePadFirstInput(); + } bool GetUsePadSecondInput(void) - { - return this->GetFilter()->GetUsePadSecondInput(); - } + { + return this->GetFilter()->GetUsePadSecondInput(); + } /** Return the computed transpose(Image1)*Image2. */ MatrixType GetResult(void) const - { - return this->GetResultOutput()->Get(); - } + { + return this->GetResultOutput()->Get(); + } MatrixObjectType* GetResultOutput(void) - { - return this->GetFilter()->GetResultOutput(); - } + { + return this->GetFilter()->GetResultOutput(); + } const MatrixObjectType* GetResultOutput() const - { - return this->GetFilter()->GetResultOutput(); - } - protected: + { + return this->GetFilter()->GetResultOutput(); + } +protected: /** Constructor */ - StreamingMatrixTransposeMatrixImageFilter(){}; + StreamingMatrixTransposeMatrixImageFilter() {}; /** Destructor */ - virtual ~StreamingMatrixTransposeMatrixImageFilter(){}; + virtual ~StreamingMatrixTransposeMatrixImageFilter() {}; - private: +private: StreamingMatrixTransposeMatrixImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; diff --git a/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.txx b/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.txx index 604d4e010d3bcdd6095978df34938212a9a627ab..7a300ca842dc1f08d7041f17f0f0844823e3b01b 100644 --- a/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.txx +++ b/Code/BasicFilters/otbStreamingMatrixTransposeMatrixImageFilter.txx @@ -29,7 +29,8 @@ #include "itkProgressReporter.h" -namespace otb { +namespace otb +{ template<class TInputImage, class TInputImage2> PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> @@ -64,18 +65,18 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> ::MakeOutput(unsigned int output) { switch (output) - { - case 0: - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - case 1: - return static_cast<itk::DataObject*>(MatrixObjectType::New().GetPointer()); - break; - default: - // might as well make an image - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - } + { + case 0: + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; + case 1: + return static_cast<itk::DataObject*>(MatrixObjectType::New().GetPointer()); + break; + default: + // might as well make an image + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; + } } template<class TInputImage, class TInputImage2> @@ -103,12 +104,12 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> Superclass::GenerateInputRequestedRegion(); if ( this->GetFirstInput() && this->GetSecondInput() ) - { - InputImagePointer image = const_cast< typename Superclass::InputImageType * >( this->GetFirstInput() ); - InputImagePointer image2 = const_cast< typename Superclass::InputImageType * >( this->GetSecondInput() ); - image->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); - image2->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); - } + { + InputImagePointer image = const_cast< typename Superclass::InputImageType * >( this->GetFirstInput() ); + InputImagePointer image2 = const_cast< typename Superclass::InputImageType * >( this->GetSecondInput() ); + image->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); + image2->SetRequestedRegion(this->GetOutput()->GetRequestedRegion()); + } } template<class TInputImage, class TInputImage2> void @@ -117,15 +118,15 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> { Superclass::GenerateOutputInformation(); if ( this->GetFirstInput() ) - { - this->GetOutput()->CopyInformation(this->GetFirstInput()); - this->GetOutput()->SetLargestPossibleRegion(this->GetFirstInput()->GetLargestPossibleRegion()); - } + { + this->GetOutput()->CopyInformation(this->GetFirstInput()); + this->GetOutput()->SetLargestPossibleRegion(this->GetFirstInput()->GetLargestPossibleRegion()); + } - if(this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) - { - this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); - } + if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) + { + this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); + } } template<class TInputImage, class TInputImage2> @@ -151,32 +152,32 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> TInputImage2 * inputPtr2 = const_cast<TInputImage2 * >(this->GetSecondInput()); inputPtr2->UpdateOutputInformation(); - if(this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) - { - this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); - } + if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) + { + this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); + } if ( inputPtr1->GetLargestPossibleRegion().GetSize() != inputPtr2->GetLargestPossibleRegion().GetSize() ) - { - itkExceptionMacro( <<" Can't multiply the transposed matrix of a " - << inputPtr1->GetLargestPossibleRegion().GetSize() - << " and a " - << inputPtr2->GetLargestPossibleRegion().GetSize() - << " matrix " ); - } + { + itkExceptionMacro( <<" Can't multiply the transposed matrix of a " + << inputPtr1->GetLargestPossibleRegion().GetSize() + << " and a " + << inputPtr2->GetLargestPossibleRegion().GetSize() + << " matrix " ); + } m_NumberOfComponents1 = inputPtr1->GetNumberOfComponentsPerPixel(); m_NumberOfComponents2 = inputPtr2->GetNumberOfComponentsPerPixel(); unsigned int numberOfThreads = this->GetNumberOfThreads(); if ( m_UsePadFirstInput == true ) - { - m_NumberOfComponents1++; - } + { + m_NumberOfComponents1++; + } if ( m_UsePadSecondInput == true ) - { - m_NumberOfComponents2++; - } + { + m_NumberOfComponents2++; + } MatrixType tempMatrix, initMatrix; tempMatrix.SetSize(m_NumberOfComponents1, m_NumberOfComponents2); @@ -202,21 +203,21 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> resultMatrix.Fill(itk::NumericTraits<RealType>::Zero); - for( unsigned int thread = 0; thread < numberOfThreads; thread++) - { - /** TODO - * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) - * resultMatrix += m_ThreadSum[thread]; - **/ - for (unsigned int i=0; i<resultMatrix.Rows(); i++) + for ( unsigned int thread = 0; thread < numberOfThreads; thread++) { - for (unsigned int j=0; j<resultMatrix.Cols(); j++) + /** TODO + * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) + * resultMatrix += m_ThreadSum[thread]; + **/ + for (unsigned int i=0; i<resultMatrix.Rows(); i++) + { + for (unsigned int j=0; j<resultMatrix.Cols(); j++) { resultMatrix(i, j) += m_ThreadSum[thread](i, j); } - } - /********END TODO ******/ } + /********END TODO ******/ + } this->GetResultOutput()->Set( resultMatrix ); } @@ -247,49 +248,49 @@ PersistentMatrixTransposeMatrixImageFilter<TInputImage, TInputImage2> // loop the second image and get one pixel a time while (!it1.IsAtEnd()) - { - PixelType vectorValue1 = it1.Get(); - PixelType2 vectorValue2 = it2.Get(); - - // Add a first component to vectorValue2 and vectorValue1 filled with ones. - if (m_UsePadFirstInput == true) { - PixelType vectortemp1(vectorValue1.Size()+1); - vectortemp1[0] = 1; - for (unsigned int n=0; n<vectorValue1.Size(); n++) + PixelType vectorValue1 = it1.Get(); + PixelType2 vectorValue2 = it2.Get(); + + // Add a first component to vectorValue2 and vectorValue1 filled with ones. + if (m_UsePadFirstInput == true) + { + PixelType vectortemp1(vectorValue1.Size()+1); + vectortemp1[0] = 1; + for (unsigned int n=0; n<vectorValue1.Size(); n++) { - vectortemp1[n+1] = vectorValue1[n]; + vectortemp1[n+1] = vectorValue1[n]; } - vectorValue1.SetSize(vectortemp1.Size()); - vectorValue1 = vectortemp1; - } + vectorValue1.SetSize(vectortemp1.Size()); + vectorValue1 = vectortemp1; + } - if (m_UsePadSecondInput == true) - { - PixelType2 vectortemp2(vectorValue2.Size()+1); - vectortemp2[0] = 1; - for (unsigned int m=0; m<vectorValue2.Size(); m++) + if (m_UsePadSecondInput == true) + { + PixelType2 vectortemp2(vectorValue2.Size()+1); + vectortemp2[0] = 1; + for (unsigned int m=0; m<vectorValue2.Size(); m++) { vectortemp2[m+1] = vectorValue2[m]; } - vectorValue2.SetSize(vectortemp2.Size()); - vectorValue2 = vectortemp2; - } + vectorValue2.SetSize(vectortemp2.Size()); + vectorValue2 = vectortemp2; + } - for (unsigned int i=0; i<vectorValue1.Size(); i++) - { - for (unsigned int j=0; j<vectorValue2.Size(); j++) + for (unsigned int i=0; i<vectorValue1.Size(); i++) + { + for (unsigned int j=0; j<vectorValue2.Size(); j++) { m_ThreadSum[threadId](i, j) += static_cast<RealType>(vectorValue1[i])*static_cast<RealType>(vectorValue2[j]); } - } - ++it1; - ++it2; - progress.CompletedPixel(); } + ++it1; + ++it2; + progress.CompletedPixel(); + } } template<class TInputImage, class TInputImage2> diff --git a/Code/BasicFilters/otbStreamingResampleImageFilter.h b/Code/BasicFilters/otbStreamingResampleImageFilter.h index 3752b8914945235332d73e13f4a54dbc7554d69f..906dbdc8230350b1eee031ddc3d81e507adfb9c8 100644 --- a/Code/BasicFilters/otbStreamingResampleImageFilter.h +++ b/Code/BasicFilters/otbStreamingResampleImageFilter.h @@ -52,7 +52,7 @@ public: /** Method for creation through the object factory. */ itkNewMacro(Self); - /** Run-time type information (and related methods). */ + /** Run-time type information (and related methods). */ itkTypeMacro(StreamingResampleImageFilter, itk::ResampleImageFilter); /** Type definitions */ diff --git a/Code/BasicFilters/otbStreamingResampleImageFilter.txx b/Code/BasicFilters/otbStreamingResampleImageFilter.txx index a3e55e7745d7367afb02e6352046c6f8edc4ba85..ad1ea471e1fb7baffe9ab57c6870ef12c9a7dbc8 100644 --- a/Code/BasicFilters/otbStreamingResampleImageFilter.txx +++ b/Code/BasicFilters/otbStreamingResampleImageFilter.txx @@ -31,167 +31,168 @@ #include "itkContinuousIndex.h" -namespace otb { - - template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> - StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> - ::StreamingResampleImageFilter() - { - // Default neighborhood interpolation radius is one pixel - m_InterpolatorNeighborhoodRadius = 1; - m_AddedRadius = 2; - } - - - template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> - void - StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> - ::GenerateInputRequestedRegion() +namespace otb +{ + +template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> +StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> +::StreamingResampleImageFilter() +{ + // Default neighborhood interpolation radius is one pixel + m_InterpolatorNeighborhoodRadius = 1; + m_AddedRadius = 2; +} + + +template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> +void +StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> +::GenerateInputRequestedRegion() +{ + Superclass::GenerateInputRequestedRegion(); + + if ( this->GetInput() ) { - Superclass::GenerateInputRequestedRegion(); + otbMsgDevMacro(<< "-------------- GenerateInputRequestedRegion ---------------" << std::endl); - if ( this->GetInput() ) - { - otbMsgDevMacro(<< "-------------- GenerateInputRequestedRegion ---------------" << std::endl); - - InputImagePointer inputImage = const_cast< typename Superclass::InputImageType *>( this->GetInput() ); - OutputImagePointer outputImage = const_cast< typename Superclass::OutputImageType *>( this->GetOutput() ); + InputImagePointer inputImage = const_cast< typename Superclass::InputImageType *>( this->GetInput() ); + OutputImagePointer outputImage = const_cast< typename Superclass::OutputImageType *>( this->GetOutput() ); - IndexType index = outputImage->GetRequestedRegion().GetIndex(); - SizeType size = outputImage->GetRequestedRegion().GetSize(); + IndexType index = outputImage->GetRequestedRegion().GetIndex(); + SizeType size = outputImage->GetRequestedRegion().GetSize(); - // Obtain coordinates of upperleft, upperright, lowerleft and lowerright points in the image - IndexType indexTmp; - std::vector<IndexType> vPoints; - typename std::vector<IndexType>::iterator it; + // Obtain coordinates of upperleft, upperright, lowerleft and lowerright points in the image + IndexType indexTmp; + std::vector<IndexType> vPoints; + typename std::vector<IndexType>::iterator it; - otbMsgDevMacro(<< "Size : " << size[0] << " " << size[1]); + otbMsgDevMacro(<< "Size : " << size[0] << " " << size[1]); - indexTmp[0]=index[0]; - indexTmp[1]=index[1]; - vPoints.push_back(indexTmp); - //otbGenericMsgDebugMacro(<< "indexUL : (" << indexTmp[0] << "," << indexTmp[1] << ")"); + indexTmp[0]=index[0]; + indexTmp[1]=index[1]; + vPoints.push_back(indexTmp); + //otbGenericMsgDebugMacro(<< "indexUL : (" << indexTmp[0] << "," << indexTmp[1] << ")"); - indexTmp[0]=index[0]+size[0]; - indexTmp[1]=index[1]; - vPoints.push_back(indexTmp); - //otbGenericMsgDebugMacro(<< "indexUR : (" << indexTmp[0] << "," << indexTmp[1] << ")"); + indexTmp[0]=index[0]+size[0]; + indexTmp[1]=index[1]; + vPoints.push_back(indexTmp); + //otbGenericMsgDebugMacro(<< "indexUR : (" << indexTmp[0] << "," << indexTmp[1] << ")"); - indexTmp[0]=index[0]+size[0]; - indexTmp[1]=index[1]+size[1]; - vPoints.push_back(indexTmp); - //otbGenericMsgDebugMacro(<< "indexLR : (" << indexTmp[0] << "," << indexTmp[1] << ")"); + indexTmp[0]=index[0]+size[0]; + indexTmp[1]=index[1]+size[1]; + vPoints.push_back(indexTmp); + //otbGenericMsgDebugMacro(<< "indexLR : (" << indexTmp[0] << "," << indexTmp[1] << ")"); - indexTmp[0]=index[0]; - indexTmp[1]=index[1]+size[1]; - vPoints.push_back(indexTmp); - //otbGenericMsgDebugMacro(<< "indexLL : (" << indexTmp[0] << "," << indexTmp[1] << ")"); + indexTmp[0]=index[0]; + indexTmp[1]=index[1]+size[1]; + vPoints.push_back(indexTmp); + //otbGenericMsgDebugMacro(<< "indexLL : (" << indexTmp[0] << "," << indexTmp[1] << ")"); - typedef itk::ContinuousIndex<TInterpolatorPrecisionType, 2> ContinuousIndexType; - typename ContinuousIndexType::ValueType minX = itk::NumericTraits<typename ContinuousIndexType::ValueType>::max(); - typename ContinuousIndexType::ValueType maxX = 0; - typename ContinuousIndexType::ValueType minY = itk::NumericTraits<typename ContinuousIndexType::ValueType>::max(); - typename ContinuousIndexType::ValueType maxY = 0; + typedef itk::ContinuousIndex<TInterpolatorPrecisionType, 2> ContinuousIndexType; + typename ContinuousIndexType::ValueType minX = itk::NumericTraits<typename ContinuousIndexType::ValueType>::max(); + typename ContinuousIndexType::ValueType maxX = 0; + typename ContinuousIndexType::ValueType minY = itk::NumericTraits<typename ContinuousIndexType::ValueType>::max(); + typename ContinuousIndexType::ValueType maxY = 0; - // Coordinates of current output pixel - PointType outputPoint; - PointType inputPoint; + // Coordinates of current output pixel + PointType outputPoint; + PointType inputPoint; - // Transform each "corner" point - for (it = vPoints.begin(); it != vPoints.end(); it++) - { - ContinuousIndexType indexTmpTr; + // Transform each "corner" point + for (it = vPoints.begin(); it != vPoints.end(); it++) + { + ContinuousIndexType indexTmpTr; // Calculate transformed points needed for previous filter in the pipeline // std::cout << "Origin : " << outputImage->GetOrigin() << std::endl; // std::cout << "Spacing : " << outputImage->GetSpacing() << std::endl; - outputImage->TransformIndexToPhysicalPoint( *it, outputPoint ); + outputImage->TransformIndexToPhysicalPoint( *it, outputPoint ); - otbMsgDevMacro(<< "Ncurrent Index :(" << (*it)[0]<<","<< (*it)[1] << ")"<< std::endl - << "Physical point: ("<< outputPoint[0]<< ","<< outputPoint[1]<< ")"); + otbMsgDevMacro(<< "Ncurrent Index :(" << (*it)[0]<<","<< (*it)[1] << ")"<< std::endl + << "Physical point: ("<< outputPoint[0]<< ","<< outputPoint[1]<< ")"); // Compute corresponding input pixel continuous index - inputPoint = this->GetTransform()->TransformPoint(outputPoint); - inputImage->TransformPhysicalPointToContinuousIndex(inputPoint, indexTmpTr); + inputPoint = this->GetTransform()->TransformPoint(outputPoint); + inputImage->TransformPhysicalPointToContinuousIndex(inputPoint, indexTmpTr); - otbMsgDevMacro(<< " -> Point Index:" << std::endl - << indexTmpTr[0] << ","<< indexTmpTr[1] ); + otbMsgDevMacro(<< " -> Point Index:" << std::endl + << indexTmpTr[0] << ","<< indexTmpTr[1] ); - if (indexTmpTr[0]>maxX) - maxX = indexTmpTr[0]; + if (indexTmpTr[0]>maxX) + maxX = indexTmpTr[0]; - if (indexTmpTr[0]<minX) - minX = indexTmpTr[0]; + if (indexTmpTr[0]<minX) + minX = indexTmpTr[0]; - if (indexTmpTr[1]>maxY) - maxY = indexTmpTr[1]; + if (indexTmpTr[1]>maxY) + maxY = indexTmpTr[1]; - if (indexTmpTr[1]<minY) - minY = indexTmpTr[1]; + if (indexTmpTr[1]<minY) + minY = indexTmpTr[1]; - //otbGenericMsgDebugMacro(<< "indexTr : (" << indexTmpTr[0] << "," << indexTmpTr[1] << ")"); - } + //otbGenericMsgDebugMacro(<< "indexTr : (" << indexTmpTr[0] << "," << indexTmpTr[1] << ")"); + } - otbMsgDevMacro(<< "MinX : " << minX << " MinY : " << minY << " MaxX : " << maxX << " MaxY " << maxY); + otbMsgDevMacro(<< "MinX : " << minX << " MinY : " << minY << " MaxX : " << maxX << " MaxY " << maxY); - // Create region needed in previous filter in the pipeline, which is the bounding box of previous transformed points - InputImageRegionType region; - index[0] = static_cast<long int>(minX); - index[1] = static_cast<long int>(minY); - size[0] = static_cast<long unsigned int>(maxX - minX); - size[1] = static_cast<long unsigned int>(maxY - minY); + // Create region needed in previous filter in the pipeline, which is the bounding box of previous transformed points + InputImageRegionType region; + index[0] = static_cast<long int>(minX); + index[1] = static_cast<long int>(minY); + size[0] = static_cast<long unsigned int>(maxX - minX); + size[1] = static_cast<long unsigned int>(maxY - minY); - otbMsgDevMacro(<< "Index : (" << index[0] << "," << index[1] << ") Size : (" << size[0] << "," << size[1] << ")"); + otbMsgDevMacro(<< "Index : (" << index[0] << "," << index[1] << ") Size : (" << size[0] << "," << size[1] << ")"); - region.SetSize(size); - region.SetIndex(index); + region.SetSize(size); + region.SetIndex(index); - // Grow region to be sure that interpolator can found needed point on image borders - unsigned int neededRadius = StreamingTraits<typename Superclass::InputImageType>::CalculateNeededRadiusForInterpolator(this->GetInterpolator()); + // Grow region to be sure that interpolator can found needed point on image borders + unsigned int neededRadius = StreamingTraits<typename Superclass::InputImageType>::CalculateNeededRadiusForInterpolator(this->GetInterpolator()); - if (neededRadius == 0) - { - itkGenericOutputMacro(<< "If you haven't fixed interpolator radius, default is 1"); - neededRadius = m_InterpolatorNeighborhoodRadius; - } + if (neededRadius == 0) + { + itkGenericOutputMacro(<< "If you haven't fixed interpolator radius, default is 1"); + neededRadius = m_InterpolatorNeighborhoodRadius; + } - otbMsgDevMacro(<< "Interpolation needed radius : " << neededRadius); - region.PadByRadius(neededRadius+m_AddedRadius); + otbMsgDevMacro(<< "Interpolation needed radius : " << neededRadius); + region.PadByRadius(neededRadius+m_AddedRadius); - otbMsgDevMacro(<< "Initial Region : Index(" << inputImage->GetLargestPossibleRegion().GetIndex()[0] << "," << inputImage->GetLargestPossibleRegion().GetIndex()[1] << ") Size(" << inputImage->GetLargestPossibleRegion().GetSize()[0] << "," << inputImage->GetLargestPossibleRegion().GetSize()[1] << ")"); + otbMsgDevMacro(<< "Initial Region : Index(" << inputImage->GetLargestPossibleRegion().GetIndex()[0] << "," << inputImage->GetLargestPossibleRegion().GetIndex()[1] << ") Size(" << inputImage->GetLargestPossibleRegion().GetSize()[0] << "," << inputImage->GetLargestPossibleRegion().GetSize()[1] << ")"); - // To be sure that requested region in pipeline is not largest than real input image - otbMsgDevMacro(<< "Final Region (Before Crop) : Index(" << region.GetIndex()[0] << "," << region.GetIndex()[1] << ") Size(" << region.GetSize()[0] << "," << region.GetSize()[1] << ")"); + // To be sure that requested region in pipeline is not largest than real input image + otbMsgDevMacro(<< "Final Region (Before Crop) : Index(" << region.GetIndex()[0] << "," << region.GetIndex()[1] << ") Size(" << region.GetSize()[0] << "," << region.GetSize()[1] << ")"); - // If requested region is not contained in input image, then result region is null - if (!region.Crop(inputImage->GetLargestPossibleRegion())) - { - index[0]=0; - index[1]=0; - size[0]=0; - size[1]=0; - region.SetIndex(index); - region.SetSize(size); - } + // If requested region is not contained in input image, then result region is null + if (!region.Crop(inputImage->GetLargestPossibleRegion())) + { + index[0]=0; + index[1]=0; + size[0]=0; + size[1]=0; + region.SetIndex(index); + region.SetSize(size); + } - inputImage->SetRequestedRegion(region); + inputImage->SetRequestedRegion(region); - otbMsgDevMacro(<< "Final Region (After Crop) : Index(" << region.GetIndex()[0] << "," << region.GetIndex()[1] << ") Size(" << region.GetSize()[0] << "," << region.GetSize()[1] << ")"); - } + otbMsgDevMacro(<< "Final Region (After Crop) : Index(" << region.GetIndex()[0] << "," << region.GetIndex()[1] << ") Size(" << region.GetSize()[0] << "," << region.GetSize()[1] << ")"); } +} - template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> - void - StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "m_InterpolatorNeighborhoodRadius: " << m_InterpolatorNeighborhoodRadius<<std::endl; - os << indent << "m_AddedRadius: " <<m_AddedRadius<< std::endl; - } +template<class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> +void +StreamingResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "m_InterpolatorNeighborhoodRadius: " << m_InterpolatorNeighborhoodRadius<<std::endl; + os << indent << "m_AddedRadius: " <<m_AddedRadius<< std::endl; +} }// end namespace otb diff --git a/Code/BasicFilters/otbStreamingShrinkImageFilter.h b/Code/BasicFilters/otbStreamingShrinkImageFilter.h index f879a31b8fc03cd15cf8349ba0ab4c33f3b08385..8e30d71f9f772ca4c9c6f1af5ad16263e05fcbc7 100644 --- a/Code/BasicFilters/otbStreamingShrinkImageFilter.h +++ b/Code/BasicFilters/otbStreamingShrinkImageFilter.h @@ -23,24 +23,24 @@ namespace otb { - /** \class StreamingShrinkImageFilter - * \brief This class performs a streaming isotropic shrinking operation without smoothing. - * - * It is intended to be used where a fast quicklook generation is needed for huge images - * (for instance for visualization applications). - * - * It computes the size of the output according to the size of the input image, a read only - * the strip of the input image needed to build a line of the output image. In this strip, - * the pixel are directly selected and passed to the output image. - * - * For example, with a 6000X6000 image and a 10 shrinkFactor, it will read 600 lines of 5990 pixels - * instead of the whole image. - */ +/** \class StreamingShrinkImageFilter + * \brief This class performs a streaming isotropic shrinking operation without smoothing. + * + * It is intended to be used where a fast quicklook generation is needed for huge images + * (for instance for visualization applications). + * + * It computes the size of the output according to the size of the input image, a read only + * the strip of the input image needed to build a line of the output image. In this strip, + * the pixel are directly selected and passed to the output image. + * + * For example, with a 6000X6000 image and a 10 shrinkFactor, it will read 600 lines of 5990 pixels + * instead of the whole image. + */ template <class TInputImage,class TOutputImage> class ITK_EXPORT StreamingShrinkImageFilter -: public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef StreamingShrinkImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -74,7 +74,7 @@ class ITK_EXPORT StreamingShrinkImageFilter /** Main computation method */ virtual void UpdateOutputData(itk::DataObject *itkNotUsed(output)); - protected: +protected: /** Constructor */ StreamingShrinkImageFilter(); /** Destructor */ @@ -82,14 +82,14 @@ class ITK_EXPORT StreamingShrinkImageFilter /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: StreamingShrinkImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented /** The shrink factor */ unsigned int m_ShrinkFactor; - }; +}; } // End namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/BasicFilters/otbStreamingShrinkImageFilter.txx b/Code/BasicFilters/otbStreamingShrinkImageFilter.txx index 3022347d132db1b142ff36c2c07d3fa53ef1ea16..58b70c221cb3c36b2c0fb5816d2b5936425c0190 100644 --- a/Code/BasicFilters/otbStreamingShrinkImageFilter.txx +++ b/Code/BasicFilters/otbStreamingShrinkImageFilter.txx @@ -57,11 +57,11 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> // we need to compute the output spacing, the output image size, and the // output image start index const typename InputImageType::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::SizeType& inputSize - = inputPtr->GetLargestPossibleRegion().GetSize(); + = inputPtr->GetLargestPossibleRegion().GetSize(); const typename InputImageType::IndexType& inputStartIndex - = inputPtr->GetLargestPossibleRegion().GetIndex(); + = inputPtr->GetLargestPossibleRegion().GetIndex(); otbMsgDebugMacro(<<"Input index "<<inputStartIndex); otbMsgDebugMacro(<<"Input size: "<<inputSize); @@ -70,12 +70,12 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> typename OutputImageType::IndexType outputStartIndex; for (unsigned int i = 0; i < OutputImageType::ImageDimension; i++) - { - outputSpacing[i] = inputSpacing[i] * static_cast<double>( m_ShrinkFactor); - outputSize[i] = static_cast<int>( static_cast<double>(inputSize[i])/static_cast<double>( m_ShrinkFactor )); - //outputStartIndex[i] = inputStartIndex[i]; - outputStartIndex[i]=0; - } + { + outputSpacing[i] = inputSpacing[i] * static_cast<double>( m_ShrinkFactor); + outputSize[i] = static_cast<int>( static_cast<double>(inputSize[i])/static_cast<double>( m_ShrinkFactor )); + //outputStartIndex[i] = inputStartIndex[i]; + outputStartIndex[i]=0; + } outputPtr->SetSpacing( outputSpacing ); typename OutputImageType::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); @@ -92,15 +92,15 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> // otbMsgDebugMacro(<<"Call to GenerateInputRequestedRegion"); // if(this->GetInput()) // { - InputImagePointerType inputPtr = const_cast<InputImageType * >( this->GetInput(0) ); - // otbMsgDebugMacro(<<"Input largest possible region: "<<inputPtr->GetLargestPossibleRegion()); - typename InputImageType::IndexType index = inputPtr->GetLargestPossibleRegion().GetIndex(); - typename InputImageType::SizeType size; - size.Fill(0); - typename InputImageType::RegionType region; - region.SetSize(size); - region.SetIndex(index); - inputPtr->SetRequestedRegion(region); + InputImagePointerType inputPtr = const_cast<InputImageType * >( this->GetInput(0) ); + // otbMsgDebugMacro(<<"Input largest possible region: "<<inputPtr->GetLargestPossibleRegion()); + typename InputImageType::IndexType index = inputPtr->GetLargestPossibleRegion().GetIndex(); + typename InputImageType::SizeType size; + size.Fill(0); + typename InputImageType::RegionType region; + region.SetSize(size); + region.SetIndex(index); + inputPtr->SetRequestedRegion(region); // } } @@ -115,9 +115,9 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> * prevent chasing our tail */ if (this->m_Updating) - { + { return; - } + } /** * Prepare all the outputs. This may deallocate previous bulk data. */ @@ -128,10 +128,10 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> */ unsigned int ninputs = this->GetNumberOfValidRequiredInputs(); if (ninputs < 1) - { + { itkExceptionMacro(<< "At least 1 input is required but only " << ninputs << " are specified."); return; - } + } this->SetAbortGenerateData(0); this->SetProgress(0.0); this->m_Updating = true; @@ -163,7 +163,7 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> typename OutputImageType::SizeType size = outputRegion.GetSize(); - for(unsigned int i=0;i<size[1]&&!it.IsAtEnd();++i) + for (unsigned int i=0;i<size[1]&&!it.IsAtEnd();++i) { typename InputImageType::IndexType readIndex; readIndex[0] = origin[0]; @@ -181,14 +181,14 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> inputPtr->UpdateOutputData(); InputIteratorType readIt(inputPtr,readRegion); unsigned int count=0; - for(readIt.GoToBegin();!readIt.IsAtEnd()&&!it.IsAtEnd();++readIt,++count) - { - if(count%m_ShrinkFactor==0) + for (readIt.GoToBegin();!readIt.IsAtEnd()&&!it.IsAtEnd();++readIt,++count) { - it.Set(readIt.Get()); - ++it; - } + if (count%m_ShrinkFactor==0) + { + it.Set(readIt.Get()); + ++it; } + } this->UpdateProgress(static_cast<float>(i)/ static_cast<float>(size[1])); } /** @@ -196,9 +196,9 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> * it probably didn't end there) */ if ( !this->GetAbortGenerateData() ) - { + { this->UpdateProgress(1.0); - } + } // Notify end event observers this->InvokeEvent(itk::EndEvent() ); @@ -207,9 +207,9 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> * Now we have to mark the data as up to data. */ if (this->GetOutput(0)) - { - this->GetOutput(0)->DataHasBeenGenerated(); - } + { + this->GetOutput(0)->DataHasBeenGenerated(); + } /** * Release any inputs if marked for release */ @@ -226,7 +226,7 @@ StreamingShrinkImageFilter<TInputImage, TOutputImage> { Superclass::PrintSelf(os,indent); os << indent << "Shrink factor: " << m_ShrinkFactor - << std::endl; + << std::endl; } } // End namespace otb #endif diff --git a/Code/BasicFilters/otbStreamingStatisticsImageFilter.h b/Code/BasicFilters/otbStreamingStatisticsImageFilter.h index eaf41a49ee987090178c60c2c06186a396a570f9..68eccc5a43d20f0dfc79bb913c7d165d5344807a 100644 --- a/Code/BasicFilters/otbStreamingStatisticsImageFilter.h +++ b/Code/BasicFilters/otbStreamingStatisticsImageFilter.h @@ -27,290 +27,303 @@ PURPOSE. See the above copyright notices for more information. #include "itkSimpleDataObjectDecorator.h" #include "otbPersistentFilterStreamingDecorator.h" -namespace otb { - - /** \class PersistentStatisticsImageFilter - * \brief Compute min. max, variance and mean of an image using the output requested region. - * - * This filter persists its temporary data. It means that if you Update it n times on n different - * requested regions, the output statistics will be the statitics of the whole set of n regions. - * - * To reset the temporary data, one should call the Reset() function. - * - * To get the statistics once the regions have been processed via the pipeline, use the Synthetize() method. - * - * \sa PersistentImageFilter - * \ingroup Streamed - * \ingroup Multithreaded - * \ingroup MathematicalStatisticsImageFilters - */ - template<class TInputImage> - class ITK_EXPORT PersistentStatisticsImageFilter : - public PersistentImageFilter<TInputImage, TInputImage> - { - public: - /** Standard Self typedef */ - typedef PersistentStatisticsImageFilter Self; - typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Runtime information support. */ - itkTypeMacro(PersistentStatisticsImageFilter,PersistentImageFilter); - - /** Image related typedefs. */ - typedef TInputImage ImageType; - typedef typename TInputImage::Pointer InputImagePointer; - - typedef typename TInputImage::RegionType RegionType; - typedef typename TInputImage::SizeType SizeType; - typedef typename TInputImage::IndexType IndexType; - typedef typename TInputImage::PixelType PixelType; - - itkStaticConstMacro(InputImageDimension, unsigned int, - TInputImage::ImageDimension); - - /** Image related typedefs. */ - itkStaticConstMacro(ImageDimension, unsigned int, - TInputImage::ImageDimension ); - - /** Type to use for computations. */ - typedef typename itk::NumericTraits<PixelType>::RealType RealType; - - /** Smart Pointer type to a DataObject. */ - typedef typename itk::DataObject::Pointer DataObjectPointer; - - /** Type of DataObjects used for scalar outputs */ - typedef itk::SimpleDataObjectDecorator<RealType> RealObjectType; - typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; - - /** Return the computed Minimum. */ - PixelType GetMinimum() const - { return this->GetMinimumOutput()->Get(); } - PixelObjectType* GetMinimumOutput(); - const PixelObjectType* GetMinimumOutput() const; - - /** Return the computed Maximum. */ - PixelType GetMaximum() const - { return this->GetMaximumOutput()->Get(); } - PixelObjectType* GetMaximumOutput(); - const PixelObjectType* GetMaximumOutput() const; - - /** Return the computed Mean. */ - RealType GetMean() const - { return this->GetMeanOutput()->Get(); } - RealObjectType* GetMeanOutput(); - const RealObjectType* GetMeanOutput() const; - - /** Return the computed Standard Deviation. */ - RealType GetSigma() const - { return this->GetSigmaOutput()->Get(); } - RealObjectType* GetSigmaOutput(); - const RealObjectType* GetSigmaOutput() const; - - /** Return the computed Variance. */ - RealType GetVariance() const - { return this->GetVarianceOutput()->Get(); } - RealObjectType* GetVarianceOutput(); - const RealObjectType* GetVarianceOutput() const; - - /** Return the compute Sum. */ - RealType GetSum() const - { return this->GetSumOutput()->Get(); } - RealObjectType* GetSumOutput(); - const RealObjectType* GetSumOutput() const; - - /** Make a DataObject of the correct type to be used as the specified - * output. */ - virtual DataObjectPointer MakeOutput(unsigned int idx); - - /** Pass the input through unmodified. Do this by Grafting in the - * AllocateOutputs method. - */ - void AllocateOutputs(); - virtual void GenerateOutputInformation(); - void Synthetize(void); - void Reset(void); - - protected: - PersistentStatisticsImageFilter(); - ~PersistentStatisticsImageFilter(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Multi-thread version GenerateData. */ - void ThreadedGenerateData (const RegionType& - outputRegionForThread, - int threadId); - - private: - PersistentStatisticsImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - itk::Array<RealType> m_ThreadSum; - itk::Array<RealType> m_SumOfSquares; - itk::Array<long> m_Count; - itk::Array<PixelType> m_ThreadMin; - itk::Array<PixelType> m_ThreadMax; - }; // end of class PersistentStatisticsImageFilter - - /*===========================================================================*/ - - /** \class StreamingStatisticsImageFilter - * \brief This class streams the whole input image through the PersistentStatisticsImageFilter. - * - * This way, it allows to compute the first order global statistics of this image. It calls the - * Reset() method of the PersistentStatisticsImageFilter before streaming the image and the - * Synthetize() method of the PersistentStatisticsImageFilter after having streamed the image - * to compute the statistics. The accessor on the results are wrapping the accessors of the - * internal PersistentStatisticsImageFilter. - * - * This filter can be used as: - * \code - * typedef otb::StreamingStatisticsImageFilter<ImageType> StatisticsType; - * StatisticsType::Pointer statistics = StatisticsType::New(); - * statistics->SetInput(reader->GetOutput()); - * statistics->Update(); - * std::cout << statistics-> GetMaximum() << std::endl; - * std::cout << statistics-> GetMinimum() << std::endl; - * \endcode - * - * \sa PersistentStatisticsImageFilter - * \sa PersistentImageFilter - * \sa PersistentFilterStreamingDecorator - * \sa StreamingImageVirtualWriter - * \ingroup Streamed - * \ingroup Multithreaded - * \ingroup MathematicalStatisticsImageFilters - */ +namespace otb +{ + +/** \class PersistentStatisticsImageFilter + * \brief Compute min. max, variance and mean of an image using the output requested region. + * + * This filter persists its temporary data. It means that if you Update it n times on n different + * requested regions, the output statistics will be the statitics of the whole set of n regions. + * + * To reset the temporary data, one should call the Reset() function. + * + * To get the statistics once the regions have been processed via the pipeline, use the Synthetize() method. + * + * \sa PersistentImageFilter + * \ingroup Streamed + * \ingroup Multithreaded + * \ingroup MathematicalStatisticsImageFilters + */ +template<class TInputImage> +class ITK_EXPORT PersistentStatisticsImageFilter : + public PersistentImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard Self typedef */ + typedef PersistentStatisticsImageFilter Self; + typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(PersistentStatisticsImageFilter,PersistentImageFilter); + + /** Image related typedefs. */ + typedef TInputImage ImageType; + typedef typename TInputImage::Pointer InputImagePointer; + + typedef typename TInputImage::RegionType RegionType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType PixelType; + + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + + /** Image related typedefs. */ + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension ); + + /** Type to use for computations. */ + typedef typename itk::NumericTraits<PixelType>::RealType RealType; + + /** Smart Pointer type to a DataObject. */ + typedef typename itk::DataObject::Pointer DataObjectPointer; + + /** Type of DataObjects used for scalar outputs */ + typedef itk::SimpleDataObjectDecorator<RealType> RealObjectType; + typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; + + /** Return the computed Minimum. */ + PixelType GetMinimum() const + { + return this->GetMinimumOutput()->Get(); + } + PixelObjectType* GetMinimumOutput(); + const PixelObjectType* GetMinimumOutput() const; + + /** Return the computed Maximum. */ + PixelType GetMaximum() const + { + return this->GetMaximumOutput()->Get(); + } + PixelObjectType* GetMaximumOutput(); + const PixelObjectType* GetMaximumOutput() const; + + /** Return the computed Mean. */ + RealType GetMean() const + { + return this->GetMeanOutput()->Get(); + } + RealObjectType* GetMeanOutput(); + const RealObjectType* GetMeanOutput() const; + + /** Return the computed Standard Deviation. */ + RealType GetSigma() const + { + return this->GetSigmaOutput()->Get(); + } + RealObjectType* GetSigmaOutput(); + const RealObjectType* GetSigmaOutput() const; + + /** Return the computed Variance. */ + RealType GetVariance() const + { + return this->GetVarianceOutput()->Get(); + } + RealObjectType* GetVarianceOutput(); + const RealObjectType* GetVarianceOutput() const; - template<class TInputImage> - class ITK_EXPORT StreamingStatisticsImageFilter : - public PersistentFilterStreamingDecorator< PersistentStatisticsImageFilter<TInputImage> > - { - public: - /** Standard Self typedef */ - typedef StreamingStatisticsImageFilter Self; - typedef PersistentFilterStreamingDecorator + /** Return the compute Sum. */ + RealType GetSum() const + { + return this->GetSumOutput()->Get(); + } + RealObjectType* GetSumOutput(); + const RealObjectType* GetSumOutput() const; + + /** Make a DataObject of the correct type to be used as the specified + * output. */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** Pass the input through unmodified. Do this by Grafting in the + * AllocateOutputs method. + */ + void AllocateOutputs(); + virtual void GenerateOutputInformation(); + void Synthetize(void); + void Reset(void); + +protected: + PersistentStatisticsImageFilter(); + ~PersistentStatisticsImageFilter() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** Multi-thread version GenerateData. */ + void ThreadedGenerateData (const RegionType& + outputRegionForThread, + int threadId); + +private: + PersistentStatisticsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + itk::Array<RealType> m_ThreadSum; + itk::Array<RealType> m_SumOfSquares; + itk::Array<long> m_Count; + itk::Array<PixelType> m_ThreadMin; + itk::Array<PixelType> m_ThreadMax; +}; // end of class PersistentStatisticsImageFilter + +/*===========================================================================*/ + +/** \class StreamingStatisticsImageFilter + * \brief This class streams the whole input image through the PersistentStatisticsImageFilter. + * + * This way, it allows to compute the first order global statistics of this image. It calls the + * Reset() method of the PersistentStatisticsImageFilter before streaming the image and the + * Synthetize() method of the PersistentStatisticsImageFilter after having streamed the image + * to compute the statistics. The accessor on the results are wrapping the accessors of the + * internal PersistentStatisticsImageFilter. + * + * This filter can be used as: + * \code + * typedef otb::StreamingStatisticsImageFilter<ImageType> StatisticsType; + * StatisticsType::Pointer statistics = StatisticsType::New(); + * statistics->SetInput(reader->GetOutput()); + * statistics->Update(); + * std::cout << statistics-> GetMaximum() << std::endl; + * std::cout << statistics-> GetMinimum() << std::endl; + * \endcode + * + * \sa PersistentStatisticsImageFilter + * \sa PersistentImageFilter + * \sa PersistentFilterStreamingDecorator + * \sa StreamingImageVirtualWriter + * \ingroup Streamed + * \ingroup Multithreaded + * \ingroup MathematicalStatisticsImageFilters + */ + +template<class TInputImage> +class ITK_EXPORT StreamingStatisticsImageFilter : + public PersistentFilterStreamingDecorator< PersistentStatisticsImageFilter<TInputImage> > +{ +public: + /** Standard Self typedef */ + typedef StreamingStatisticsImageFilter Self; + typedef PersistentFilterStreamingDecorator < PersistentStatisticsImageFilter<TInputImage> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Type macro */ - itkNewMacro(Self); + /** Type macro */ + itkNewMacro(Self); - /** Creation through object factory macro */ - itkTypeMacro(StreamingStatisticsImageFilter,PersistentFilterStreamingDecorator); + /** Creation through object factory macro */ + itkTypeMacro(StreamingStatisticsImageFilter,PersistentFilterStreamingDecorator); - typedef typename Superclass::FilterType StatFilterType; - typedef typename StatFilterType::PixelType PixelType; - typedef typename StatFilterType::RealType RealType; - typedef TInputImage InputImageType; + typedef typename Superclass::FilterType StatFilterType; + typedef typename StatFilterType::PixelType PixelType; + typedef typename StatFilterType::RealType RealType; + typedef TInputImage InputImageType; - /** Type of DataObjects used for scalar outputs */ - typedef itk::SimpleDataObjectDecorator<RealType> RealObjectType; - typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; + /** Type of DataObjects used for scalar outputs */ + typedef itk::SimpleDataObjectDecorator<RealType> RealObjectType; + typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; - void SetInput(InputImageType * input) + void SetInput(InputImageType * input) { this->GetFilter()->SetInput(input); } - /** Return the computed Minimum. */ - PixelType GetMinimum() const + /** Return the computed Minimum. */ + PixelType GetMinimum() const { return this->GetFilter()->GetMinimumOutput()->Get(); } - PixelObjectType* GetMinimumOutput() + PixelObjectType* GetMinimumOutput() { return this->GetFilter()->MinimumOutput(); } - const PixelObjectType* GetMinimumOutput() const + const PixelObjectType* GetMinimumOutput() const { return this->GetFilter()->MinimumOutput(); } - /** Return the computed Maximum. */ - PixelType GetMaximum() const + /** Return the computed Maximum. */ + PixelType GetMaximum() const { return this->GetFilter()->GetMaximumOutput()->Get(); } - PixelObjectType* GetMaximumOutput() + PixelObjectType* GetMaximumOutput() { return this->GetFilter()->GetMaximumOutput(); } - const PixelObjectType* GetMaximumOutput() const + const PixelObjectType* GetMaximumOutput() const { return this->GetFilter()->GetMaximumOutput(); } - /** Return the computed Mean. */ - RealType GetMean() const + /** Return the computed Mean. */ + RealType GetMean() const { return this->GetFilter()->GetMeanOutput()->Get(); } - RealObjectType* GetMeanOutput() + RealObjectType* GetMeanOutput() { return this->GetFilter()->GetMeanOutput(); } - const RealObjectType* GetMeanOutput() const + const RealObjectType* GetMeanOutput() const { return this->GetFilter()->GetMeanOutput(); } - /** Return the computed Standard Deviation. */ - RealType GetSigma() const + /** Return the computed Standard Deviation. */ + RealType GetSigma() const { return this->GetSigmaOutput()->Get(); } - RealObjectType* GetSigmaOutput() + RealObjectType* GetSigmaOutput() { return this->GetFilter()->GetSigmaOutput(); } - const RealObjectType* GetSigmaOutput() const + const RealObjectType* GetSigmaOutput() const { return this->GetFilter()->GetSigmaOutput(); } - /** Return the computed Variance. */ - RealType GetVariance() const + /** Return the computed Variance. */ + RealType GetVariance() const { return this->GetFilter()->GetVarianceOutput()->Get(); } - RealObjectType* GetVarianceOutput() + RealObjectType* GetVarianceOutput() { return this->GetFilter()->GetVarianceOutput(); } - const RealObjectType* GetVarianceOutput() const + const RealObjectType* GetVarianceOutput() const { return this->GetFilter()->GetVarianceOutput(); } - /** Return the compute Sum. */ - RealType GetSum() const + /** Return the compute Sum. */ + RealType GetSum() const { return this->GetFilter()->GetSumOutput()->Get(); } - RealObjectType* GetSumOutput() + RealObjectType* GetSumOutput() { return this->GetFilter()->GetSumOutput(); } - const RealObjectType* GetSumOutput() const + const RealObjectType* GetSumOutput() const { return this->GetFilter()->GetSumOutput(); } - protected: - /** Constructor */ - StreamingStatisticsImageFilter(){}; - /** Destructor */ - virtual ~StreamingStatisticsImageFilter(){}; +protected: + /** Constructor */ + StreamingStatisticsImageFilter() {}; + /** Destructor */ + virtual ~StreamingStatisticsImageFilter() {}; - private: - StreamingStatisticsImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +private: + StreamingStatisticsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // end namespace otb diff --git a/Code/BasicFilters/otbStreamingStatisticsImageFilter.txx b/Code/BasicFilters/otbStreamingStatisticsImageFilter.txx index 3883bf69fa2229eb11fef2ce342b1e4847814608..93c44e7a87d113d246937fd438049be690b82f38 100644 --- a/Code/BasicFilters/otbStreamingStatisticsImageFilter.txx +++ b/Code/BasicFilters/otbStreamingStatisticsImageFilter.txx @@ -28,321 +28,322 @@ PURPOSE. See the above copyright notices for more information. #include "itkProgressReporter.h" #include "otbMacro.h" -namespace otb { +namespace otb +{ - template<class TInputImage> - PersistentStatisticsImageFilter<TInputImage> - ::PersistentStatisticsImageFilter(): m_ThreadSum(1), m_SumOfSquares(1), m_Count(1), m_ThreadMin(1), m_ThreadMax(1) +template<class TInputImage> +PersistentStatisticsImageFilter<TInputImage> +::PersistentStatisticsImageFilter(): m_ThreadSum(1), m_SumOfSquares(1), m_Count(1), m_ThreadMin(1), m_ThreadMax(1) +{ + // first output is a copy of the image, DataObject created by + // superclass + // + // allocate the data objects for the outputs which are + // just decorators around pixel types + for (int i=1; i < 3; ++i) { - // first output is a copy of the image, DataObject created by - // superclass - // - // allocate the data objects for the outputs which are - // just decorators around pixel types - for (int i=1; i < 3; ++i) - { - typename PixelObjectType::Pointer output + typename PixelObjectType::Pointer output = static_cast<PixelObjectType*>(this->MakeOutput(i).GetPointer()); - this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); - } - // allocate the data objects for the outputs which are - // just decorators around real types - for (int i=3; i < 7; ++i) - { - typename RealObjectType::Pointer output + this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); + } + // allocate the data objects for the outputs which are + // just decorators around real types + for (int i=3; i < 7; ++i) + { + typename RealObjectType::Pointer output = static_cast<RealObjectType*>(this->MakeOutput(i).GetPointer()); - this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); - } + this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); + } - this->GetMinimumOutput()->Set( itk::NumericTraits<PixelType>::max() ); - this->GetMaximumOutput()->Set( itk::NumericTraits<PixelType>::NonpositiveMin() ); - this->GetMeanOutput()->Set( itk::NumericTraits<RealType>::max() ); - this->GetSigmaOutput()->Set( itk::NumericTraits<RealType>::max() ); - this->GetVarianceOutput()->Set( itk::NumericTraits<RealType>::max() ); - this->GetSumOutput()->Set( itk::NumericTraits<RealType>::Zero ); + this->GetMinimumOutput()->Set( itk::NumericTraits<PixelType>::max() ); + this->GetMaximumOutput()->Set( itk::NumericTraits<PixelType>::NonpositiveMin() ); + this->GetMeanOutput()->Set( itk::NumericTraits<RealType>::max() ); + this->GetSigmaOutput()->Set( itk::NumericTraits<RealType>::max() ); + this->GetVarianceOutput()->Set( itk::NumericTraits<RealType>::max() ); + this->GetSumOutput()->Set( itk::NumericTraits<RealType>::Zero ); - this->Reset(); - } + this->Reset(); +} - template<class TInputImage> - typename itk::DataObject::Pointer - PersistentStatisticsImageFilter<TInputImage> - ::MakeOutput(unsigned int output) +template<class TInputImage> +typename itk::DataObject::Pointer +PersistentStatisticsImageFilter<TInputImage> +::MakeOutput(unsigned int output) +{ + switch (output) { - switch (output) - { - case 0: - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - case 1: - return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); - break; - case 2: - return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); - break; - case 3: - case 4: - case 5: - case 6: - return static_cast<itk::DataObject*>(RealObjectType::New().GetPointer()); - break; - default: - // might as well make an image - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - } + case 0: + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; + case 1: + return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); + break; + case 2: + return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); + break; + case 3: + case 4: + case 5: + case 6: + return static_cast<itk::DataObject*>(RealObjectType::New().GetPointer()); + break; + default: + // might as well make an image + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; } +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMinimumOutput() - { - return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMinimumOutput() +{ + return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMinimumOutput() const - { - return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); - } +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMinimumOutput() const +{ + return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMaximumOutput() - { - return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMaximumOutput() +{ + return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMaximumOutput() const - { - return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); - } +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMaximumOutput() const +{ + return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMeanOutput() - { - return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(3)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMeanOutput() +{ + return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(3)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetMeanOutput() const - { - return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(3)); - } +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetMeanOutput() const +{ + return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(3)); +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetSigmaOutput() - { - return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(4)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetSigmaOutput() +{ + return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(4)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetSigmaOutput() const - { - return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(4)); - } +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetSigmaOutput() const +{ + return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(4)); +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetVarianceOutput() - { - return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(5)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetVarianceOutput() +{ + return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(5)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetVarianceOutput() const - { - return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(5)); - } +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetVarianceOutput() const +{ + return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(5)); +} - template<class TInputImage> - typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetSumOutput() - { - return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(6)); - } +template<class TInputImage> +typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetSumOutput() +{ + return static_cast<RealObjectType*>(this->itk::ProcessObject::GetOutput(6)); +} - template<class TInputImage> - const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* - PersistentStatisticsImageFilter<TInputImage> - ::GetSumOutput() const - { - return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(6)); - } - template<class TInputImage> - void - PersistentStatisticsImageFilter<TInputImage> - ::GenerateOutputInformation() +template<class TInputImage> +const typename PersistentStatisticsImageFilter<TInputImage>::RealObjectType* +PersistentStatisticsImageFilter<TInputImage> +::GetSumOutput() const +{ + return static_cast<const RealObjectType*>(this->itk::ProcessObject::GetOutput(6)); +} +template<class TInputImage> +void +PersistentStatisticsImageFilter<TInputImage> +::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); + if ( this->GetInput() ) { - Superclass::GenerateOutputInformation(); - if ( this->GetInput() ) - { - this->GetOutput()->CopyInformation(this->GetInput()); - this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); + this->GetOutput()->CopyInformation(this->GetInput()); + this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); - if(this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) + if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) { this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); } - } - } - template<class TInputImage> - void - PersistentStatisticsImageFilter<TInputImage> - ::AllocateOutputs() - { - // This is commented to prevent the streaming of the whole image for the first stream strip - // It shall not cause any problem because the output image of this filter is not intended to be used. - //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); - //this->GraftOutput( image ); - // Nothing that needs to be allocated for the remaining outputs } +} +template<class TInputImage> +void +PersistentStatisticsImageFilter<TInputImage> +::AllocateOutputs() +{ + // This is commented to prevent the streaming of the whole image for the first stream strip + // It shall not cause any problem because the output image of this filter is not intended to be used. + //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); + //this->GraftOutput( image ); + // Nothing that needs to be allocated for the remaining outputs +} - template<class TInputImage> - void - PersistentStatisticsImageFilter<TInputImage> - ::Synthetize() +template<class TInputImage> +void +PersistentStatisticsImageFilter<TInputImage> +::Synthetize() +{ + int i; + long count; + RealType sumOfSquares; + + int numberOfThreads = this->GetNumberOfThreads(); + + PixelType minimum; + PixelType maximum; + RealType mean; + RealType sigma; + RealType variance; + RealType sum; + + sum = sumOfSquares = itk::NumericTraits<RealType>::Zero; + count = 0; + + // Find the min/max over all threads and accumulate count, sum and + // sum of squares + minimum = itk::NumericTraits<PixelType>::max(); + maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); + for ( i = 0; i < numberOfThreads; i++) { - int i; - long count; - RealType sumOfSquares; - - int numberOfThreads = this->GetNumberOfThreads(); - - PixelType minimum; - PixelType maximum; - RealType mean; - RealType sigma; - RealType variance; - RealType sum; - - sum = sumOfSquares = itk::NumericTraits<RealType>::Zero; - count = 0; - - // Find the min/max over all threads and accumulate count, sum and - // sum of squares - minimum = itk::NumericTraits<PixelType>::max(); - maximum = itk::NumericTraits<PixelType>::NonpositiveMin(); - for( i = 0; i < numberOfThreads; i++) - { - count += m_Count[i]; - sum += m_ThreadSum[i]; - sumOfSquares += m_SumOfSquares[i]; - - if (m_ThreadMin[i] < minimum) + count += m_Count[i]; + sum += m_ThreadSum[i]; + sumOfSquares += m_SumOfSquares[i]; + + if (m_ThreadMin[i] < minimum) { minimum = m_ThreadMin[i]; } - if (m_ThreadMax[i] > maximum) + if (m_ThreadMax[i] > maximum) { maximum = m_ThreadMax[i]; } - } - // compute statistics - mean = sum / static_cast<RealType>(count); - - // unbiased estimate - variance = (sumOfSquares - (sum*sum / static_cast<RealType>(count))) - / (static_cast<RealType>(count) - 1); - sigma = vcl_sqrt(variance); - - // Set the outputs - this->GetMinimumOutput()->Set( minimum ); - this->GetMaximumOutput()->Set( maximum ); - this->GetMeanOutput()->Set( mean ); - this->GetSigmaOutput()->Set( sigma ); - this->GetVarianceOutput()->Set( variance ); - this->GetSumOutput()->Set( sum ); } + // compute statistics + mean = sum / static_cast<RealType>(count); + + // unbiased estimate + variance = (sumOfSquares - (sum*sum / static_cast<RealType>(count))) + / (static_cast<RealType>(count) - 1); + sigma = vcl_sqrt(variance); + + // Set the outputs + this->GetMinimumOutput()->Set( minimum ); + this->GetMaximumOutput()->Set( maximum ); + this->GetMeanOutput()->Set( mean ); + this->GetSigmaOutput()->Set( sigma ); + this->GetVarianceOutput()->Set( variance ); + this->GetSumOutput()->Set( sum ); +} + +template<class TInputImage> +void +PersistentStatisticsImageFilter<TInputImage> +::Reset() +{ + int numberOfThreads = this->GetNumberOfThreads(); + + // Resize the thread temporaries + m_Count.SetSize(numberOfThreads); + m_SumOfSquares.SetSize(numberOfThreads); + m_ThreadSum.SetSize(numberOfThreads); + m_ThreadMin.SetSize(numberOfThreads); + m_ThreadMax.SetSize(numberOfThreads); + + // Initialize the temporaries + m_Count.Fill(itk::NumericTraits<long>::Zero); + m_ThreadSum.Fill(itk::NumericTraits<RealType>::Zero); + m_SumOfSquares.Fill(itk::NumericTraits<RealType>::Zero); + m_ThreadMin.Fill(itk::NumericTraits<PixelType>::max()); + m_ThreadMax.Fill(itk::NumericTraits<PixelType>::NonpositiveMin()); +} - template<class TInputImage> - void - PersistentStatisticsImageFilter<TInputImage> - ::Reset() - { - int numberOfThreads = this->GetNumberOfThreads(); - - // Resize the thread temporaries - m_Count.SetSize(numberOfThreads); - m_SumOfSquares.SetSize(numberOfThreads); - m_ThreadSum.SetSize(numberOfThreads); - m_ThreadMin.SetSize(numberOfThreads); - m_ThreadMax.SetSize(numberOfThreads); - - // Initialize the temporaries - m_Count.Fill(itk::NumericTraits<long>::Zero); - m_ThreadSum.Fill(itk::NumericTraits<RealType>::Zero); - m_SumOfSquares.Fill(itk::NumericTraits<RealType>::Zero); - m_ThreadMin.Fill(itk::NumericTraits<PixelType>::max()); - m_ThreadMax.Fill(itk::NumericTraits<PixelType>::NonpositiveMin()); - } +template<class TInputImage> +void +PersistentStatisticsImageFilter<TInputImage> +::ThreadedGenerateData(const RegionType& outputRegionForThread, + int threadId) +{ + /** + * Grab the input + */ + InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput(0) ); + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + RealType realValue; + PixelType value; - template<class TInputImage> - void - PersistentStatisticsImageFilter<TInputImage> - ::ThreadedGenerateData(const RegionType& outputRegionForThread, - int threadId) + itk::ImageRegionConstIterator<TInputImage> it (inputPtr, outputRegionForThread); + + it.GoToBegin(); + // do the work + while (!it.IsAtEnd()) { - /** - * Grab the input - */ - InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput(0) ); - // support progress methods/callbacks - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - RealType realValue; - PixelType value; - - itk::ImageRegionConstIterator<TInputImage> it (inputPtr, outputRegionForThread); - - it.GoToBegin(); - // do the work - while (!it.IsAtEnd()) - { - value = it.Get(); - realValue = static_cast<RealType>( value ); - if (value < m_ThreadMin[threadId]) + value = it.Get(); + realValue = static_cast<RealType>( value ); + if (value < m_ThreadMin[threadId]) { m_ThreadMin[threadId] = value; } - if (value > m_ThreadMax[threadId]) + if (value > m_ThreadMax[threadId]) { m_ThreadMax[threadId] = value; } - m_ThreadSum[threadId] += realValue; - m_SumOfSquares[threadId] += (realValue * realValue); - m_Count[threadId]++; - ++it; - progress.CompletedPixel(); - } + m_ThreadSum[threadId] += realValue; + m_SumOfSquares[threadId] += (realValue * realValue); + m_Count[threadId]++; + ++it; + progress.CompletedPixel(); } +} template <class TImage> void PersistentStatisticsImageFilter<TImage> @@ -351,9 +352,9 @@ PersistentStatisticsImageFilter<TImage> Superclass::PrintSelf(os,indent); os << indent << "Minimum: " - << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(this->GetMinimum()) << std::endl; + << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(this->GetMinimum()) << std::endl; os << indent << "Maximum: " - << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(this->GetMaximum()) << std::endl; + << static_cast<typename itk::NumericTraits<PixelType>::PrintType>(this->GetMaximum()) << std::endl; os << indent << "Sum: " << this->GetSum() << std::endl; os << indent << "Mean: " << this->GetMean() << std::endl; os << indent << "Sigma: " << this->GetSigma() << std::endl; diff --git a/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.h b/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.h index 8b02faebeb6d299e17396fc2865831109ab72401..093c9938f0f2ae9790e68bc935ba1d1128205d7b 100644 --- a/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.h +++ b/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.h @@ -32,7 +32,8 @@ #include "itkVariableLengthVector.h" -namespace otb { +namespace otb +{ /** \class StreamingStatisticsVectorImageFilter * \brief Compute min. max, covariance of a large image using streaming @@ -52,110 +53,125 @@ namespace otb { */ template<class TInputImage> class ITK_EXPORT PersistentStatisticsVectorImageFilter : - public PersistentImageFilter<TInputImage, TInputImage> + public PersistentImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard Self typedef */ + typedef PersistentStatisticsVectorImageFilter Self; + typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(PersistentStatisticsVectorImageFilter,PersistentImageFilter); + + /** Image related typedefs. */ + typedef TInputImage ImageType; + typedef typename TInputImage::Pointer InputImagePointer; + typedef typename TInputImage::RegionType RegionType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::PixelType PixelType; + typedef typename TInputImage::InternalPixelType InternalPixelType; + + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + + /** Image related typedefs. */ + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension ); + + /** Type to use for computations. */ + typedef typename itk::NumericTraits<InternalPixelType>::RealType RealType; + typedef itk::VariableLengthVector<RealType> RealPixelType; + + /** Smart Pointer type to a DataObject. */ + typedef typename itk::DataObject::Pointer DataObjectPointer; + + /** Type of DataObjects used for scalar outputs */ + typedef typename itk::VariableSizeMatrix<RealType> MatrixType; + typedef typename std::vector<MatrixType> ArrayMatrixType; + typedef typename itk::Array<long> ArrayLongPixelType; + typedef typename std::vector<RealPixelType> ArrayRealPixelType; + typedef typename std::vector<PixelType> ArrayPixelType; + typedef itk::SimpleDataObjectDecorator<RealPixelType> RealPixelObjectType; + typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; + typedef itk::SimpleDataObjectDecorator<MatrixType> MatrixObjectType; + + + /** Return the computed Minimum. */ + PixelType GetMinimum() const + { + return this->GetMinimumOutput()->Get(); + }; + PixelObjectType* GetMinimumOutput(); + const PixelObjectType* GetMinimumOutput() const; + + /** Return the computed Maximum. */ + PixelType GetMaximum() const + { + return this->GetMaximumOutput()->Get(); + }; + PixelObjectType* GetMaximumOutput(); + const PixelObjectType* GetMaximumOutput() const; + + /** Return the computed Mean. */ + RealPixelType GetMean() const + { + return this->GetMeanOutput()->Get(); + }; + RealPixelObjectType* GetMeanOutput(); + const RealPixelObjectType* GetMeanOutput() const; + + /** Return the compute Sum. */ + RealPixelType GetSum() const { - public: - /** Standard Self typedef */ - typedef PersistentStatisticsVectorImageFilter Self; - typedef PersistentImageFilter<TInputImage,TInputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Runtime information support. */ - itkTypeMacro(PersistentStatisticsVectorImageFilter,PersistentImageFilter); - - /** Image related typedefs. */ - typedef TInputImage ImageType; - typedef typename TInputImage::Pointer InputImagePointer; - typedef typename TInputImage::RegionType RegionType; - typedef typename TInputImage::SizeType SizeType; - typedef typename TInputImage::IndexType IndexType; - typedef typename TInputImage::PixelType PixelType; - typedef typename TInputImage::InternalPixelType InternalPixelType; - - itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); - - /** Image related typedefs. */ - itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension ); - - /** Type to use for computations. */ - typedef typename itk::NumericTraits<InternalPixelType>::RealType RealType; - typedef itk::VariableLengthVector<RealType> RealPixelType; - - /** Smart Pointer type to a DataObject. */ - typedef typename itk::DataObject::Pointer DataObjectPointer; - - /** Type of DataObjects used for scalar outputs */ - typedef typename itk::VariableSizeMatrix<RealType> MatrixType; - typedef typename std::vector<MatrixType> ArrayMatrixType; - typedef typename itk::Array<long> ArrayLongPixelType; - typedef typename std::vector<RealPixelType> ArrayRealPixelType; - typedef typename std::vector<PixelType> ArrayPixelType; - typedef itk::SimpleDataObjectDecorator<RealPixelType> RealPixelObjectType; - typedef itk::SimpleDataObjectDecorator<PixelType> PixelObjectType; - typedef itk::SimpleDataObjectDecorator<MatrixType> MatrixObjectType; - - - /** Return the computed Minimum. */ - PixelType GetMinimum() const { return this->GetMinimumOutput()->Get(); }; - PixelObjectType* GetMinimumOutput(); - const PixelObjectType* GetMinimumOutput() const; - - /** Return the computed Maximum. */ - PixelType GetMaximum() const { return this->GetMaximumOutput()->Get(); }; - PixelObjectType* GetMaximumOutput(); - const PixelObjectType* GetMaximumOutput() const; - - /** Return the computed Mean. */ - RealPixelType GetMean() const { return this->GetMeanOutput()->Get(); }; - RealPixelObjectType* GetMeanOutput(); - const RealPixelObjectType* GetMeanOutput() const; - - /** Return the compute Sum. */ - RealPixelType GetSum() const { return this->GetSumOutput()->Get(); }; - RealPixelObjectType* GetSumOutput(); - const RealPixelObjectType* GetSumOutput() const; - - /** Return the computed Covariance. */ - MatrixType GetCovariance() const { return this->GetCovarianceOutput()->Get(); }; - MatrixObjectType* GetCovarianceOutput(); - const MatrixObjectType* GetCovarianceOutput() const; - - - /** Make a DataObject of the correct type to be used as the specified - * output. - */ - virtual DataObjectPointer MakeOutput(unsigned int idx); - - /** Pass the input through unmodified. Do this by Grafting in the - * AllocateOutputs method. - */ - virtual void AllocateOutputs(); - virtual void GenerateOutputInformation(); - virtual void Synthetize(void); - virtual void Reset(void); - - protected: - PersistentStatisticsVectorImageFilter(); - virtual ~PersistentStatisticsVectorImageFilter(){}; - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Multi-thread version GenerateData. */ - void ThreadedGenerateData (const RegionType& outputRegionForThread,int threadId); - - private: - PersistentStatisticsVectorImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - ArrayRealPixelType m_ThreadSum; - ArrayLongPixelType m_Count; - ArrayPixelType m_ThreadMin; - ArrayPixelType m_ThreadMax; - ArrayMatrixType m_XX; - - }; // end of class PersistentStatisticsVectorImageFilter + return this->GetSumOutput()->Get(); + }; + RealPixelObjectType* GetSumOutput(); + const RealPixelObjectType* GetSumOutput() const; + + /** Return the computed Covariance. */ + MatrixType GetCovariance() const + { + return this->GetCovarianceOutput()->Get(); + }; + MatrixObjectType* GetCovarianceOutput(); + const MatrixObjectType* GetCovarianceOutput() const; + + + /** Make a DataObject of the correct type to be used as the specified + * output. + */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** Pass the input through unmodified. Do this by Grafting in the + * AllocateOutputs method. + */ + virtual void AllocateOutputs(); + virtual void GenerateOutputInformation(); + virtual void Synthetize(void); + virtual void Reset(void); + +protected: + PersistentStatisticsVectorImageFilter(); + virtual ~PersistentStatisticsVectorImageFilter() {}; + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Multi-thread version GenerateData. */ + void ThreadedGenerateData (const RegionType& outputRegionForThread,int threadId); + +private: + PersistentStatisticsVectorImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + ArrayRealPixelType m_ThreadSum; + ArrayLongPixelType m_Count; + ArrayPixelType m_ThreadMin; + ArrayPixelType m_ThreadMax; + ArrayMatrixType m_XX; + +}; // end of class PersistentStatisticsVectorImageFilter /**===========================================================================*/ @@ -179,13 +195,13 @@ class ITK_EXPORT PersistentStatisticsVectorImageFilter : template<class TInputImage> class ITK_EXPORT StreamingStatisticsVectorImageFilter : - public PersistentFilterStreamingDecorator< PersistentStatisticsVectorImageFilter<TInputImage> > + public PersistentFilterStreamingDecorator< PersistentStatisticsVectorImageFilter<TInputImage> > { public: /** Standard Self typedef */ typedef StreamingStatisticsVectorImageFilter Self; typedef PersistentFilterStreamingDecorator - < PersistentStatisticsVectorImageFilter<TInputImage> > Superclass; + < PersistentStatisticsVectorImageFilter<TInputImage> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -216,46 +232,91 @@ public: typedef typename StatFilterType::MatrixObjectType MatrixObjectType; void SetInput(TInputImage * input) - { - this->GetFilter()->SetInput(input); - } + { + this->GetFilter()->SetInput(input); + } TInputImage * GetInput() - { - return this->GetFilter()->GetInput(); - } + { + return this->GetFilter()->GetInput(); + } /** Return the computed Minimum. */ - PixelType GetMinimum() const { return this->GetFilter()->GetMinimumOutput()->Get(); }; - PixelObjectType* GetMinimumOutput(){ return this->GetFilter()->MinimumOutput(); }; - const PixelObjectType* GetMinimumOutput() const{ return this->GetFilter()->MinimumOutput(); }; + PixelType GetMinimum() const + { + return this->GetFilter()->GetMinimumOutput()->Get(); + }; + PixelObjectType* GetMinimumOutput() + { + return this->GetFilter()->MinimumOutput(); + }; + const PixelObjectType* GetMinimumOutput() const + { + return this->GetFilter()->MinimumOutput(); + }; /** Return the computed Maximum. */ - PixelType GetMaximum() const { return this->GetFilter()->GetMaximumOutput()->Get(); }; - PixelObjectType* GetMaximumOutput(){ return this->GetFilter()->MaximumOutput(); }; - const PixelObjectType* GetMaximumOutput() const{ return this->GetFilter()->MaximumOutput(); }; + PixelType GetMaximum() const + { + return this->GetFilter()->GetMaximumOutput()->Get(); + }; + PixelObjectType* GetMaximumOutput() + { + return this->GetFilter()->MaximumOutput(); + }; + const PixelObjectType* GetMaximumOutput() const + { + return this->GetFilter()->MaximumOutput(); + }; /** Return the computed Mean. */ - RealPixelType GetMean() const { return this->GetFilter()->GetMeanOutput()->Get(); }; - RealPixelObjectType* GetMeanOutput(){ return this->GetFilter()->GetMeanOutput(); }; - const RealPixelObjectType* GetMeanOutput() const {return this->GetFilter()->GetMeanOutput();}; + RealPixelType GetMean() const + { + return this->GetFilter()->GetMeanOutput()->Get(); + }; + RealPixelObjectType* GetMeanOutput() + { + return this->GetFilter()->GetMeanOutput(); + }; + const RealPixelObjectType* GetMeanOutput() const + { + return this->GetFilter()->GetMeanOutput(); + }; /** Return the compute Sum. */ - RealPixelType GetSum() const { return this->GetFilter()->GetSumOutput()->Get(); }; - RealPixelObjectType* GetSumOutput(){ return this->GetFilter()->GetSumOutput();}; - const RealPixelObjectType* GetSumOutput() const {return this->GetFilter()->GetSumOutput();}; + RealPixelType GetSum() const + { + return this->GetFilter()->GetSumOutput()->Get(); + }; + RealPixelObjectType* GetSumOutput() + { + return this->GetFilter()->GetSumOutput(); + }; + const RealPixelObjectType* GetSumOutput() const + { + return this->GetFilter()->GetSumOutput(); + }; /** Return the computed Covariance. */ - MatrixType GetCovariance() const { return this->GetFilter()->GetCovarianceOutput()->Get(); }; - MatrixObjectType* GetCovarianceOutput(){ return this->GetFilter()->GetCovarianceOutput(); }; - const MatrixObjectType* GetCovarianceOutput() const { return this->GetFilter()->GetCovarianceOutput(); }; + MatrixType GetCovariance() const + { + return this->GetFilter()->GetCovarianceOutput()->Get(); + }; + MatrixObjectType* GetCovarianceOutput() + { + return this->GetFilter()->GetCovarianceOutput(); + }; + const MatrixObjectType* GetCovarianceOutput() const + { + return this->GetFilter()->GetCovarianceOutput(); + }; - protected: +protected: /** Constructor */ - StreamingStatisticsVectorImageFilter(){}; + StreamingStatisticsVectorImageFilter() {}; /** Destructor */ - virtual ~StreamingStatisticsVectorImageFilter(){}; + virtual ~StreamingStatisticsVectorImageFilter() {}; private: StreamingStatisticsVectorImageFilter(const Self&); //purposely not implemented diff --git a/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.txx b/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.txx index 4aa308ef3ca307b266b1e47080c8843d2375a75e..045630b3445a90c9e40fa735d4f04a7998487892 100644 --- a/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.txx +++ b/Code/BasicFilters/otbStreamingStatisticsVectorImageFilter.txx @@ -28,445 +28,446 @@ PURPOSE. See the above copyright notices for more information. #include "itkProgressReporter.h" #include "otbMacro.h" -namespace otb { - - template<class TInputImage> - PersistentStatisticsVectorImageFilter<TInputImage> - ::PersistentStatisticsVectorImageFilter() - { - // first output is a copy of the image, DataObject created by - // superclass - // - // allocate the data objects for the outputs which are - // just decorators around pixel types - - for (int i=1; i < 3; ++i) - { - typename PixelObjectType::Pointer output = static_cast<PixelObjectType*>(this->MakeOutput(i).GetPointer()); - this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); - } - - // allocate the data objects for the outputs which are - // just decorators around real types - - for (int i=3; i < 5; ++i) - { - typename RealPixelObjectType::Pointer output = static_cast<RealPixelObjectType*>(this->MakeOutput(i).GetPointer()); - this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); - } - - // allocate the data objects for the outputs which are - // just decorators around matrix types - typename MatrixObjectType::Pointer output = static_cast<MatrixObjectType*>(this->MakeOutput(5).GetPointer()); - this->itk::ProcessObject::SetNthOutput(5, output.GetPointer()); - } - - template<class TInputImage> - itk::DataObject::Pointer - PersistentStatisticsVectorImageFilter<TInputImage> - ::MakeOutput(unsigned int output) - { - switch (output) - { - case 0: - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - case 1: - case 2: - return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); - break; - case 3: - case 4: - return static_cast<itk::DataObject*>(RealPixelObjectType::New().GetPointer()); - break; - case 5: - return static_cast<itk::DataObject*>(MatrixObjectType::New().GetPointer()); - break; - default: - // might as well make an image - return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); - break; - } - - } - - - template<class TInputImage> - typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMinimumOutput() +namespace otb +{ + +template<class TInputImage> +PersistentStatisticsVectorImageFilter<TInputImage> +::PersistentStatisticsVectorImageFilter() +{ + // first output is a copy of the image, DataObject created by + // superclass + // + // allocate the data objects for the outputs which are + // just decorators around pixel types + + for (int i=1; i < 3; ++i) { - return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); + typename PixelObjectType::Pointer output = static_cast<PixelObjectType*>(this->MakeOutput(i).GetPointer()); + this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); } - template<class TInputImage> - const typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMinimumOutput() const - { - return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); - } + // allocate the data objects for the outputs which are + // just decorators around real types - - template<class TInputImage> - typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMaximumOutput() + for (int i=3; i < 5; ++i) { - return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); + typename RealPixelObjectType::Pointer output = static_cast<RealPixelObjectType*>(this->MakeOutput(i).GetPointer()); + this->itk::ProcessObject::SetNthOutput(i, output.GetPointer()); } - template<class TInputImage> - const typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMaximumOutput() const + // allocate the data objects for the outputs which are + // just decorators around matrix types + typename MatrixObjectType::Pointer output = static_cast<MatrixObjectType*>(this->MakeOutput(5).GetPointer()); + this->itk::ProcessObject::SetNthOutput(5, output.GetPointer()); +} + +template<class TInputImage> +itk::DataObject::Pointer +PersistentStatisticsVectorImageFilter<TInputImage> +::MakeOutput(unsigned int output) +{ + switch (output) { - return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); + case 0: + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; + case 1: + case 2: + return static_cast<itk::DataObject*>(PixelObjectType::New().GetPointer()); + break; + case 3: + case 4: + return static_cast<itk::DataObject*>(RealPixelObjectType::New().GetPointer()); + break; + case 5: + return static_cast<itk::DataObject*>(MatrixObjectType::New().GetPointer()); + break; + default: + // might as well make an image + return static_cast<itk::DataObject*>(TInputImage::New().GetPointer()); + break; } - - template<class TInputImage> - typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMeanOutput() +} + + +template<class TInputImage> +typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMinimumOutput() +{ + return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); +} + +template<class TInputImage> +const typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMinimumOutput() const +{ + return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(1)); +} + + +template<class TInputImage> +typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMaximumOutput() +{ + return static_cast<PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); +} + +template<class TInputImage> +const typename PersistentStatisticsVectorImageFilter<TInputImage>::PixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMaximumOutput() const +{ + return static_cast<const PixelObjectType*>(this->itk::ProcessObject::GetOutput(2)); +} + + +template<class TInputImage> +typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMeanOutput() +{ + return static_cast<RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(3)); +} + +template<class TInputImage> +const typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetMeanOutput() const +{ + return static_cast<const RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(3)); +} + +template<class TInputImage> +typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetSumOutput() +{ + return static_cast<RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(4)); +} + +template<class TInputImage> +const typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetSumOutput() const +{ + return static_cast<const RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(4)); +} + +template<class TInputImage> +typename PersistentStatisticsVectorImageFilter<TInputImage>::MatrixObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetCovarianceOutput() +{ + return static_cast<MatrixObjectType*>(this->itk::ProcessObject::GetOutput(5)); +} + +template<class TInputImage> +const typename PersistentStatisticsVectorImageFilter<TInputImage>::MatrixObjectType* +PersistentStatisticsVectorImageFilter<TInputImage> +::GetCovarianceOutput() const +{ + return static_cast<const MatrixObjectType*>(this->itk::ProcessObject::GetOutput(5)); +} + + +template<class TInputImage> +void +PersistentStatisticsVectorImageFilter<TInputImage> +::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); + if ( this->GetInput() ) { - return static_cast<RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(3)); - } - - template<class TInputImage> - const typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetMeanOutput() const - { - return static_cast<const RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(3)); - } - - template<class TInputImage> - typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetSumOutput() - { - return static_cast<RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(4)); - } + this->GetOutput()->CopyInformation(this->GetInput()); + this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); - template<class TInputImage> - const typename PersistentStatisticsVectorImageFilter<TInputImage>::RealPixelObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetSumOutput() const - { - return static_cast<const RealPixelObjectType*>(this->itk::ProcessObject::GetOutput(4)); - } - - template<class TInputImage> - typename PersistentStatisticsVectorImageFilter<TInputImage>::MatrixObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetCovarianceOutput() - { - return static_cast<MatrixObjectType*>(this->itk::ProcessObject::GetOutput(5)); - } - - template<class TInputImage> - const typename PersistentStatisticsVectorImageFilter<TInputImage>::MatrixObjectType* - PersistentStatisticsVectorImageFilter<TInputImage> - ::GetCovarianceOutput() const - { - return static_cast<const MatrixObjectType*>(this->itk::ProcessObject::GetOutput(5)); - } - - - template<class TInputImage> - void - PersistentStatisticsVectorImageFilter<TInputImage> - ::GenerateOutputInformation() - { - Superclass::GenerateOutputInformation(); - if ( this->GetInput() ) - { - this->GetOutput()->CopyInformation(this->GetInput()); - this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); - - if(this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) + if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels()==0) { this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); } - } - } - - template<class TInputImage> - void - PersistentStatisticsVectorImageFilter<TInputImage> - ::AllocateOutputs() - { - // This is commented to prevent the streaming of the whole image for the first stream strip - // It shall not cause any problem because the output image of this filter is not intended to be used. - //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); - //this->GraftOutput( image ); - // Nothing that needs to be allocated for the remaining outputs - } - - template<class TInputImage> - void - PersistentStatisticsVectorImageFilter<TInputImage> - ::Reset() - { - TInputImage * inputPtr = const_cast<TInputImage * >(this->GetInput()); - inputPtr->UpdateOutputInformation(); - - unsigned int numberOfThreads = this->GetNumberOfThreads(); - unsigned int numberOfComponent = inputPtr->GetNumberOfComponentsPerPixel(); - - // Variable Initialisation - PixelType tempPixel; - tempPixel.SetSize(numberOfComponent); - tempPixel.Fill(itk::NumericTraits<InternalPixelType>::Zero); - this->GetMaximumOutput()->Set( tempPixel ); - - tempPixel.Fill(itk::NumericTraits<InternalPixelType>::max()); - this->GetMinimumOutput()->Set( tempPixel ); - - RealPixelType tempRealPixel; - tempRealPixel.SetSize(numberOfComponent); - tempRealPixel.Fill(itk::NumericTraits<RealType>::max()); - this->GetMeanOutput()->Set( tempRealPixel ); - - tempRealPixel.Fill(itk::NumericTraits<RealType>::Zero); - this->GetMeanOutput()->Set( tempRealPixel ); - - MatrixType tempMatrix; - tempMatrix.SetSize(numberOfComponent, numberOfComponent); - tempMatrix.Fill(itk::NumericTraits<RealType>::Zero); - - // Initialize the tempories - m_Count.SetSize(numberOfThreads); - m_Count.Fill( itk::NumericTraits<long>::Zero ); - - PixelType tempTemporiesPixel; - tempTemporiesPixel.SetSize(numberOfComponent); - tempTemporiesPixel.Fill(itk::NumericTraits<InternalPixelType>::max()); - m_ThreadMin = ArrayPixelType(numberOfThreads, tempTemporiesPixel); - - tempTemporiesPixel.Fill(itk::NumericTraits<InternalPixelType>::Zero); - m_ThreadMax = ArrayPixelType(numberOfThreads, tempTemporiesPixel); - - RealPixelType tempTemporiesRealPixel; - tempTemporiesRealPixel.SetSize(numberOfComponent); - tempTemporiesRealPixel.Fill(itk::NumericTraits<RealType>::Zero); - m_ThreadSum = ArrayRealPixelType(numberOfThreads, tempTemporiesRealPixel); - - m_XX = ArrayMatrixType(numberOfThreads, tempMatrix); } - - template<class TInputImage> - void - PersistentStatisticsVectorImageFilter<TInputImage> - ::Synthetize() +} + +template<class TInputImage> +void +PersistentStatisticsVectorImageFilter<TInputImage> +::AllocateOutputs() +{ + // This is commented to prevent the streaming of the whole image for the first stream strip + // It shall not cause any problem because the output image of this filter is not intended to be used. + //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); + //this->GraftOutput( image ); + // Nothing that needs to be allocated for the remaining outputs +} + +template<class TInputImage> +void +PersistentStatisticsVectorImageFilter<TInputImage> +::Reset() +{ + TInputImage * inputPtr = const_cast<TInputImage * >(this->GetInput()); + inputPtr->UpdateOutputInformation(); + + unsigned int numberOfThreads = this->GetNumberOfThreads(); + unsigned int numberOfComponent = inputPtr->GetNumberOfComponentsPerPixel(); + + // Variable Initialisation + PixelType tempPixel; + tempPixel.SetSize(numberOfComponent); + tempPixel.Fill(itk::NumericTraits<InternalPixelType>::Zero); + this->GetMaximumOutput()->Set( tempPixel ); + + tempPixel.Fill(itk::NumericTraits<InternalPixelType>::max()); + this->GetMinimumOutput()->Set( tempPixel ); + + RealPixelType tempRealPixel; + tempRealPixel.SetSize(numberOfComponent); + tempRealPixel.Fill(itk::NumericTraits<RealType>::max()); + this->GetMeanOutput()->Set( tempRealPixel ); + + tempRealPixel.Fill(itk::NumericTraits<RealType>::Zero); + this->GetMeanOutput()->Set( tempRealPixel ); + + MatrixType tempMatrix; + tempMatrix.SetSize(numberOfComponent, numberOfComponent); + tempMatrix.Fill(itk::NumericTraits<RealType>::Zero); + + // Initialize the tempories + m_Count.SetSize(numberOfThreads); + m_Count.Fill( itk::NumericTraits<long>::Zero ); + + PixelType tempTemporiesPixel; + tempTemporiesPixel.SetSize(numberOfComponent); + tempTemporiesPixel.Fill(itk::NumericTraits<InternalPixelType>::max()); + m_ThreadMin = ArrayPixelType(numberOfThreads, tempTemporiesPixel); + + tempTemporiesPixel.Fill(itk::NumericTraits<InternalPixelType>::Zero); + m_ThreadMax = ArrayPixelType(numberOfThreads, tempTemporiesPixel); + + RealPixelType tempTemporiesRealPixel; + tempTemporiesRealPixel.SetSize(numberOfComponent); + tempTemporiesRealPixel.Fill(itk::NumericTraits<RealType>::Zero); + m_ThreadSum = ArrayRealPixelType(numberOfThreads, tempTemporiesRealPixel); + + m_XX = ArrayMatrixType(numberOfThreads, tempMatrix); +} + +template<class TInputImage> +void +PersistentStatisticsVectorImageFilter<TInputImage> +::Synthetize() +{ + int i; + long count; + + int numberOfThreads = this->GetNumberOfThreads(); + unsigned int numberOfComponent = this->GetInput()->GetNumberOfComponentsPerPixel(); + + PixelType minimumVector; + minimumVector.SetSize( numberOfComponent ); + minimumVector.Fill(itk::NumericTraits<InternalPixelType>::max()); + + PixelType maximumVector; + maximumVector.SetSize( numberOfComponent ); + maximumVector.Fill(itk::NumericTraits<InternalPixelType>::NonpositiveMin()); + + RealPixelType sumVector; + sumVector.SetSize( numberOfComponent ); + sumVector.Fill(itk::NumericTraits<RealType>::Zero); + + RealPixelType meanVector; + meanVector.SetSize( numberOfComponent ); + MatrixType crossedMatrix; + crossedMatrix.SetSize(numberOfComponent,numberOfComponent); + crossedMatrix.Fill(itk::NumericTraits<RealType>::Zero); + count = 0; + + // Find the min/max over all threads and accumulate count, sum and + // sum of squares + for ( i = 0; i < numberOfThreads; i++) { - int i; - long count; - - int numberOfThreads = this->GetNumberOfThreads(); - unsigned int numberOfComponent = this->GetInput()->GetNumberOfComponentsPerPixel(); - - PixelType minimumVector; - minimumVector.SetSize( numberOfComponent ); - minimumVector.Fill(itk::NumericTraits<InternalPixelType>::max()); - - PixelType maximumVector; - maximumVector.SetSize( numberOfComponent ); - maximumVector.Fill(itk::NumericTraits<InternalPixelType>::NonpositiveMin()); - - RealPixelType sumVector; - sumVector.SetSize( numberOfComponent ); - sumVector.Fill(itk::NumericTraits<RealType>::Zero); - - RealPixelType meanVector; - meanVector.SetSize( numberOfComponent ); - MatrixType crossedMatrix; - crossedMatrix.SetSize(numberOfComponent,numberOfComponent); - crossedMatrix.Fill(itk::NumericTraits<RealType>::Zero); - count = 0; - - // Find the min/max over all threads and accumulate count, sum and - // sum of squares - for( i = 0; i < numberOfThreads; i++) - { - count += m_Count[i]; - /** TODO - * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) - * crossedMatrix += m_XX[i]; - **/ - if( (m_XX[i].Rows() != crossedMatrix.Rows()) || (m_XX[i].Cols() != crossedMatrix.Cols())) + count += m_Count[i]; + /** TODO + * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) + * crossedMatrix += m_XX[i]; + **/ + if ( (m_XX[i].Rows() != crossedMatrix.Rows()) || (m_XX[i].Cols() != crossedMatrix.Cols())) { itkExceptionMacro( << "Matrix with size (" << m_XX[i].Rows() << "," << - m_XX[i].Cols() << ") cannot be subtracted from matrix with size (" << - crossedMatrix.Rows() << "," << crossedMatrix.Cols() ); + m_XX[i].Cols() << ") cannot be subtracted from matrix with size (" << + crossedMatrix.Rows() << "," << crossedMatrix.Cols() ); } - for( unsigned int r=0; r<m_XX[i].Rows(); r++) + for ( unsigned int r=0; r<m_XX[i].Rows(); r++) { - for( unsigned int c=0; c<m_XX[i].Cols(); c++ ) - { - crossedMatrix(r,c) += m_XX[i](r,c); - } + for ( unsigned int c=0; c<m_XX[i].Cols(); c++ ) + { + crossedMatrix(r,c) += m_XX[i](r,c); + } } - //**** END TODO **** + //**** END TODO **** - for (unsigned int j=0; j<numberOfComponent; j++) + for (unsigned int j=0; j<numberOfComponent; j++) { sumVector[j] += m_ThreadSum[i][j]; if (m_ThreadMin[i][j] < minimumVector[j]) - { - minimumVector[j] = m_ThreadMin[i][j]; - } - if (m_ThreadMax[i][j] > maximumVector[j]) - { - maximumVector[j] = m_ThreadMax[i][j]; - } - } - } // end for( i = 0; i < numberOfThreads; i++) - - for (unsigned int j=0; j<numberOfComponent; j++) { - // compute statistics - meanVector[j] = sumVector[j] / static_cast<RealType>(count); + minimumVector[j] = m_ThreadMin[i][j]; } - - // Compute Matrix Covariance - MatrixType pixelSumMatrix; - pixelSumMatrix.SetSize(static_cast<unsigned int>(numberOfComponent), 1); - pixelSumMatrix.Fill(itk::NumericTraits<RealType>::Zero); - for( unsigned int j = 0; j < numberOfComponent; j++) + if (m_ThreadMax[i][j] > maximumVector[j]) { - pixelSumMatrix(j, 0) = sumVector[j]; + maximumVector[j] = m_ThreadMax[i][j]; } + } + } // end for( i = 0; i < numberOfThreads; i++) - MatrixType covMatrix, covMatrixTemp, tempTranspose; - covMatrix.SetSize(static_cast<unsigned int>(numberOfComponent), static_cast<unsigned int>(numberOfComponent)); - covMatrixTemp.SetSize(static_cast<unsigned int>(numberOfComponent), static_cast<unsigned int>(numberOfComponent)); - tempTranspose.SetSize(1, static_cast<unsigned int>(numberOfComponent)); + for (unsigned int j=0; j<numberOfComponent; j++) + { + // compute statistics + meanVector[j] = sumVector[j] / static_cast<RealType>(count); + } - covMatrix = crossedMatrix/static_cast<RealType>(count); - pixelSumMatrix/=static_cast<RealType>(count); - tempTranspose = pixelSumMatrix.GetTranspose(); - covMatrixTemp = pixelSumMatrix*tempTranspose; - /** TODO - * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) - *covMatrix -= covMatrixTemp; - **/ - if( (covMatrix.Rows() != covMatrixTemp.Rows()) || (covMatrix.Cols() != covMatrixTemp.Cols())) - { - itkExceptionMacro( << "Matrix with size (" << covMatrix.Rows() << "," << - covMatrix.Cols() << ") cannot be subtracted from matrix with size (" << - covMatrixTemp.Rows() << "," << covMatrixTemp.Cols() ); - } + // Compute Matrix Covariance + MatrixType pixelSumMatrix; + pixelSumMatrix.SetSize(static_cast<unsigned int>(numberOfComponent), 1); + pixelSumMatrix.Fill(itk::NumericTraits<RealType>::Zero); + for ( unsigned int j = 0; j < numberOfComponent; j++) + { + pixelSumMatrix(j, 0) = sumVector[j]; + } - for( unsigned int r=0; r<covMatrix.Rows(); r++) - { - for( unsigned int c=0; c<covMatrix.Cols(); c++ ) + MatrixType covMatrix, covMatrixTemp, tempTranspose; + covMatrix.SetSize(static_cast<unsigned int>(numberOfComponent), static_cast<unsigned int>(numberOfComponent)); + covMatrixTemp.SetSize(static_cast<unsigned int>(numberOfComponent), static_cast<unsigned int>(numberOfComponent)); + tempTranspose.SetSize(1, static_cast<unsigned int>(numberOfComponent)); + + covMatrix = crossedMatrix/static_cast<RealType>(count); + pixelSumMatrix/=static_cast<RealType>(count); + tempTranspose = pixelSumMatrix.GetTranspose(); + covMatrixTemp = pixelSumMatrix*tempTranspose; + /** TODO + * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) + *covMatrix -= covMatrixTemp; + **/ + if ( (covMatrix.Rows() != covMatrixTemp.Rows()) || (covMatrix.Cols() != covMatrixTemp.Cols())) + { + itkExceptionMacro( << "Matrix with size (" << covMatrix.Rows() << "," << + covMatrix.Cols() << ") cannot be subtracted from matrix with size (" << + covMatrixTemp.Rows() << "," << covMatrixTemp.Cols() ); + } + + for ( unsigned int r=0; r<covMatrix.Rows(); r++) + { + for ( unsigned int c=0; c<covMatrix.Cols(); c++ ) { covMatrix(r,c) -= covMatrixTemp(r,c); } - } - //**** END TODO ****/ - - // Set the outputs - this->GetMinimumOutput()->Set( minimumVector ); - this->GetMaximumOutput()->Set( maximumVector ); - this->GetMeanOutput()->Set( meanVector ); - this->GetSumOutput()->Set( sumVector); - this->GetCovarianceOutput()->Set( covMatrix ); } - - template<class TInputImage> - void - PersistentStatisticsVectorImageFilter<TInputImage> - ::ThreadedGenerateData(const RegionType& outputRegionForThread, int threadId) + //**** END TODO ****/ + + // Set the outputs + this->GetMinimumOutput()->Set( minimumVector ); + this->GetMaximumOutput()->Set( maximumVector ); + this->GetMeanOutput()->Set( meanVector ); + this->GetSumOutput()->Set( sumVector); + this->GetCovarianceOutput()->Set( covMatrix ); +} + +template<class TInputImage> +void +PersistentStatisticsVectorImageFilter<TInputImage> +::ThreadedGenerateData(const RegionType& outputRegionForThread, int threadId) +{ + /** + * Grab the input + */ + InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); + // support progress methods/callbacks + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + + MatrixType pixelVector, pixelTransposeVector, pixelSumVector, tempMatrix; + + pixelVector.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), 1); + pixelVector.Fill(itk::NumericTraits<RealType>::Zero); + pixelTransposeVector.SetSize(1, this->GetInput()->GetNumberOfComponentsPerPixel()); + pixelTransposeVector.Fill(itk::NumericTraits<RealType>::Zero); + pixelSumVector.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), this->GetInput()->GetNumberOfComponentsPerPixel()); + pixelSumVector.Fill(itk::NumericTraits<RealType>::Zero); + tempMatrix.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), this->GetInput()->GetNumberOfComponentsPerPixel()); + + + + itk::ImageRegionConstIteratorWithIndex<TInputImage> it (inputPtr, outputRegionForThread); + it.GoToBegin(); + // do the work + while (!it.IsAtEnd()) { - /** - * Grab the input - */ - InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); - // support progress methods/callbacks - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - - MatrixType pixelVector, pixelTransposeVector, pixelSumVector, tempMatrix; - - pixelVector.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), 1); - pixelVector.Fill(itk::NumericTraits<RealType>::Zero); - pixelTransposeVector.SetSize(1, this->GetInput()->GetNumberOfComponentsPerPixel()); - pixelTransposeVector.Fill(itk::NumericTraits<RealType>::Zero); - pixelSumVector.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), this->GetInput()->GetNumberOfComponentsPerPixel()); - pixelSumVector.Fill(itk::NumericTraits<RealType>::Zero); - tempMatrix.SetSize(this->GetInput()->GetNumberOfComponentsPerPixel(), this->GetInput()->GetNumberOfComponentsPerPixel()); - - - - itk::ImageRegionConstIteratorWithIndex<TInputImage> it (inputPtr, outputRegionForThread); - it.GoToBegin(); - // do the work - while (!it.IsAtEnd()) - { - IndexType index = it.GetIndex(); - PixelType vectorValue = it.Get(); - for (unsigned int j=0; j<vectorValue.GetSize(); j++) + IndexType index = it.GetIndex(); + PixelType vectorValue = it.Get(); + for (unsigned int j=0; j<vectorValue.GetSize(); j++) { InternalPixelType value = vectorValue[j]; RealType realValue = static_cast<RealType>( value ); if (value < m_ThreadMin[threadId][j]) - { - m_ThreadMin[threadId][j] = value; - } + { + m_ThreadMin[threadId][j] = value; + } if (value > m_ThreadMax[threadId][j]) - { - m_ThreadMax[threadId][j] = value; - } + { + m_ThreadMax[threadId][j] = value; + } m_ThreadSum[threadId][j] += realValue; pixelVector(j, 0) = realValue; } - ++it; - progress.CompletedPixel(); - pixelTransposeVector = pixelVector.GetTranspose(); - /** TODO - * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) - * m_XX[threadId]+=pixelVector*pixelTransposeVector; - **/ - tempMatrix = pixelVector*pixelTransposeVector; - if( (m_XX[threadId].Rows() != tempMatrix.Rows()) || (m_XX[threadId].Cols() != tempMatrix.Cols())) + ++it; + progress.CompletedPixel(); + pixelTransposeVector = pixelVector.GetTranspose(); + /** TODO + * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) + * m_XX[threadId]+=pixelVector*pixelTransposeVector; + **/ + tempMatrix = pixelVector*pixelTransposeVector; + if ( (m_XX[threadId].Rows() != tempMatrix.Rows()) || (m_XX[threadId].Cols() != tempMatrix.Cols())) { itkExceptionMacro( << "Matrix with size (" << m_XX[threadId].Rows() << "," << - m_XX[threadId].Cols() << ") cannot be subtracted from matrix with size (" << - tempMatrix.Rows() << "," << tempMatrix.Cols() ); + m_XX[threadId].Cols() << ") cannot be subtracted from matrix with size (" << + tempMatrix.Rows() << "," << tempMatrix.Cols() ); } - for( unsigned int r=0; r<m_XX[threadId].Rows(); r++) + for ( unsigned int r=0; r<m_XX[threadId].Rows(); r++) { - for( unsigned int c=0; c<m_XX[threadId].Cols(); c++ ) - { - m_XX[threadId](r,c) += tempMatrix(r,c); - } - } - //**** END TODO **** - m_Count[threadId]++; + for ( unsigned int c=0; c<m_XX[threadId].Cols(); c++ ) + { + m_XX[threadId](r,c) += tempMatrix(r,c); } + } + //**** END TODO **** + m_Count[threadId]++; } - - template <class TImage> - void - PersistentStatisticsVectorImageFilter<TImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - - os << indent << "Minimum: " <<this->GetMinimumOutput()->Get()<< std::endl; - os << indent << "Maximum: "<< this->GetMaximumOutput()->Get() << std::endl; - os << indent << "Sum: " << this->GetSumOutput()->Get() << std::endl; - os << indent << "Mean: " << this->GetMeanOutput()->Get() << std::endl; - os << indent << "Covariance: " << this->GetCovarianceOutput()->Get() << std::endl; - - } +} + +template <class TImage> +void +PersistentStatisticsVectorImageFilter<TImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Minimum: " <<this->GetMinimumOutput()->Get()<< std::endl; + os << indent << "Maximum: "<< this->GetMaximumOutput()->Get() << std::endl; + os << indent << "Sum: " << this->GetSumOutput()->Get() << std::endl; + os << indent << "Mean: " << this->GetMeanOutput()->Get() << std::endl; + os << indent << "Covariance: " << this->GetCovarianceOutput()->Get() << std::endl; + +} }// end namespace otb diff --git a/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.h b/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.h index 2373bb1796910b95a31f0f5ca7f56bbb50162e90..ebeb5f910598ae3b35e9380b48d329b81e0c5d11 100644 --- a/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.h +++ b/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.h @@ -33,7 +33,7 @@ namespace otb * \ingroup ObjectListFilter */ template <class TInputList, class TOutputList, class TFunction > - class ITK_EXPORT UnaryFunctorObjectListBooleanFilter : public otb::ObjectListToObjectListFilter<TInputList,TOutputList> +class ITK_EXPORT UnaryFunctorObjectListBooleanFilter : public otb::ObjectListToObjectListFilter<TInputList,TOutputList> { public: /** Standard class typedefs. */ @@ -63,8 +63,14 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; - const FunctorType& GetFunctor() const { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -75,10 +81,10 @@ public: void SetFunctor(const FunctorType& functor) { if (m_Functor != functor) - { + { m_Functor = functor; this->Modified(); - } + } } diff --git a/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.txx b/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.txx index adc0dea1e2c13361d0fc285e6e1f90e3315bbffb..17043d297840db8f9d4e14615b537e5dd65c7afc 100644 --- a/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.txx +++ b/Code/BasicFilters/otbUnaryFunctorObjectListBooleanFilter.txx @@ -51,9 +51,9 @@ UnaryFunctorObjectListBooleanFilter<TInputList,TOutputList,TFunction> itk::ProgressReporter progress(this, 0, inputPtr->Size()); // Define the iterators - for(InputListIterator it = inputPtr->Begin(); it != inputPtr->End(); ++it) + for (InputListIterator it = inputPtr->Begin(); it != inputPtr->End(); ++it) { - if(m_Functor(it.Get())) + if (m_Functor(it.Get())) { outputPtr->PushBack(it.Get()); } diff --git a/Code/BasicFilters/otbUnaryFunctorObjectListFilter.h b/Code/BasicFilters/otbUnaryFunctorObjectListFilter.h index 6c9fd37a3ab2930045a369f447d9ff5da9aa523b..ff3829334ceabf1c0d835bed7767dd2a83195f06 100644 --- a/Code/BasicFilters/otbUnaryFunctorObjectListFilter.h +++ b/Code/BasicFilters/otbUnaryFunctorObjectListFilter.h @@ -33,7 +33,7 @@ namespace otb * \ingroup ObjectListFilter */ template <class TInputList, class TOutputList, class TFunction > - class ITK_EXPORT UnaryFunctorObjectListFilter : public otb::ObjectListToObjectListFilter<TInputList,TOutputList> +class ITK_EXPORT UnaryFunctorObjectListFilter : public otb::ObjectListToObjectListFilter<TInputList,TOutputList> { public: /** Standard class typedefs. */ @@ -62,8 +62,14 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; - const FunctorType& GetFunctor() const { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -74,10 +80,10 @@ public: void SetFunctor(const FunctorType& functor) { if (m_Functor != functor) - { + { m_Functor = functor; this->Modified(); - } + } } diff --git a/Code/BasicFilters/otbUnaryFunctorObjectListFilter.txx b/Code/BasicFilters/otbUnaryFunctorObjectListFilter.txx index 0bccd2a3c7c062593a925b98bb831c63f23a1041..4c2b3950f1fbfdf1dfb0d9d5a6d95e35e40c7977 100644 --- a/Code/BasicFilters/otbUnaryFunctorObjectListFilter.txx +++ b/Code/BasicFilters/otbUnaryFunctorObjectListFilter.txx @@ -55,7 +55,7 @@ UnaryFunctorObjectListFilter<TInputList,TOutputList,TFunction> ++count; } - while((count < stopIndex) && (it != inputPtr->End())) + while ((count < stopIndex) && (it != inputPtr->End())) { this->m_ObjectListPerThread[threadId]->PushBack(m_Functor(it.Get())); @@ -68,17 +68,17 @@ UnaryFunctorObjectListFilter<TInputList,TOutputList,TFunction> template <class TInputList, class TOutputList, class TFunction > - void - UnaryFunctorObjectListFilter<TInputList,TOutputList,TFunction> - ::AfterThreadedGenerateData() +void +UnaryFunctorObjectListFilter<TInputList,TOutputList,TFunction> +::AfterThreadedGenerateData() { // copy the lists to the output OutputListPointer outputPtr = this->GetOutput(); for (unsigned int i=0; i< this->m_ObjectListPerThread.size(); ++i) { - for(OutputListIterator it = this->m_ObjectListPerThread[i]->Begin(); - it != this->m_ObjectListPerThread[i]->End(); - ++it) + for (OutputListIterator it = this->m_ObjectListPerThread[i]->Begin(); + it != this->m_ObjectListPerThread[i]->End(); + ++it) { outputPtr->PushBack(it.Get()); } diff --git a/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.h b/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.h index b71967cd4d4dedc2806a0c97712cc1a53bd2228c..b8c97718c665bf67270197169f1167c7e9713d7f 100644 --- a/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.h +++ b/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.h @@ -30,14 +30,14 @@ namespace otb { - /** \class UnaryImageFunctorWithVectorImageFilter - * \brief The aim of the class is to work with vector images but with a functor that uses as input a componant of the pixel. - * - * For N components pixel, the fucntor will be called N times and completes the Nth component the corresponding output pixel. - * - * \ingroup Functor - * \ingroup VectorImage - */ +/** \class UnaryImageFunctorWithVectorImageFilter + * \brief The aim of the class is to work with vector images but with a functor that uses as input a componant of the pixel. + * + * For N components pixel, the fucntor will be called N times and completes the Nth component the corresponding output pixel. + * + * \ingroup Functor + * \ingroup VectorImage + */ template <class TInputImage, class TOutputImage, class TFunction> class ITK_EXPORT UnaryImageFunctorWithVectorImageFilter : public itk::InPlaceImageFilter<TInputImage,TOutputImage> @@ -80,13 +80,13 @@ public: /** Get the functor list */ FunctorVectorType& GetFunctorVector(void) - { - return m_FunctorVector; - } + { + return m_FunctorVector; + } - protected: +protected: UnaryImageFunctorWithVectorImageFilter(); - virtual ~UnaryImageFunctorWithVectorImageFilter(){}; + virtual ~UnaryImageFunctorWithVectorImageFilter() {}; /** UnaryImageFunctorWithVectorImageFilter can produce an image which is a different * resolution than its input image. As such, UnaryImageFunctorWithVectorImageFilter diff --git a/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.txx b/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.txx index df82d67b959abdad296404e409291c1a267153f2..17d6a26b2bd8b8ce093e71bedabb79b04f256e19 100644 --- a/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.txx +++ b/Code/BasicFilters/otbUnaryImageFunctorWithVectorImageFilter.txx @@ -59,19 +59,19 @@ UnaryImageFunctorWithVectorImageFilter<TInputImage,TOutputImage,TFunction> typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); if ( !outputPtr || !inputPtr) - { + { return; - } - outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info - inputPtr->GetNumberOfComponentsPerPixel()); + } + outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info + inputPtr->GetNumberOfComponentsPerPixel()); - // TODO: Check this - // The Functor vector is not initialised ! - for(unsigned int i = 0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) - { - FunctorType functor; - m_FunctorVector.push_back(functor); - } + // TODO: Check this + // The Functor vector is not initialised ! + for (unsigned int i = 0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) + { + FunctorType functor; + m_FunctorVector.push_back(functor); + } } /** @@ -99,25 +99,25 @@ UnaryImageFunctorWithVectorImageFilter<TInputImage,TOutputImage,TFunction> nullPixel.SetSize( inputPtr->GetNumberOfComponentsPerPixel() ); nullPixel.Fill(itk::NumericTraits<OutputInternalPixelType>::Zero); - while( !inputIt.IsAtEnd() ) - { - InputPixelType inPixel = inputIt.Get(); - OutputPixelType outPixel; - outPixel.SetSize( inputPtr->GetNumberOfComponentsPerPixel() ); - outPixel.Fill(itk::NumericTraits<OutputInternalPixelType>::Zero); - // if the input pixel in null, the output is considered as null ( no sensor informations ) - if( inPixel!= nullPixel) + while ( !inputIt.IsAtEnd() ) { + InputPixelType inPixel = inputIt.Get(); + OutputPixelType outPixel; + outPixel.SetSize( inputPtr->GetNumberOfComponentsPerPixel() ); + outPixel.Fill(itk::NumericTraits<OutputInternalPixelType>::Zero); + // if the input pixel in null, the output is considered as null ( no sensor informations ) + if ( inPixel!= nullPixel) + { for (unsigned int j=0; j<inputPtr->GetNumberOfComponentsPerPixel(); j++) - { - outPixel[j] = m_FunctorVector[j]( inPixel[j] ); - } - } - outputIt.Set(outPixel); - ++inputIt; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here + { + outPixel[j] = m_FunctorVector[j]( inPixel[j] ); + } } + outputIt.Set(outPixel); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } } template <class TInputImage, class TOutputImage, class TFunction> diff --git a/Code/BasicFilters/otbVarianceImageFilter.h b/Code/BasicFilters/otbVarianceImageFilter.h index 40f43d689beaddf05d1970b2f40cadcf65fa65f1..c3735a8bbabfa4a9e52834dd0285a19943ea8b28 100644 --- a/Code/BasicFilters/otbVarianceImageFilter.h +++ b/Code/BasicFilters/otbVarianceImageFilter.h @@ -40,7 +40,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT VarianceImageFilter : - public itk::ImageToImageFilter< TInputImage, TOutputImage > + public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: /** Extract dimension from input and output image. */ diff --git a/Code/BasicFilters/otbVarianceImageFilter.txx b/Code/BasicFilters/otbVarianceImageFilter.txx index a1f89da0fed1febb17211fc3bf786561c2d47b6d..09274a48c0ef575c19206831f290327cbbff7649 100644 --- a/Code/BasicFilters/otbVarianceImageFilter.txx +++ b/Code/BasicFilters/otbVarianceImageFilter.txx @@ -52,9 +52,9 @@ VarianceImageFilter<TInputImage, TOutputImage> typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -66,12 +66,12 @@ VarianceImageFilter<TInputImage, TOutputImage> // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -84,7 +84,7 @@ VarianceImageFilter<TInputImage, TOutputImage> e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } @@ -120,24 +120,24 @@ VarianceImageFilter< TInputImage, TOutputImage> // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, - input, *fit); + input, *fit); unsigned int neighborhoodSize = bit.Size(); it = itk::ImageRegionIterator<OutputImageType>(output, *fit); bit.OverrideBoundaryCondition(&nbc); bit.GoToBegin(); while ( ! bit.IsAtEnd() ) - { + { sum = itk::NumericTraits<InputRealType>::Zero; sumOfSquares = itk::NumericTraits<InputRealType>::Zero; for (i = 0; i < neighborhoodSize; ++i) - { + { const InputRealType value = static_cast<InputRealType>( bit.GetPixel(i) ); - sum += value; - sumOfSquares += value * value; - } + sum += value; + sumOfSquares += value * value; + } // get the mean value const double num = static_cast<double>( neighborhoodSize ); @@ -146,8 +146,8 @@ VarianceImageFilter< TInputImage, TOutputImage> ++bit; ++it; progress.CompletedPixel(); - } } + } } /** diff --git a/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.h b/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.h index 9bccd70b42ce0befc1a2504367fb88728fe780a0..0f3bc3a23d4f45631b622bd889ec5142afcc17cd 100644 --- a/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.h +++ b/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.h @@ -38,9 +38,9 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT VectorImageTo3DScalarImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef VectorImageTo3DScalarImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -84,7 +84,7 @@ protected: VectorImageTo3DScalarImageFilter(); /** Destructor */ virtual ~VectorImageTo3DScalarImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.txx b/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.txx index 32fc314a8a45398b0f86e90d8f0d5a9d44f06fe5..4f7334a71ac6dfd49ab3d8fcf48c47536b4f44e4 100644 --- a/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.txx +++ b/Code/BasicFilters/otbVectorImageTo3DScalarImageFilter.txx @@ -44,11 +44,11 @@ VectorImageTo3DScalarImageFilter<TInputImage, TOutputImage> InputImageRegionType inputLargestRegion = this->GetInput()->GetLargestPossibleRegion(); OutputImageSizeType size; OutputImageIndexType index; - for(unsigned int i = 0;i<InputImageType::ImageDimension;++i) - { - size[i] = inputLargestRegion.GetSize()[i]; - index[i]= inputLargestRegion.GetIndex()[i]; - } + for (unsigned int i = 0;i<InputImageType::ImageDimension;++i) + { + size[i] = inputLargestRegion.GetSize()[i]; + index[i]= inputLargestRegion.GetIndex()[i]; + } size[OutputImageType::ImageDimension-1]=inputPtr->GetNumberOfComponentsPerPixel(); index[OutputImageType::ImageDimension-1]=0; @@ -71,11 +71,11 @@ VectorImageTo3DScalarImageFilter<TInputImage, TOutputImage> InputImageSizeType size; InputImageIndexType index; - for(unsigned int i = 0;i<InputImageType::ImageDimension;++i) - { - size[i]=requestedRegion.GetSize()[i]; - index[i]=requestedRegion.GetIndex()[i]; - } + for (unsigned int i = 0;i<InputImageType::ImageDimension;++i) + { + size[i]=requestedRegion.GetSize()[i]; + index[i]=requestedRegion.GetIndex()[i]; + } inputRequestedRegion.SetSize(size); inputRequestedRegion.SetIndex(index); inputPtr->SetRequestedRegion(inputRequestedRegion); @@ -84,7 +84,7 @@ template <class TInputImage, class TOutputImage> void VectorImageTo3DScalarImageFilter<TInputImage, TOutputImage> ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ) + int threadId ) { const InputImageType* inputPtr = this->GetInput(); OutputImageType* outputPtr = this->GetOutput(); @@ -96,11 +96,11 @@ VectorImageTo3DScalarImageFilter<TInputImage, TOutputImage> InputImageSizeType size; InputImageIndexType index; - for(unsigned int i = 0;i<InputImageType::ImageDimension;++i) - { - size[i]=outputRegionForThread.GetSize()[i]; - index[i]=outputRegionForThread.GetIndex()[i]; - } + for (unsigned int i = 0;i<InputImageType::ImageDimension;++i) + { + size[i]=outputRegionForThread.GetSize()[i]; + index[i]=outputRegionForThread.GetIndex()[i]; + } inputRegion.SetSize(size); inputRegion.SetIndex(index); @@ -113,24 +113,24 @@ VectorImageTo3DScalarImageFilter<TInputImage, TOutputImage> outIt.GoToBegin(); inIt.GoToBegin(); - while(!outIt.IsAtEnd()) + while (!outIt.IsAtEnd()) + { + outIt.Set(static_cast<OutputPixelType>(inIt.Get()[outIt.GetIndex()[InputImageType::ImageDimension]])); + ++inIt; + if (inIt.IsAtEnd()) + { + inIt.GoToBegin(); + } + ++outIt; + if (outIt.IsAtEndOfLine()) { - outIt.Set(static_cast<OutputPixelType>(inIt.Get()[outIt.GetIndex()[InputImageType::ImageDimension]])); - ++inIt; - if(inIt.IsAtEnd()) - { - inIt.GoToBegin(); - } - ++outIt; - if(outIt.IsAtEndOfLine()) - { outIt.NextLine(); - } - if(outIt.IsAtEndOfSlice()) - { - outIt.NextSlice(); - } } + if (outIt.IsAtEndOfSlice()) + { + outIt.NextSlice(); + } + } } /** * PrintSelf Method diff --git a/Code/BasicFilters/otbVectorImageToAmplitudeImageFilter.h b/Code/BasicFilters/otbVectorImageToAmplitudeImageFilter.h index a926dbbc1eef272ae73fcc6c0cd7264ced3434ab..4206d3cef6f30f7ecf376df7c630b8a4c5e324c4 100644 --- a/Code/BasicFilters/otbVectorImageToAmplitudeImageFilter.h +++ b/Code/BasicFilters/otbVectorImageToAmplitudeImageFilter.h @@ -23,21 +23,21 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace Functor - { - template < class TInput, class TOutput> - class VectorToAmplitudeFunctor - { - public: - VectorToAmplitudeFunctor(){}; - ~VectorToAmplitudeFunctor(){}; +namespace Functor +{ +template < class TInput, class TOutput> +class VectorToAmplitudeFunctor +{ +public: + VectorToAmplitudeFunctor() {}; + ~VectorToAmplitudeFunctor() {}; - inline TOutput operator()(const TInput & A) - { - return static_cast<TOutput>(vcl_sqrt(A.GetSquaredNorm())); - } - }; // end namespace Functor - } + inline TOutput operator()(const TInput & A) + { + return static_cast<TOutput>(vcl_sqrt(A.GetSquaredNorm())); + } +}; // end namespace Functor +} /** \class VectorImageToAmplitudeImageFilter @@ -48,10 +48,10 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT VectorImageToAmplitudeImageFilter - : public itk::UnaryFunctorImageFilter<TInputImage,TOutputImage,Functor::VectorToAmplitudeFunctor< - typename TInputImage::PixelType, typename TOutputImage::PixelType> > + : public itk::UnaryFunctorImageFilter<TInputImage,TOutputImage,Functor::VectorToAmplitudeFunctor< + typename TInputImage::PixelType, typename TOutputImage::PixelType> > { - public: +public: /** Standard typedefs */ typedef VectorImageToAmplitudeImageFilter Self; typedef itk::UnaryFunctorImageFilter<TInputImage,TOutputImage,Functor::VectorToAmplitudeFunctor< @@ -67,14 +67,14 @@ class ITK_EXPORT VectorImageToAmplitudeImageFilter protected: /** Constructor */ - VectorImageToAmplitudeImageFilter(){}; + VectorImageToAmplitudeImageFilter() {}; /** Destructor */ virtual ~VectorImageToAmplitudeImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: VectorImageToAmplitudeImageFilter(const Self&); //purposely not implemented diff --git a/Code/BasicFilters/otbVectorImageToImageListFilter.h b/Code/BasicFilters/otbVectorImageToImageListFilter.h index 01441aaf5fdd6ebd8f51b6bc97e70705c1115df0..a1de085ae938ab03468c87f8c947c15d9cc1481e 100644 --- a/Code/BasicFilters/otbVectorImageToImageListFilter.h +++ b/Code/BasicFilters/otbVectorImageToImageListFilter.h @@ -34,13 +34,13 @@ namespace otb */ template <class TVectorImageType, class TImageList> class ITK_EXPORT VectorImageToImageListFilter - : public ImageToImageListFilter<TVectorImageType,typename TImageList::ImageType> + : public ImageToImageListFilter<TVectorImageType,typename TImageList::ImageType> { - public: +public: /** Standard typedefs */ typedef VectorImageToImageListFilter Self; typedef ImageToImageListFilter<TVectorImageType, - typename TImageList::ImageType> Superclass; + typename TImageList::ImageType> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -73,7 +73,7 @@ protected: VectorImageToImageListFilter() {}; /** Destructor */ virtual ~VectorImageToImageListFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/BasicFilters/otbVectorImageToImageListFilter.txx b/Code/BasicFilters/otbVectorImageToImageListFilter.txx index c9581fd66215634af85603cf76a0595ebcd310f8..862eaf28e21839f6f1a8bb4c6c3e58cdd9615060 100644 --- a/Code/BasicFilters/otbVectorImageToImageListFilter.txx +++ b/Code/BasicFilters/otbVectorImageToImageListFilter.txx @@ -36,27 +36,27 @@ VectorImageToImageListFilter<TVectorImageType,TImageList> OutputImageListPointerType outputPtr = this->GetOutput(); InputVectorImagePointerType inputPtr = this->GetInput(); - if(inputPtr) - { - if(outputPtr->Size()!=inputPtr->GetNumberOfComponentsPerPixel()) + if (inputPtr) { - // if the number of components does not match, clear the list - outputPtr->Clear(); - for(unsigned int i=0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) + if (outputPtr->Size()!=inputPtr->GetNumberOfComponentsPerPixel()) + { + // if the number of components does not match, clear the list + outputPtr->Clear(); + for (unsigned int i=0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) { typename OutputImageType::Pointer tmpImagePtr = OutputImageType::New(); this->AddOutput(tmpImagePtr); outputPtr->PushBack(tmpImagePtr); } - } - for(unsigned int i=0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) - { - typename OutputImageType::Pointer tmpImagePtr = outputPtr->GetNthElement(i); - tmpImagePtr->CopyInformation(inputPtr); - tmpImagePtr->SetLargestPossibleRegion(inputPtr->GetLargestPossibleRegion()); - tmpImagePtr->SetRequestedRegion(inputPtr->GetLargestPossibleRegion()); - } } + for (unsigned int i=0;i<inputPtr->GetNumberOfComponentsPerPixel();++i) + { + typename OutputImageType::Pointer tmpImagePtr = outputPtr->GetNthElement(i); + tmpImagePtr->CopyInformation(inputPtr); + tmpImagePtr->SetLargestPossibleRegion(inputPtr->GetLargestPossibleRegion()); + tmpImagePtr->SetRequestedRegion(inputPtr->GetLargestPossibleRegion()); + } + } } /** Generate the output information by building the output list. */ template <class TVectorImageType, class TImageList> @@ -67,13 +67,13 @@ VectorImageToImageListFilter<TVectorImageType,TImageList> OutputImageListPointerType outputPtr = this->GetOutput(); InputVectorImagePointerType inputPtr = this->GetInput(); - if(inputPtr) - { - if(outputPtr->Size()>0) + if (inputPtr) { - inputPtr->SetRequestedRegion(outputPtr->GetNthElement(0)->GetRequestedRegion()); - } + if (outputPtr->Size()>0) + { + inputPtr->SetRequestedRegion(outputPtr->GetNthElement(0)->GetRequestedRegion()); } + } } /** * Main computation method @@ -91,41 +91,41 @@ VectorImageToImageListFilter<TVectorImageType,TImageList> std::vector<OutputIteratorType> outputIteratorList; - typename OutputImageListType::ConstIterator outputListIt = outputPtr->Begin(); - for(;outputListIt!=outputPtr->End();++outputListIt) - { - outputListIt.Get()->SetBufferedRegion(outputListIt.Get()->GetRequestedRegion()); - outputListIt.Get()->Allocate(); - OutputIteratorType tmpIt = OutputIteratorType(outputListIt.Get(),outputListIt.Get()->GetRequestedRegion()); - tmpIt.GoToBegin(); - outputIteratorList.push_back(tmpIt); - } + typename OutputImageListType::ConstIterator outputListIt = outputPtr->Begin(); + for (;outputListIt!=outputPtr->End();++outputListIt) + { + outputListIt.Get()->SetBufferedRegion(outputListIt.Get()->GetRequestedRegion()); + outputListIt.Get()->Allocate(); + OutputIteratorType tmpIt = OutputIteratorType(outputListIt.Get(),outputListIt.Get()->GetRequestedRegion()); + tmpIt.GoToBegin(); + outputIteratorList.push_back(tmpIt); + } InputIteratorType inputIt(inputPtr,outputPtr->GetNthElement(0)->GetRequestedRegion()); itk::ProgressReporter progress(this,0,outputPtr->GetNthElement(0)->GetRequestedRegion().GetNumberOfPixels()); inputIt.GoToBegin(); - while(!inputIt.IsAtEnd()) - { - unsigned int counter = 0; - for(typename std::vector<OutputIteratorType>::iterator it = outputIteratorList.begin(); - it!=outputIteratorList.end();++it) + while (!inputIt.IsAtEnd()) { - if(!(*it).IsAtEnd()) + unsigned int counter = 0; + for (typename std::vector<OutputIteratorType>::iterator it = outputIteratorList.begin(); + it!=outputIteratorList.end();++it) + { + if (!(*it).IsAtEnd()) { (*it).Set(static_cast<typename OutputImageType::PixelType>(inputIt.Get()[counter])); ++(*it); ++counter; } - else + else { itkGenericExceptionMacro("End of image for band "<<counter<<" at index "<<(*it).GetIndex()<<" !"); } - } - progress.CompletedPixel(); - ++inputIt; } + progress.CompletedPixel(); + ++inputIt; + } } /** * PrintSelf Method diff --git a/Code/BasicFilters/otbVectorImageToIntensityImageFilter.h b/Code/BasicFilters/otbVectorImageToIntensityImageFilter.h index 288934e0e922f814e146f2cedbb8d8c74972c17a..7ffef91b6d2e06ca3e97a551f087f5f9b3c27bcf 100644 --- a/Code/BasicFilters/otbVectorImageToIntensityImageFilter.h +++ b/Code/BasicFilters/otbVectorImageToIntensityImageFilter.h @@ -45,9 +45,9 @@ namespace otb */ template <class TInputImage,class TOutputImage> class ITK_EXPORT VectorImageToIntensityImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef VectorImageToIntensityImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -76,7 +76,7 @@ protected: VectorImageToIntensityImageFilter(); /** Destructor */ virtual ~VectorImageToIntensityImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** VectorImageToIntensityImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() routine diff --git a/Code/BasicFilters/otbVectorImageToIntensityImageFilter.txx b/Code/BasicFilters/otbVectorImageToIntensityImageFilter.txx index d4da7976a84357458507b36f07746c2858c197b3..1cfd2066fc6907c9b32e74732c35a2cb46603ca5 100644 --- a/Code/BasicFilters/otbVectorImageToIntensityImageFilter.txx +++ b/Code/BasicFilters/otbVectorImageToIntensityImageFilter.txx @@ -62,22 +62,22 @@ VectorImageToIntensityImageFilter<TInputImage,TOutputImage> inputIt.GoToBegin(); outputIt.GoToBegin(); - while(!inputIt.IsAtEnd() && !outputIt.IsAtEnd()) - { - double sum=0.0; - InputPixelType pixel = inputIt.Get(); - for (unsigned int i=0; i<pixel.Size(); i++) + while (!inputIt.IsAtEnd() && !outputIt.IsAtEnd()) { - sum += pixel[i]; - } - sum /= pixel.Size(); + double sum=0.0; + InputPixelType pixel = inputIt.Get(); + for (unsigned int i=0; i<pixel.Size(); i++) + { + sum += pixel[i]; + } + sum /= pixel.Size(); outputIt.Set(static_cast<OutputPixelType>(sum)); ++inputIt; ++outputIt; progress.CompletedPixel(); // potential exception thrown here - } + } } /** * PrintSelf Method diff --git a/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.h b/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.h index d87ede019b43b544f9f24e2f0435e0cd273d9292..647c85d2f2667d3056c49acdd21fe032d1dd7e1c 100644 --- a/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.h +++ b/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.h @@ -26,135 +26,160 @@ namespace otb { -namespace Functor { - /** \class VectorAffineTransform - * \brief This functor performs a per band linear transform of its input. - * - * Values upper than InputMaximum or lower than InputMinimum are clamped to OutputMaximum - * respectively OutputMinimum values. - * - * TInput and TOutput type are supposed to be of type itk::VariableLengthVector. - * - */ - template< typename TInput, typename TOutput> - class VectorAffineTransform - { - public: - /// Real type typedef - typedef typename itk::NumericTraits< typename TInput::ValueType >::RealType RealType; - - /// Constructor - VectorAffineTransform() {} - /// Desctructor - ~VectorAffineTransform() {} - - /// Accessors - void SetOutputMaximum( TOutput a ) { m_OutputMaximum = a;} - void SetOutputMinimum( TOutput a) {m_OutputMinimum = a;} - void SetInputMinimum(TInput a) {m_InputMinimum = a;} - void SetInputMaximum(TInput a) {m_InputMaximum = a;} - TOutput GetOutputMaximum(){return m_OutputMaximum;} - TOutput GetOutputMinimum(){return m_OutputMinimum;} - TInput GetInputMinimum(){return m_InputMinimum;} - TInput GetInputMaximum(){return m_InputMaximum;} - - - bool operator!=( const VectorAffineTransform & other ) const +namespace Functor +{ +/** \class VectorAffineTransform + * \brief This functor performs a per band linear transform of its input. + * + * Values upper than InputMaximum or lower than InputMinimum are clamped to OutputMaximum + * respectively OutputMinimum values. + * + * TInput and TOutput type are supposed to be of type itk::VariableLengthVector. + * + */ +template< typename TInput, typename TOutput> +class VectorAffineTransform +{ +public: + /// Real type typedef + typedef typename itk::NumericTraits< typename TInput::ValueType >::RealType RealType; + + /// Constructor + VectorAffineTransform() {} + /// Desctructor + ~VectorAffineTransform() {} + + /// Accessors + void SetOutputMaximum( TOutput a ) { - if(m_OutputMaximum.Size()==other.GetOutputMaximum().Size()) - { - for(unsigned int i = 0;i<m_OutputMaximum.Size();++i) + m_OutputMaximum = a; + } + void SetOutputMinimum( TOutput a) + { + m_OutputMinimum = a; + } + void SetInputMinimum(TInput a) + { + m_InputMinimum = a; + } + void SetInputMaximum(TInput a) + { + m_InputMaximum = a; + } + TOutput GetOutputMaximum() + { + return m_OutputMaximum; + } + TOutput GetOutputMinimum() + { + return m_OutputMinimum; + } + TInput GetInputMinimum() + { + return m_InputMinimum; + } + TInput GetInputMaximum() + { + return m_InputMaximum; + } + + + bool operator!=( const VectorAffineTransform & other ) const + { + if (m_OutputMaximum.Size()==other.GetOutputMaximum().Size()) { - if( m_OutputMaximum[i] != other.GetOutputMaximum()[i] ) + for (unsigned int i = 0;i<m_OutputMaximum.Size();++i) + { + if ( m_OutputMaximum[i] != other.GetOutputMaximum()[i] ) { return true; } - } } - if(m_OutputMaximum.Size()==other.GetOutputMaximum().Size()) - { - for(unsigned int i = 0;i<m_OutputMaximum.Size();++i) + } + if (m_OutputMaximum.Size()==other.GetOutputMaximum().Size()) { - if( m_OutputMaximum[i] != other.GetOutputMaximum()[i] ) + for (unsigned int i = 0;i<m_OutputMaximum.Size();++i) + { + if ( m_OutputMaximum[i] != other.GetOutputMaximum()[i] ) { return true; } - } } - if(m_InputMinimum.Size()==other.GetInputMinimum().Size()) - { - for(unsigned int i = 0;i<m_InputMinimum.Size();++i) + } + if (m_InputMinimum.Size()==other.GetInputMinimum().Size()) { - if( m_InputMinimum[i] != other.GetInputMinimum()[i] ) + for (unsigned int i = 0;i<m_InputMinimum.Size();++i) + { + if ( m_InputMinimum[i] != other.GetInputMinimum()[i] ) { return true; } - } } - if(m_InputMaximum.Size()==other.GetInputMaximum().Size()) - { - for(unsigned int i = 0;i<m_InputMaximum.Size();++i) + } + if (m_InputMaximum.Size()==other.GetInputMaximum().Size()) { - if( m_InputMaximum[i] != other.GetInputMaximum()[i] ) + for (unsigned int i = 0;i<m_InputMaximum.Size();++i) + { + if ( m_InputMaximum[i] != other.GetInputMaximum()[i] ) { return true; } - } } + } return false; } - bool operator==( const VectorAffineTransform & other ) const + bool operator==( const VectorAffineTransform & other ) const { return !(*this != other); } - // main computation method - inline TOutput operator()( const TInput & x ) + // main computation method + inline TOutput operator()( const TInput & x ) { // output instantiation TOutput result; result.SetSize(x.GetSize()); // consistency checking - if( result.GetSize()!=m_OutputMaximum.GetSize() - || result.GetSize() != m_OutputMaximum.GetSize() - || result.GetSize() != m_InputMinimum.GetSize() - || result.GetSize() != m_InputMaximum.GetSize()) - { - itkGenericExceptionMacro(<<"Pixel size different from scale or shift size !"); - } - - // transformation - for(unsigned int i=0; i<x.GetSize();++i) - { - if(x[i]<m_InputMinimum[i]) - { - result[i] = m_OutputMinimum[i]; - } - else if (x[i]>m_InputMaximum[i]) - { - result[i] = m_OutputMaximum[i]; - } - else if(m_InputMaximum[i]==m_InputMinimum[i]) + if ( result.GetSize()!=m_OutputMaximum.GetSize() + || result.GetSize() != m_OutputMaximum.GetSize() + || result.GetSize() != m_InputMinimum.GetSize() + || result.GetSize() != m_InputMaximum.GetSize()) { - result[i]=m_OutputMinimum[i]; + itkGenericExceptionMacro(<<"Pixel size different from scale or shift size !"); } - else + + // transformation + for (unsigned int i=0; i<x.GetSize();++i) { - const RealType scaledComponent = static_cast<RealType>( x[i]-m_InputMinimum[i] ) - * static_cast<RealType> (m_OutputMaximum[i] - m_OutputMinimum[i]) - / static_cast<RealType> (m_InputMaximum[i] - m_InputMinimum[i]); - result[i]= static_cast< typename TOutput::ValueType >( scaledComponent+m_OutputMinimum[i] ); - } + if (x[i]<m_InputMinimum[i]) + { + result[i] = m_OutputMinimum[i]; + } + else if (x[i]>m_InputMaximum[i]) + { + result[i] = m_OutputMaximum[i]; + } + else if (m_InputMaximum[i]==m_InputMinimum[i]) + { + result[i]=m_OutputMinimum[i]; + } + else + { + const RealType scaledComponent = static_cast<RealType>( x[i]-m_InputMinimum[i] ) + * static_cast<RealType> (m_OutputMaximum[i] - m_OutputMinimum[i]) + / static_cast<RealType> (m_InputMaximum[i] - m_InputMinimum[i]); + result[i]= static_cast< typename TOutput::ValueType >( scaledComponent+m_OutputMinimum[i] ); } + } return result; } - private: - TOutput m_OutputMaximum; - TOutput m_OutputMinimum; - TInput m_InputMinimum; - TInput m_InputMaximum; - }; +private: + TOutput m_OutputMaximum; + TOutput m_OutputMinimum; + TInput m_InputMinimum; + TInput m_InputMaximum; +}; } // end namespace functor @@ -172,12 +197,12 @@ namespace Functor { */ template <class TInputImage, class TOutputImage=TInputImage> class ITK_EXPORT VectorRescaleIntensityImageFilter - : public itk::UnaryFunctorImageFilter<TInputImage,TOutputImage, - Functor::VectorAffineTransform< - typename TInputImage::PixelType, - typename TOutputImage::PixelType> > + : public itk::UnaryFunctorImageFilter<TInputImage,TOutputImage, + Functor::VectorAffineTransform< + typename TInputImage::PixelType, + typename TOutputImage::PixelType> > { - public: +public: /** Standard class typedefs. */ typedef VectorRescaleIntensityImageFilter Self; typedef itk::UnaryFunctorImageFilter<TInputImage,TOutputImage, diff --git a/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.txx b/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.txx index dce5fe5988478d1ecd4005e2da19e7c4df39ca6a..4ddccd1c2c138b2a52f14f518a76d0bd8140e80b 100644 --- a/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.txx +++ b/Code/BasicFilters/otbVectorRescaleIntensityImageFilter.txx @@ -50,7 +50,7 @@ VectorRescaleIntensityImageFilter<TInputImage,TOutputImage> { this->Superclass::GenerateOutputInformation(); this->GetOutput()->SetNumberOfComponentsPerPixel( - this->GetInput()->GetNumberOfComponentsPerPixel() ); + this->GetInput()->GetNumberOfComponentsPerPixel() ); } /** * Generate input requested region. @@ -59,15 +59,15 @@ template <class TInputImage, class TOutputImage> void VectorRescaleIntensityImageFilter<TInputImage,TOutputImage> ::GenerateInputRequestedRegion(void) - { - if(this->GetInput()) - { - typename TInputImage::Pointer input = const_cast<TInputImage *>(this->GetInput()); - typename TInputImage::RegionType inputRegion; - this->CallCopyOutputRegionToInputRegion(inputRegion,this->GetOutput()->GetRequestedRegion()); - input->SetRequestedRegion(inputRegion); - } - } +{ + if (this->GetInput()) + { + typename TInputImage::Pointer input = const_cast<TInputImage *>(this->GetInput()); + typename TInputImage::RegionType inputRegion; + this->CallCopyOutputRegionToInputRegion(inputRegion,this->GetOutput()->GetRequestedRegion()); + input->SetRequestedRegion(inputRegion); + } +} /** * Process to execute before entering the multithreaded section. */ @@ -76,63 +76,63 @@ void VectorRescaleIntensityImageFilter<TInputImage, TOutputImage> ::BeforeThreadedGenerateData() { - if(m_AutomaticInputMinMaxComputation) - { + if (m_AutomaticInputMinMaxComputation) + { - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; - // Get the input - InputImagePointer inputImage = this->GetInput(); + // Get the input + InputImagePointer inputImage = this->GetInput(); - typedef itk::ImageRegionConstIterator< InputImageType > InputIterator; - typedef itk::Vector<typename InputImageType::InternalPixelType,1> MeasurementVectorType; - typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; - typedef float HistogramMeasurementType; - typedef itk::Statistics::ListSampleToHistogramGenerator<ListSampleType,HistogramMeasurementType, - itk::Statistics::DenseFrequencyContainer,1> HistogramGeneratorType; + typedef itk::ImageRegionConstIterator< InputImageType > InputIterator; + typedef itk::Vector<typename InputImageType::InternalPixelType,1> MeasurementVectorType; + typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; + typedef float HistogramMeasurementType; + typedef itk::Statistics::ListSampleToHistogramGenerator<ListSampleType,HistogramMeasurementType, + itk::Statistics::DenseFrequencyContainer,1> HistogramGeneratorType; - typedef ObjectList<ListSampleType> ListSampleListType; + typedef ObjectList<ListSampleType> ListSampleListType; - m_InputMinimum.SetSize(inputImage->GetNumberOfComponentsPerPixel()); - m_InputMaximum.SetSize(inputImage->GetNumberOfComponentsPerPixel()); - typename ListSampleListType::Pointer sl = ListSampleListType::New(); + m_InputMinimum.SetSize(inputImage->GetNumberOfComponentsPerPixel()); + m_InputMaximum.SetSize(inputImage->GetNumberOfComponentsPerPixel()); + typename ListSampleListType::Pointer sl = ListSampleListType::New(); - sl->Reserve(inputImage->GetNumberOfComponentsPerPixel()); + sl->Reserve(inputImage->GetNumberOfComponentsPerPixel()); - for(unsigned int i = 0;i<m_InputMaximum.GetSize();++i) - { - sl->PushBack(ListSampleType::New()); - } + for (unsigned int i = 0;i<m_InputMaximum.GetSize();++i) + { + sl->PushBack(ListSampleType::New()); + } - InputIterator it( inputImage, inputImage->GetBufferedRegion() ); + InputIterator it( inputImage, inputImage->GetBufferedRegion() ); - it.GoToBegin(); + it.GoToBegin(); - while( !it.IsAtEnd() ) - { - InputPixelType pixel = it.Get(); - for(unsigned int i = 0;i<m_InputMaximum.GetSize();++i) + while ( !it.IsAtEnd() ) + { + InputPixelType pixel = it.Get(); + for (unsigned int i = 0;i<m_InputMaximum.GetSize();++i) { sl->GetNthElement(i)->PushBack(pixel[i]); } - ++it; - } + ++it; + } - for(unsigned int i = 0;i<m_InputMaximum.GetSize();++i) - { - typename HistogramGeneratorType::Pointer generator = HistogramGeneratorType::New(); - generator->SetListSample(sl->GetNthElement(i)); - typename HistogramGeneratorType::HistogramType::SizeType size; - size.Fill(static_cast<unsigned int>(vcl_ceil(1/m_ClampThreshold)*10)); - generator->SetNumberOfBins(size); - generator->Update(); - m_InputMinimum[i]=static_cast<typename InputImageType::InternalPixelType>(generator->GetOutput()->Quantile(0,m_ClampThreshold)); - m_InputMaximum[i]=static_cast<typename InputImageType::InternalPixelType>(generator->GetOutput()->Quantile(0,1-m_ClampThreshold)); - } + for (unsigned int i = 0;i<m_InputMaximum.GetSize();++i) + { + typename HistogramGeneratorType::Pointer generator = HistogramGeneratorType::New(); + generator->SetListSample(sl->GetNthElement(i)); + typename HistogramGeneratorType::HistogramType::SizeType size; + size.Fill(static_cast<unsigned int>(vcl_ceil(1/m_ClampThreshold)*10)); + generator->SetNumberOfBins(size); + generator->Update(); + m_InputMinimum[i]=static_cast<typename InputImageType::InternalPixelType>(generator->GetOutput()->Quantile(0,m_ClampThreshold)); + m_InputMaximum[i]=static_cast<typename InputImageType::InternalPixelType>(generator->GetOutput()->Quantile(0,1-m_ClampThreshold)); } + } - // set up the functor values + // set up the functor values this->GetFunctor().SetInputMinimum( m_InputMinimum ); this->GetFunctor().SetInputMaximum( m_InputMaximum ); this->GetFunctor().SetOutputMaximum(m_OutputMaximum ); diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageBlackmanFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageBlackmanFunction.h index 81298e56f7ce0e1ea5351da5df781682a800f075..56c3de5b122fa51362675449592ec76b724ea4a2 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageBlackmanFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageBlackmanFunction.h @@ -28,40 +28,49 @@ namespace otb namespace Function { - /** - * \class BlackmanWindowFunction - * \brief Window function for sinc interpolation. - * \f[ w(x) = 0.42 + 0.5 cos(\frac{\pi x}{m}) + 0.08 cos(\frac{2 \pi x}{m}) \f] - * \sa WindowedSincInterpolateImageBlackmanFunction - */ +/** + * \class BlackmanWindowFunction + * \brief Window function for sinc interpolation. + * \f[ w(x) = 0.42 + 0.5 cos(\frac{\pi x}{m}) + 0.08 cos(\frac{2 \pi x}{m}) \f] + * \sa WindowedSincInterpolateImageBlackmanFunction + */ template< class TInput=double, class TOutput=double > class BlackmanWindowFunction +{ +public: + void SetRadius(unsigned int radius) + { + m_Radius = radius; + m_Factor1 = M_PI / static_cast<double>(radius); + m_Factor2 = 2.0 * M_PI / static_cast<double>(radius); + } + unsigned int GetRadius() const + { + return m_Radius; + }; + double GetFactor1() { - public: - void SetRadius(unsigned int radius) - { - m_Radius = radius; - m_Factor1 = M_PI / static_cast<double>(radius); - m_Factor2 = 2.0 * M_PI / static_cast<double>(radius); - } - unsigned int GetRadius() const { return m_Radius; }; - double GetFactor1() { return m_Factor1; }; - double GetFactor2() { return m_Factor2; }; - - inline TOutput operator()( const TInput & A ) const - { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp = 0.42 + 0.5 * vcl_cos(x * m_Factor1) + 0.08 * vcl_cos(x * m_Factor2); - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); - } - private: - unsigned int m_Radius; - // Equal to \f$ \frac{\pi}{m} \f$ - double m_Factor1; - // Equal to \f$ \frac{2 \pi}{m} \f$ - double m_Factor2; + return m_Factor1; }; + double GetFactor2() + { + return m_Factor2; + }; + + inline TOutput operator()( const TInput & A ) const + { + double x = static_cast<double>(A); + double px = M_PI * x; + double temp = 0.42 + 0.5 * vcl_cos(x * m_Factor1) + 0.08 * vcl_cos(x * m_Factor2); + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } +private: + unsigned int m_Radius; + // Equal to \f$ \frac{\pi}{m} \f$ + double m_Factor1; + // Equal to \f$ \frac{2 \pi}{m} \f$ + double m_Factor2; +}; }//namespace Function @@ -80,53 +89,56 @@ class BlackmanWindowFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageBlackmanFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::BlackmanWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::BlackmanWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageBlackmanFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::BlackmanWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageBlackmanFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageBlackmanFunction() {}; + ~WindowedSincInterpolateImageBlackmanFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageBlackmanFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::BlackmanWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageBlackmanFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageBlackmanFunction(){}; - ~WindowedSincInterpolateImageBlackmanFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageBlackmanFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageBlackmanFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageCosineFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageCosineFunction.h index ce150b2521839bd1d7b910a02c042162928677ab..1a0e21c94dee096fa2378bfb448791b9f7386138 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageCosineFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageCosineFunction.h @@ -28,37 +28,43 @@ namespace otb namespace Function { - /** - * \class HammingWindowFunction - * \brief Window function for sinc interpolation. - * \f[ w(x) = 0.54 + 0.46 cos(\frac{\pi x}{m} ) \f] - * \sa WindowedSincInterpolateImageCosineFunction - */ +/** + * \class HammingWindowFunction + * \brief Window function for sinc interpolation. + * \f[ w(x) = 0.54 + 0.46 cos(\frac{\pi x}{m} ) \f] + * \sa WindowedSincInterpolateImageCosineFunction + */ template< class TInput=double, class TOutput=double > class CosineWindowFunction +{ +public: + void SetRadius(unsigned int radius) + { + m_Radius = radius; + m_Factor = M_PI / ( 2 * static_cast<double>(radius) ); + } + unsigned int GetRadius() const + { + return m_Radius; + }; + double GetFactor() { - public: - void SetRadius(unsigned int radius) - { - m_Radius = radius; - m_Factor = M_PI / ( 2 * static_cast<double>(radius) ); - } - unsigned int GetRadius() const { return m_Radius; }; - double GetFactor() { return m_Factor; }; - - inline TOutput operator()( const TInput & A ) const - { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp = vcl_cos(x * m_Factor ); - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); - } - private: - // Equal to \f$ \frac{\pi}{2 m} \f$ - double m_Factor; - unsigned int m_Radius; + return m_Factor; }; - }//namespace Function + + inline TOutput operator()( const TInput & A ) const + { + double x = static_cast<double>(A); + double px = M_PI * x; + double temp = vcl_cos(x * m_Factor ); + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } +private: + // Equal to \f$ \frac{\pi}{2 m} \f$ + double m_Factor; + unsigned int m_Radius; +}; +}//namespace Function /** @@ -76,53 +82,56 @@ class CosineWindowFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageCosineFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::CosineWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::CosineWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageCosineFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::CosineWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageCosineFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageCosineFunction() {}; + ~WindowedSincInterpolateImageCosineFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageCosineFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::CosineWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageCosineFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageCosineFunction(){}; - ~WindowedSincInterpolateImageCosineFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageCosineFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageCosineFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageFunctionBase.h b/Code/BasicFilters/otbWindowedSincInterpolateImageFunctionBase.h index 1958a4ecbec767b7ae18511abaeb698b99b8023f..4ace8910d79e687c0363e0843b65e165fb8d92b1 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageFunctionBase.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageFunctionBase.h @@ -133,56 +133,56 @@ namespace otb */ template<class TInputImage, class TWindowFunction, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double> class ITK_EXPORT WindowedSincInterpolateImageFunctionBase : -public GenericInterpolateImageFunction< TInputImage, - TWindowFunction, - TBoundaryCondition, - TCoordRep > - { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageFunctionBase Self; - typedef GenericInterpolateImageFunction<TInputImage, TWindowFunction, TBoundaryCondition, TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageFunctionBase, GenericInterpolateImageFunction); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - //typedef typename TWindowFunction FunctionType; - typedef typename Superclass::FunctionType FunctionType; - typedef typename std::vector<double> VectorType; - - /** Compute a resampled profil according to the window size.*/ - void ComputeResampledWindowedSincProfil(); - - /** Positionne le sigma de l'interpolateur */ - void SetRadius(unsigned int sigma); - - protected: - WindowedSincInterpolateImageFunctionBase(); - ~WindowedSincInterpolateImageFunctionBase(); - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - WindowedSincInterpolateImageFunctionBase(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; + public GenericInterpolateImageFunction< TInputImage, + TWindowFunction, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageFunctionBase Self; + typedef GenericInterpolateImageFunction<TInputImage, TWindowFunction, TBoundaryCondition, TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageFunctionBase, GenericInterpolateImageFunction); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + //typedef typename TWindowFunction FunctionType; + typedef typename Superclass::FunctionType FunctionType; + typedef typename std::vector<double> VectorType; + + /** Compute a resampled profil according to the window size.*/ + void ComputeResampledWindowedSincProfil(); + + /** Positionne le sigma de l'interpolateur */ + void SetRadius(unsigned int sigma); + +protected: + WindowedSincInterpolateImageFunctionBase(); + ~WindowedSincInterpolateImageFunctionBase(); + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + WindowedSincInterpolateImageFunctionBase(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // end namespace itk diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageGaussianFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageGaussianFunction.h index d07c5521d6c915edca10dc63390552b88ed426ca..70fd1a032907ed7b4f20cccbbeb5f40592859eb4 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageGaussianFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageGaussianFunction.h @@ -36,26 +36,32 @@ namespace Function */ template< class TInput=double, class TOutput=double> class GaussianWindowFunction +{ +public: + void SetRadius( unsigned int radius) + { + m_Radius = radius; + m_Factor = -2. / ( static_cast<double>(m_Radius * m_Radius) * M_PI ); + } + double GetFactor() + { + return m_Factor; + }; + unsigned int GetRadius() const + { + return m_Radius; + }; + + inline TOutput operator()( const TInput & A ) const { - public: - void SetRadius( unsigned int radius) - { - m_Radius = radius; - m_Factor = -2. / ( static_cast<double>(m_Radius * m_Radius) * M_PI ); - } - double GetFactor() { return m_Factor; }; - unsigned int GetRadius() const { return m_Radius; }; - - inline TOutput operator()( const TInput & A ) const - { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp = vcl_exp( px*px * m_Factor); - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); - } - private: - double m_Factor; - unsigned int m_Radius; + double x = static_cast<double>(A); + double px = M_PI * x; + double temp = vcl_exp( px*px * m_Factor); + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } +private: + double m_Factor; + unsigned int m_Radius; }; }//namespace Function @@ -76,53 +82,56 @@ class GaussianWindowFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageGaussianFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::GaussianWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::GaussianWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageGaussianFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::GaussianWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageGaussianFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageGaussianFunction() {}; + ~WindowedSincInterpolateImageGaussianFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageGaussianFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::GaussianWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageGaussianFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageGaussianFunction(){}; - ~WindowedSincInterpolateImageGaussianFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageGaussianFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageGaussianFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageHammingFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageHammingFunction.h index c4d2c3bdc26886c5628e95320b73f869d3898354..e06020493a0739a37fbb1e300d40c2aa1a4ffe14 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageHammingFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageHammingFunction.h @@ -28,31 +28,37 @@ namespace otb namespace Function { - /** - * \class HammingWindowFunction - * \brief Window function for sinc interpolation. - * \f[ w(x) = 0.54 + 0.46 cos(\frac{\pi x}{m} ) \f] - * \sa WindowedSincInterpolateImageHammingFunction - */ +/** + * \class HammingWindowFunction + * \brief Window function for sinc interpolation. + * \f[ w(x) = 0.54 + 0.46 cos(\frac{\pi x}{m} ) \f] + * \sa WindowedSincInterpolateImageHammingFunction + */ template< class TInput=double, class TOutput=double > class HammingWindowFunction { - public: +public: void SetRadius(unsigned int radius) { m_Radius = radius; m_Factor = M_PI / static_cast<double>(radius); } - unsigned int GetRadius() const { return m_Radius; }; - double GetFactor() { return m_Factor; }; + unsigned int GetRadius() const + { + return m_Radius; + }; + double GetFactor() + { + return m_Factor; + }; inline TOutput operator()( const TInput & A ) const - { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp = 0.54 + 0.46 * vcl_cos(x * m_Factor ); - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); - } + { + double x = static_cast<double>(A); + double px = M_PI * x; + double temp = 0.54 + 0.46 * vcl_cos(x * m_Factor ); + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } private: // Equal to \f$ \frac{\pi}{m} \f$ double m_Factor; @@ -78,53 +84,56 @@ private: */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageHammingFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::HammingWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::HammingWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageHammingFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::HammingWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageHammingFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageHammingFunction() {}; + ~WindowedSincInterpolateImageHammingFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageHammingFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::HammingWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageHammingFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageHammingFunction(){}; - ~WindowedSincInterpolateImageHammingFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageHammingFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageHammingFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageLanczosFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageLanczosFunction.h index 15b0cbca8a25640f964df706663bbd3b117dbcfb..a0cde43ac5c471411ffa13b677a487e17b634bab 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageLanczosFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageLanczosFunction.h @@ -28,47 +28,53 @@ namespace otb namespace Function { - /** - * \class LanczosWindowFunction - * \brief Window function for sinc interpolation. - * \f[ w(x) = \textrm{sinc} ( \frac{x}{m} ) \f] - * Note: Paper referenced in WindowedSincInterpolateImageFunctionBase gives - * an incorrect definition of this window function. - * \sa WindowedSincInterpolateImageLanczosFunction - */ +/** + * \class LanczosWindowFunction + * \brief Window function for sinc interpolation. + * \f[ w(x) = \textrm{sinc} ( \frac{x}{m} ) \f] + * Note: Paper referenced in WindowedSincInterpolateImageFunctionBase gives + * an incorrect definition of this window function. + * \sa WindowedSincInterpolateImageLanczosFunction + */ template< class TInput=double, class TOutput=double > class LanczosWindowFunction +{ +public: + void SetRadius(unsigned int radius) + { + m_Radius = radius; + m_Factor = M_PI / static_cast<double>(radius); + } + unsigned int GetRadius() const + { + return m_Radius; + }; + double GetFactor() + { + return m_Factor; + }; + + inline TOutput operator()( const TInput & A ) const { - public: - void SetRadius(unsigned int radius) + double x = static_cast<double>(A); + double px = M_PI * x; + double temp; + if (x == 0.0) { - m_Radius = radius; - m_Factor = M_PI / static_cast<double>(radius); + temp = 1.0; } - unsigned int GetRadius() const { return m_Radius; }; - double GetFactor() { return m_Factor; }; - - inline TOutput operator()( const TInput & A ) const + else { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp; - if(x == 0.0) - { - temp = 1.0; - } - else - { - double z = m_Factor * x; - temp = vcl_sin(z) / z; - } - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + double z = m_Factor * x; + temp = vcl_sin(z) / z; } - private: - // Equal to \f$ \frac{\pi}{m} \f$ - double m_Factor; - unsigned int m_Radius; - }; + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } +private: + // Equal to \f$ \frac{\pi}{m} \f$ + double m_Factor; + unsigned int m_Radius; +}; }//namespace Function @@ -87,53 +93,56 @@ class LanczosWindowFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageLanczosFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::LanczosWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::LanczosWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageLanczosFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::LanczosWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageLanczosFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageLanczosFunction() {}; + ~WindowedSincInterpolateImageLanczosFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageLanczosFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::LanczosWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageLanczosFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageLanczosFunction(){}; - ~WindowedSincInterpolateImageLanczosFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageLanczosFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageLanczosFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/BasicFilters/otbWindowedSincInterpolateImageWelchFunction.h b/Code/BasicFilters/otbWindowedSincInterpolateImageWelchFunction.h index 627881c611ae979ed80fdab6cc3e372bef9429b3..8ed551703bbc9e2029c79cec76dbf2cd0dadf361 100644 --- a/Code/BasicFilters/otbWindowedSincInterpolateImageWelchFunction.h +++ b/Code/BasicFilters/otbWindowedSincInterpolateImageWelchFunction.h @@ -28,36 +28,42 @@ namespace otb namespace Function { - /** - * \class WelchWindowFunction - * \brief Window function for sinc interpolation. - * \f[ w(x) = 1 - ( \frac{x^2}{m^2} ) \f] - * \sa WindowedSincInterpolateImageWelchFunction - */ +/** + * \class WelchWindowFunction + * \brief Window function for sinc interpolation. + * \f[ w(x) = 1 - ( \frac{x^2}{m^2} ) \f] + * \sa WindowedSincInterpolateImageWelchFunction + */ template< class TInput=double, class TOutput=double > class WelchWindowFunction +{ +public: + void SetRadius(unsigned int radius) + { + m_Radius = radius; + m_Factor = 1 / static_cast<double>(radius * radius); + } + unsigned int GetRadius() const + { + return m_Radius; + }; + double GetFactor() { - public: - void SetRadius(unsigned int radius) - { - m_Radius = radius; - m_Factor = 1 / static_cast<double>(radius * radius); - } - unsigned int GetRadius() const { return m_Radius; }; - double GetFactor() { return m_Factor; }; - - inline TOutput operator()( const TInput & A ) const - { - double x = static_cast<double>(A); - double px = M_PI * x; - double temp = 1.0 - x * m_Factor * x; - return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); - } - private: - // Equal to \f$ \frac{1}{m^2} \f$ - double m_Factor; - unsigned int m_Radius; + return m_Factor; }; + + inline TOutput operator()( const TInput & A ) const + { + double x = static_cast<double>(A); + double px = M_PI * x; + double temp = 1.0 - x * m_Factor * x; + return (x == 0.0) ? static_cast<TOutput>(temp) : static_cast<TOutput>(temp * vcl_sin(px) / px); + } +private: + // Equal to \f$ \frac{1}{m^2} \f$ + double m_Factor; + unsigned int m_Radius; +}; }//namespace Function @@ -76,53 +82,56 @@ class WelchWindowFunction */ template<class TInputImage, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep=double, class TInputInterpolator=double, class TOutputInterpolator=double> class ITK_EXPORT WindowedSincInterpolateImageWelchFunction : -public WindowedSincInterpolateImageFunctionBase< TInputImage, - ITK_TYPENAME Function::WelchWindowFunction< TInputInterpolator, TOutputInterpolator>, - TBoundaryCondition, - TCoordRep > + public WindowedSincInterpolateImageFunctionBase< TInputImage, + ITK_TYPENAME Function::WelchWindowFunction< TInputInterpolator, TOutputInterpolator>, + TBoundaryCondition, + TCoordRep > +{ +public: + /** Standard class typedefs. */ + typedef WindowedSincInterpolateImageWelchFunction Self; + typedef WindowedSincInterpolateImageFunctionBase<TInputImage, + ITK_TYPENAME Function::WelchWindowFunction< TInputInterpolator, + TOutputInterpolator>, + TBoundaryCondition, + TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(WindowedSincInterpolateImageWelchFunction, WindowedSincInterpolateImageFunctionBase); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputType OutputType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Superclass typedef inheritance. */ + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef typename Superclass::IteratorType IteratorType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + +protected: + WindowedSincInterpolateImageWelchFunction() {}; + ~WindowedSincInterpolateImageWelchFunction() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard class typedefs. */ - typedef WindowedSincInterpolateImageWelchFunction Self; - typedef WindowedSincInterpolateImageFunctionBase<TInputImage, - ITK_TYPENAME Function::WelchWindowFunction< TInputInterpolator, - TOutputInterpolator>, - TBoundaryCondition, - TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(WindowedSincInterpolateImageWelchFunction, WindowedSincInterpolateImageFunctionBase); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputType OutputType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Superclass typedef inheritance. */ - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef typename Superclass::IteratorType IteratorType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - - protected: - WindowedSincInterpolateImageWelchFunction(){}; - ~WindowedSincInterpolateImageWelchFunction(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const{ Superclass::PrintSelf( os, indent ); }; - - private: - WindowedSincInterpolateImageWelchFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf( os, indent ); }; +private: + WindowedSincInterpolateImageWelchFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + } // end namespace otb diff --git a/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.h b/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.h index a0cbb0e0704dfd56a4b4d20c57d98aa5dc221c59..cab5fc0d6e5b246ce1ecf71adb1e8bd376a22e55 100644 --- a/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.h +++ b/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.h @@ -36,7 +36,7 @@ namespace otb * \ingroup IntensityImageFilters Multithreaded */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > class ITK_EXPORT BinaryFunctorNeighborhoodJoinHistogramImageFilter : public itk::ImageToImageFilter<TInputImage1,TOutputImage> { public: @@ -86,7 +86,10 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -103,9 +106,9 @@ public: typedef itk::ConstNeighborhoodIterator<TInputImage1> - NeighborhoodIteratorType1; + NeighborhoodIteratorType1; typedef itk::ConstNeighborhoodIterator<TInputImage2> - NeighborhoodIteratorType2; + NeighborhoodIteratorType2; typedef typename NeighborhoodIteratorType1::RadiusType RadiusType1; typedef typename NeighborhoodIteratorType2::RadiusType RadiusType2; @@ -121,8 +124,8 @@ public: typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; typedef typename HistogramType::SizeType HistogramSizeType; - /** Sets the histogram size. Note this function must be called before - \c Initialize(). */ + /** Sets the histogram size. Note this function must be called before + \c Initialize(). */ itkSetMacro( HistogramSize, HistogramSizeType ); /** Gets the histogram size. */ @@ -161,7 +164,7 @@ protected: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ); + int threadId ); /** * Pad the inputs requested regions by radius @@ -172,7 +175,7 @@ protected: HistogramType::Pointer m_Histogram; - /** The histogram size. */ + /** The histogram size. */ HistogramSizeType m_HistogramSize; /** The lower bound for samples in the histogram. */ mutable MeasurementVectorType m_LowerBound; @@ -187,7 +190,7 @@ private: FunctorType m_Functor; - /** The padding value. */ + /** The padding value. */ Input1ImagePixelType m_PaddingValue; /** True if those pixels in the fixed image with the same value as the diff --git a/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.txx b/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.txx index e33cd04a578404081975a57b67d41810c7ea3689..1a7f6de8f501284f56ef79cf74c97197220643f9 100644 --- a/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.txx +++ b/Code/ChangeDetection/otbBinaryFunctorNeighborhoodJoinHistogramImageFilter.txx @@ -31,7 +31,7 @@ namespace otb * Constructor */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::BinaryFunctorNeighborhoodJoinHistogramImageFilter() { @@ -39,7 +39,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut m_Radius = 3; m_HistogramSize.Fill(256); m_UsePaddingValue = false; - m_UpperBoundIncreaseFactor = 0.001; + m_UpperBoundIncreaseFactor = 0.001; } @@ -47,7 +47,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput1( const TInputImage1 * image1 ) @@ -61,7 +61,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput2( const TInputImage2 * image2 ) @@ -71,33 +71,33 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > const TInputImage1 * BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GetInput1() { - if(this->GetNumberOfInputs()<1) - { - return 0; - } + if (this->GetNumberOfInputs()<1) + { + return 0; + } return static_cast<const TInputImage1 *>(this->itk::ProcessObject::GetInput(0)); } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > const TInputImage2 * BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GetInput2() { - if(this->GetNumberOfInputs()<2) - { - return 0; - } + if (this->GetNumberOfInputs()<2) + { + return 0; + } return static_cast<const TInputImage2 *>(this->itk::ProcessObject::GetInput(1)); } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GenerateInputRequestedRegion() @@ -106,16 +106,16 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output - Input1ImagePointer inputPtr1 = - const_cast< TInputImage1 * >( this->GetInput1()); - Input2ImagePointer inputPtr2 = - const_cast< TInputImage2 * >( this->GetInput2()); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); + Input1ImagePointer inputPtr1 = + const_cast< TInputImage1 * >( this->GetInput1()); + Input2ImagePointer inputPtr2 = + const_cast< TInputImage2 * >( this->GetInput2()); + typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr1 || !inputPtr2 || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage1::RegionType inputRequestedRegion1, inputRequestedRegion2; @@ -127,11 +127,11 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut // crop the input requested region at the input's largest possible region if ( inputRequestedRegion1.Crop(inputPtr1->GetLargestPossibleRegion())) - { + { inputPtr1->SetRequestedRegion( inputRequestedRegion1 ); - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -142,18 +142,18 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << this->GetNameOfClass() - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region of image 1."); e.SetDataObject(inputPtr1); throw e; - } + } if ( inputRequestedRegion2.Crop(inputPtr2->GetLargestPossibleRegion())) - { + { inputPtr2->SetRequestedRegion( inputRequestedRegion2 ); - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -164,12 +164,12 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << this->GetNameOfClass() - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region of image 1."); e.SetDataObject(inputPtr2); throw e; - } + } return; } @@ -178,7 +178,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut * Initialize the histogram */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::HistogramType::Pointer BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> @@ -186,55 +186,55 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut { // Calculate min and max image values in input1 image. Input1ImageConstPointer pInput1Image - = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); + = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); Input1ImagePixelType minInput1, maxInput1; itk::ImageRegionConstIterator<Input1ImageType> fiIt(pInput1Image, - pInput1Image->GetBufferedRegion()); + pInput1Image->GetBufferedRegion()); fiIt.GoToBegin(); minInput1 = fiIt.Value(); maxInput1 = fiIt.Value(); ++fiIt; while (!fiIt.IsAtEnd()) - { + { Input1ImagePixelType value = fiIt.Value(); if (value < minInput1) - { + { minInput1 = value; - } + } else if (value > maxInput1) - { + { maxInput1 = value; - } + } ++fiIt; - } + } // Calculate min and max image values in input2 image. - Input2ImageConstPointer pInput2Image - = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); + Input2ImageConstPointer pInput2Image + = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); Input2ImagePixelType minInput2, maxInput2; itk::ImageRegionConstIterator<Input2ImageType> miIt(pInput2Image, - pInput2Image->GetBufferedRegion()); + pInput2Image->GetBufferedRegion()); miIt.GoToBegin(); minInput2 = miIt.Value(); maxInput2 = miIt.Value(); ++miIt; while (!miIt.IsAtEnd()) - { + { Input2ImagePixelType value = miIt.Value(); if (value < minInput2) - { + { minInput2 = value; - } + } else if (value > maxInput2) - { + { maxInput2 = value; - } - ++miIt; } + ++miIt; + } // Initialize the upper and lower bounds of the histogram. m_LowerBound[0] = minInput1; @@ -247,7 +247,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut typedef itk::ImageRegionConstIteratorWithIndex<Input1ImageType> Input1IteratorType; - typedef itk::ImageRegionConstIteratorWithIndex<Input2ImageType> Input2IteratorType; + typedef itk::ImageRegionConstIteratorWithIndex<Input2ImageType> Input2IteratorType; typename Input1ImageType::RegionType input1Region; typename Input1ImageType::RegionType input2Region; @@ -265,19 +265,19 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1,TInputImage2,TOut ti1.GoToBegin(); ti2.GoToBegin(); while (!ti1.IsAtEnd() && !ti2.IsAtEnd()) - { + { - typename HistogramType::MeasurementVectorType sample; - sample[0] = ti1.Get(); - sample[1] = ti2.Get(); - if(sample[0]!=itk::NumericTraits<Input1ImagePixelType>::Zero && - sample[1]!=itk::NumericTraits<Input2ImagePixelType>::Zero) - histogram->IncreaseFrequency(sample, 1); + typename HistogramType::MeasurementVectorType sample; + sample[0] = ti1.Get(); + sample[1] = ti2.Get(); + if (sample[0]!=itk::NumericTraits<Input1ImagePixelType>::Zero && + sample[1]!=itk::NumericTraits<Input2ImagePixelType>::Zero) + histogram->IncreaseFrequency(sample, 1); ++ti1; ++ti2; - } + } return histogram; @@ -308,9 +308,9 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1, TInputImage2, TO // ImageToJoinHistogramImageFilter::GetInput(int) always returns a pointer to a // TInputImage1 so it cannot be used for the second input. Input1ImageConstPointer inputPtr1 - = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); + = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); Input2ImageConstPointer inputPtr2 - = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); + = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); OutputImagePointer outputPtr = this->GetOutput(0); @@ -343,7 +343,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1, TInputImage2, TO // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit1=faceList1.begin(), fit2=faceList2.begin(); fit1 != faceList1.end(), fit2 != faceList2.end(); ++fit1, ++fit2) - { + { neighInputIt1 = itk::ConstNeighborhoodIterator<TInputImage1>(r1, inputPtr1, *fit1); neighInputIt2 = itk::ConstNeighborhoodIterator<TInputImage2>(r1, inputPtr2, *fit2); outputIt = itk::ImageRegionIterator<TOutputImage>(outputPtr, outputRegionForThread); @@ -355,7 +355,7 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1, TInputImage2, TO neighInputIt2.GoToBegin(); while ( ! outputIt.IsAtEnd() ) - { + { outputIt.Set( m_Functor( neighInputIt1, neighInputIt2, histogram ) ); @@ -363,8 +363,8 @@ BinaryFunctorNeighborhoodJoinHistogramImageFilter<TInputImage1, TInputImage2, TO ++neighInputIt2; ++outputIt; progress.CompletedPixel(); - } } + } diff --git a/Code/ChangeDetection/otbCBAMIChangeDetector.h b/Code/ChangeDetection/otbCBAMIChangeDetector.h index e8fab99223156b27fb15187619a78d1a287fb4d6..11a35903842f11016bae16564cb6752af332154f 100644 --- a/Code/ChangeDetection/otbCBAMIChangeDetector.h +++ b/Code/ChangeDetection/otbCBAMIChangeDetector.h @@ -55,7 +55,8 @@ namespace otb #define epsilon 0.01 -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class CBAMI @@ -76,13 +77,13 @@ public: VectorType vecA; VectorType vecB; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { vecA.push_back(static_cast<TOutput>(itA.GetPixel(pos))); vecB.push_back(static_cast<TOutput>(itB.GetPixel(pos))); - } + } normalizeInPlace(vecA); normalizeInPlace(vecB); @@ -99,30 +100,31 @@ protected: IteratorType itx; - for( itx = vx.begin(); itx < vx.end(); itx++) - { + for ( itx = vx.begin(); itx < vx.end(); itx++) + { Ex += (*itx); - } + } Ex /= (vx.size()); TOutput Vx = 0.0; - for( itx = vx.begin(); itx < vx.end(); itx++) - { - Vx += vcl_pow((*itx)-Ex,2); - } + for ( itx = vx.begin(); itx < vx.end(); itx++) + { + Vx += vcl_pow((*itx)-Ex,2); + } Vx /= (vx.size()); - for( itx = vx.begin(); itx < vx.end(); itx++) - { + for ( itx = vx.begin(); itx < vx.end(); itx++) + { (*itx) = ((*itx)-Ex)/vcl_sqrt(Vx); - } + } } - inline TOutput Exyc(VectorType vx, VectorType vy){ + inline TOutput Exyc(VectorType vx, VectorType vy) + { TOutput Exy = 0.0; TOutput Ex = 0.0; @@ -131,13 +133,13 @@ protected: IteratorType itx; IteratorType ity; - for( itx = vx.begin(), ity = vy.begin(); itx < vx.end(); itx++, ity++) - { + for ( itx = vx.begin(), ity = vy.begin(); itx < vx.end(); itx++, ity++) + { //Ex += (*itx); //Ey += (*ity); Exy += (*itx)*(*ity); - } + } //Ex /= (vx.size()); //Ey /= (vy.size()); @@ -146,7 +148,8 @@ protected: return Exy-Ex*Ey; } - inline TOutput Exyztc(VectorType vx, VectorType vy, VectorType vz, VectorType vt){ + inline TOutput Exyztc(VectorType vx, VectorType vy, VectorType vz, VectorType vt) + { TOutput Exyzt = 0.0; @@ -173,16 +176,16 @@ protected: IteratorType itz; IteratorType itt; - for( itx = vx.begin(), - ity = vy.begin(), - itz = vz.begin(), - itt = vt.begin(); - itx < vx.end(); - itx++, - ity++, - itz++, - itt++) - { + for ( itx = vx.begin(), + ity = vy.begin(), + itz = vz.begin(), + itt = vt.begin(); + itx < vx.end(); + itx++, + ity++, + itz++, + itt++) + { //Ex += (*itx); //Ey += (*ity); //Ez += (*itz); @@ -202,7 +205,7 @@ protected: Exyzt += (*itx)*(*ity)*(*itz)*(*itt); - } + } /*Ex /= (vx.size()); Ey /= (vx.size()); @@ -223,8 +226,8 @@ protected: TOutput result = Exyzt - Exyz*Et- Exyt*Ez- Exzt*Ey- Eyzt*Ex + - Exy*Ez*Et + Exz*Et*Ey + Ext*Ey*Ez + Eyz*Et*Ex + Eyt*Ex*Ez + Ezt*Ex*Ey - - 3*Ex*Ey*Ez*Et; + Exy*Ez*Et + Exz*Et*Ey + Ext*Ey*Ez + Eyz*Et*Ex + Eyt*Ex*Ez + Ezt*Ex*Ey - + 3*Ex*Ey*Ez*Et; return result; } @@ -277,19 +280,19 @@ protected: TOutput termeR = 0.0; TOutput termeQ = 0.0; - for( iti = donnees.begin(); iti < donnees.end(); iti++ ) - for( itj = donnees.begin(); itj < donnees.end(); itj++ ) - { - if(iti != itj) - termeR += vcl_pow(Rxy((*iti),(*itj)),2); - - for( itk = donnees.begin(); itk < donnees.end(); itk++ ) - for( itl = donnees.begin(); itl < donnees.end(); itl++ ) + for ( iti = donnees.begin(); iti < donnees.end(); iti++ ) + for ( itj = donnees.begin(); itj < donnees.end(); itj++ ) { - if((iti != itj) || (iti != itk) || (iti != itl)) - termeQ += vcl_pow( Qxijkl((*iti),(*itj),(*itk),(*itl)),2); + if (iti != itj) + termeR += vcl_pow(Rxy((*iti),(*itj)),2); + + for ( itk = donnees.begin(); itk < donnees.end(); itk++ ) + for ( itl = donnees.begin(); itl < donnees.end(); itl++ ) + { + if ((iti != itj) || (iti != itk) || (iti != itl)) + termeQ += vcl_pow( Qxijkl((*iti),(*itj),(*itk),(*itl)),2); + } } - } return 1.0/4.0*termeR + 1.0/48.0*termeQ; @@ -301,22 +304,22 @@ protected: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT CBAMIChangeDetector : - public BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::CBAMI< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::CBAMI< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef CBAMIChangeDetector Self; typedef BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::CBAMI< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::CBAMI< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/ChangeDetection/otbCommandProgressUpdate.txx b/Code/ChangeDetection/otbCommandProgressUpdate.txx index e5fa6e7db5f94f4082d303bd66368e8b43ba22dd..d5907cafe7b72e77fce7a595ed9247000c1365f9 100644 --- a/Code/ChangeDetection/otbCommandProgressUpdate.txx +++ b/Code/ChangeDetection/otbCommandProgressUpdate.txx @@ -28,35 +28,35 @@ namespace otb template <class TFilter> void CommandProgressUpdate<TFilter>::Execute(itk::Object *caller, const itk::EventObject & event) { - Execute( (const itk::Object *)caller, event); - } + Execute( (const itk::Object *)caller, event); +} template <class TFilter> void CommandProgressUpdate<TFilter>::Execute(const itk::Object * object, const itk::EventObject & event) { - FilterPointer filter = - dynamic_cast< FilterPointer >( object ); - if( typeid( event ) != typeid( itk::ProgressEvent ) ) - { - return; - } + FilterPointer filter = + dynamic_cast< FilterPointer >( object ); + if ( typeid( event ) != typeid( itk::ProgressEvent ) ) + { + return; + } - int factor = 160; + int factor = 160; - int val = int(filter->GetProgress()*factor); + int val = int(filter->GetProgress()*factor); - if((val%2) == 0) + if ((val%2) == 0) { - std::cout << "|"; - std::cout.flush(); + std::cout << "|"; + std::cout.flush(); } - if(val == factor) + if (val == factor) { - std::cout << ">"; - std::cout.flush(); + std::cout << ">"; + std::cout.flush(); } - } +} diff --git a/Code/ChangeDetection/otbCorrelationChangeDetector.h b/Code/ChangeDetection/otbCorrelationChangeDetector.h index 5479267983068105f85dd763a939cfe1acefb53c..d4c723e7c96da1e332e330f935bbf9505ec9a28e 100644 --- a/Code/ChangeDetection/otbCorrelationChangeDetector.h +++ b/Code/ChangeDetection/otbCorrelationChangeDetector.h @@ -46,7 +46,8 @@ namespace otb * * \ingroup IntensityImageFilters Multithreaded */ -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class CrossCorrelation @@ -61,14 +62,14 @@ public: TOutput meanA = itk::NumericTraits<TOutput>::Zero; TOutput meanB = itk::NumericTraits<TOutput>::Zero; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { meanA += static_cast<TOutput>(itA.GetPixel(pos)); meanB += static_cast<TOutput>(itB.GetPixel(pos)); - } + } meanA /= itA.Size(); meanB /= itB.Size(); @@ -76,30 +77,30 @@ public: TOutput varA = itk::NumericTraits<TOutput>::Zero; TOutput varB = itk::NumericTraits<TOutput>::Zero; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { varA += static_cast<TOutput>( vcl_pow( static_cast<double>(itA.GetPixel(pos))-static_cast<double>(meanA),static_cast<double>(2.0))); varB += static_cast<TOutput>( vcl_pow( static_cast<double>(itB.GetPixel(pos))-static_cast<double>(meanB),static_cast<double>(2.0))); - } + } varA /= itA.Size(); varB /= itB.Size(); TOutput crossCorrel = itk::NumericTraits<TOutput>::Zero; - if(varA!= itk::NumericTraits<TOutput>::Zero && varB!= itk::NumericTraits<TOutput>::Zero) + if (varA!= itk::NumericTraits<TOutput>::Zero && varB!= itk::NumericTraits<TOutput>::Zero) { - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { - crossCorrel += (static_cast<TOutput>(itA.GetPixel(pos))-meanA)*(static_cast<TOutput>(itB.GetPixel(pos))-meanB)/(itA.Size()*vcl_sqrt(varA*varB)); - } - } - else if(varA==itk::NumericTraits<TOutput>::Zero && varB==itk::NumericTraits<TOutput>::Zero) + for (unsigned long pos = 0; pos< itA.Size(); ++pos) { - crossCorrel = itk::NumericTraits<TOutput>::One; + crossCorrel += (static_cast<TOutput>(itA.GetPixel(pos))-meanA)*(static_cast<TOutput>(itB.GetPixel(pos))-meanB)/(itA.Size()*vcl_sqrt(varA*varB)); } + } + else if (varA==itk::NumericTraits<TOutput>::Zero && varB==itk::NumericTraits<TOutput>::Zero) + { + crossCorrel = itk::NumericTraits<TOutput>::One; + } return static_cast<TOutput>( itk::NumericTraits<TOutput>::One - crossCorrel ); } }; @@ -107,22 +108,22 @@ public: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT CorrelationChangeDetector : - public BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::CrossCorrelation< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::CrossCorrelation< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef CorrelationChangeDetector Self; typedef BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::CrossCorrelation< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::CrossCorrelation< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/ChangeDetection/otbJoinHistogramMIImageFilter.h b/Code/ChangeDetection/otbJoinHistogramMIImageFilter.h index 4405477eac660e91b4f1c71d4d88e004a55342ae..9843268ebd80577269b3e3d4c4ba3ef750938333 100644 --- a/Code/ChangeDetection/otbJoinHistogramMIImageFilter.h +++ b/Code/ChangeDetection/otbJoinHistogramMIImageFilter.h @@ -48,7 +48,8 @@ namespace otb * * \ingroup IntensityImageFilters Multithreaded */ -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class JoinHistogramMI @@ -64,115 +65,115 @@ public: TOutput jointEntropy = itk::NumericTraits<TOutput>::Zero; HistogramFrequencyType totalFreq = histogram->GetTotalFrequency(); -/* for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { - double value = static_cast<double>(itA.GetPixel(pos)); - - unsigned int bin = - HistogramFrequencyType freq = histogram.GetFrequency(, 0); - if (freq > 0) - { - entropyX += freq*vcl_log(freq); - } - } + /* for(unsigned long pos = 0; pos< itA.Size(); ++pos) + { + double value = static_cast<double>(itA.GetPixel(pos)); + + unsigned int bin = + HistogramFrequencyType freq = histogram.GetFrequency(, 0); + if (freq > 0) + { + entropyX += freq*vcl_log(freq); + } + } + + entropyX = -entropyX/static_cast<TOutput>(totalFreq) + vcl_log(totalFreq); + + for (unsigned int i = 0; i < this->GetHistogramSize()[1]; i++) + { + HistogramFrequencyType freq = histogram.GetFrequency(i, 1); + if (freq > 0) + { + entropyY += freq*vcl_log(freq); + } + } + + entropyY = -entropyY/static_cast<TOutput>(totalFreq) + vcl_log(totalFreq); + + HistogramIteratorType it = histogram.Begin(); + HistogramIteratorType end = histogram.End(); + while (it != end) + { + HistogramFrequencyType freq = it.GetFrequency(); + if (freq > 0) + { + jointEntropy += freq*vcl_log(freq); + } + ++it; + } + + jointEntropy = -jointEntropy/static_cast<TOutput>(totalFreq) + + vcl_log(totalFreq); + + return entropyX + entropyY - jointEntropy;*/ - entropyX = -entropyX/static_cast<TOutput>(totalFreq) + vcl_log(totalFreq); - for (unsigned int i = 0; i < this->GetHistogramSize()[1]; i++) + typename HistogramType::MeasurementVectorType sample; + for (unsigned long pos = 0; pos< itA.Size(); ++pos) { - HistogramFrequencyType freq = histogram.GetFrequency(i, 1); - if (freq > 0) - { - entropyY += freq*vcl_log(freq); - } - } + double valueA = static_cast<double>(itA.GetPixel(pos)); + double valueB = static_cast<double>(itB.GetPixel(pos)); - entropyY = -entropyY/static_cast<TOutput>(totalFreq) + vcl_log(totalFreq); + sample[0] = valueA; + sample[1] = valueB; - HistogramIteratorType it = histogram.Begin(); - HistogramIteratorType end = histogram.End(); - while (it != end) - { - HistogramFrequencyType freq = it.GetFrequency(); + + HistogramFrequencyType freq = histogram->GetFrequency( + histogram->GetIndex(sample)); if (freq > 0) { jointEntropy += freq*vcl_log(freq); } - ++it; - } - - jointEntropy = -jointEntropy/static_cast<TOutput>(totalFreq) + - vcl_log(totalFreq); - - return entropyX + entropyY - jointEntropy;*/ - - typename HistogramType::MeasurementVectorType sample; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { - double valueA = static_cast<double>(itA.GetPixel(pos)); - double valueB = static_cast<double>(itB.GetPixel(pos)); - - sample[0] = valueA; - sample[1] = valueB; - - - HistogramFrequencyType freq = histogram->GetFrequency( - histogram->GetIndex(sample)); - if (freq > 0) - { - jointEntropy += freq*vcl_log(freq); } - } - jointEntropy = -jointEntropy/static_cast<TOutput>(totalFreq) + - vcl_log(totalFreq); + vcl_log(totalFreq); return jointEntropy; -/* TOutput meanA = 0.0; - TOutput meanB = 0.0; + /* TOutput meanA = 0.0; + TOutput meanB = 0.0; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for(unsigned long pos = 0; pos< itA.Size(); ++pos) + { - meanA += static_cast<TOutput>(itA.GetPixel(pos)); - meanB += static_cast<TOutput>(itB.GetPixel(pos)); + meanA += static_cast<TOutput>(itA.GetPixel(pos)); + meanB += static_cast<TOutput>(itB.GetPixel(pos)); - }*/ + }*/ return static_cast<TOutput>( 0 ); } -/* void SetHistogram(HistogramType* histo) - { - m_Histogram = histo; - } + /* void SetHistogram(HistogramType* histo) + { + m_Histogram = histo; + } -protected: - HistogramType::Pointer m_Histogram;*/ + protected: + HistogramType::Pointer m_Histogram;*/ }; } template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT JoinHistogramMIImageFilter : - public BinaryFunctorNeighborhoodJoinHistogramImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::JoinHistogramMI< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodJoinHistogramImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::JoinHistogramMI< + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef JoinHistogramMIImageFilter Self; typedef BinaryFunctorNeighborhoodJoinHistogramImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::JoinHistogramMI< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::JoinHistogramMI< + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.h b/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.h index 73da40771cc0c12c705c39cec11591a5abe1df3f..ec5276aadfe44f8c19ac003db294c497a951fdba 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.h +++ b/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.h @@ -23,63 +23,78 @@ #include "itkVariableLengthVector.h" #include "otbBinaryFunctorNeighborhoodImageFilter.h" -namespace otb { +namespace otb +{ - /** \class CumulantsForEdgeworth - * \brief Helper class for KullbackLeiblerDistanceImageFilter. Please refer to KullbackLeiblerDistanceImageFilter. - * - */ +/** \class CumulantsForEdgeworth + * \brief Helper class for KullbackLeiblerDistanceImageFilter. Please refer to KullbackLeiblerDistanceImageFilter. + * + */ template < class TInput > class CumulantsForEdgeworth { - public : - CumulantsForEdgeworth ( const TInput & input ); - CumulantsForEdgeworth ( const itk::Image< typename TInput::ImageType::PixelType, 1 > * input ); - virtual ~CumulantsForEdgeworth () { } - - /** KL Divergence calculation */ - template <class TInput2> - double Divergence ( const CumulantsForEdgeworth<TInput2> & cumulants ); - - inline double GetMean () const { return this->fMean; } - inline double GetVariance () const { return this->fVariance; } - inline double GetSkewness () const { return this->fSkewness; } - inline double GetKurtosis () const { return this->fKurtosis; } - - protected : - - /** Moment estimation from intial neighborhood */ - int MakeSumAndMoments ( const TInput & input ); - /** Moment estimation from raw data */ - int MakeSumAndMoments ( const itk::Image< typename TInput::ImageType::PixelType, 1 > * input ); - /** transformation moment -> cumulants (for Edgeworth) */ - int MakeCumulants(); - - double fSum0, fSum1, fSum2, fSum3, fSum4; - double fMu1, fMu2, fMu3, fMu4; - double fMean, fVariance, fSkewness, fKurtosis; +public : + CumulantsForEdgeworth ( const TInput & input ); + CumulantsForEdgeworth ( const itk::Image< typename TInput::ImageType::PixelType, 1 > * input ); + virtual ~CumulantsForEdgeworth () { } + + /** KL Divergence calculation */ + template <class TInput2> + double Divergence ( const CumulantsForEdgeworth<TInput2> & cumulants ); + + inline double GetMean () const + { + return this->fMean; + } + inline double GetVariance () const + { + return this->fVariance; + } + inline double GetSkewness () const + { + return this->fSkewness; + } + inline double GetKurtosis () const + { + return this->fKurtosis; + } + +protected : + + /** Moment estimation from intial neighborhood */ + int MakeSumAndMoments ( const TInput & input ); + /** Moment estimation from raw data */ + int MakeSumAndMoments ( const itk::Image< typename TInput::ImageType::PixelType, 1 > * input ); + /** transformation moment -> cumulants (for Edgeworth) */ + int MakeCumulants(); + + double fSum0, fSum1, fSum2, fSum3, fSum4; + double fMu1, fMu2, fMu3, fMu4; + double fMean, fVariance, fSkewness, fKurtosis; }; -namespace Functor { - /** \class KullbackLeiblerDistance - * \brief Functor for KullbackLeiblerDistanceImageFilter. Please refer to KullbackLeiblerDistanceImageFilter. - * - */ - template < class TInput1, class TInput2, class TOutput > - class KullbackLeiblerDistance +namespace Functor +{ +/** \class KullbackLeiblerDistance + * \brief Functor for KullbackLeiblerDistanceImageFilter. Please refer to KullbackLeiblerDistanceImageFilter. + * + */ +template < class TInput1, class TInput2, class TOutput > +class KullbackLeiblerDistance +{ +public : + KullbackLeiblerDistance () { } + virtual ~KullbackLeiblerDistance () { } + TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ) { - public : - KullbackLeiblerDistance () { } - virtual ~KullbackLeiblerDistance () { } - TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ) { - CumulantsForEdgeworth<TInput1> cum1 ( it1 ); - CumulantsForEdgeworth<TInput2> cum2 ( it2 ); - return static_cast<TOutput> ( cum1.Divergence( cum2 ) - + cum2.Divergence( cum1 ) ); - } - }; + CumulantsForEdgeworth<TInput1> cum1 ( it1 ); + CumulantsForEdgeworth<TInput2> cum2 ( it2 ); + return static_cast<TOutput> ( cum1.Divergence( cum2 ) + + cum2.Divergence( cum1 ) ); + } +}; } // Functor @@ -114,36 +129,36 @@ namespace Functor { */ template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT KullbackLeiblerDistanceImageFilter : - public otb::BinaryFunctorNeighborhoodImageFilter< + public otb::BinaryFunctorNeighborhoodImageFilter< TInputImage1,TInputImage2,TOutputImage, Functor::KullbackLeiblerDistance< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> > + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> > { - public: - /** Standard class typedefs. */ - typedef KullbackLeiblerDistanceImageFilter Self; - typedef otb::BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::KullbackLeiblerDistance< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> - > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - protected: - KullbackLeiblerDistanceImageFilter() {} - virtual ~KullbackLeiblerDistanceImageFilter() {} - - private: - KullbackLeiblerDistanceImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +public: + /** Standard class typedefs. */ + typedef KullbackLeiblerDistanceImageFilter Self; + typedef otb::BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::KullbackLeiblerDistance< + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> + > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + +protected: + KullbackLeiblerDistanceImageFilter() {} + virtual ~KullbackLeiblerDistanceImageFilter() {} + +private: + KullbackLeiblerDistanceImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented }; diff --git a/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.txx b/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.txx index a9c449cb06cf74e01c7987b662e51f351cd44af1..774ec97a8a863777d75a82c7e26a11ac7f195990 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.txx +++ b/Code/ChangeDetection/otbKullbackLeiblerDistanceImageFilter.txx @@ -26,7 +26,8 @@ #include "otbMacro.h" -namespace otb { +namespace otb +{ /* ******************************************************************* * CumulantsForEdgeworth @@ -96,11 +97,11 @@ CumulantsForEdgeworth< TInput > double tmp = cum1 - tilde_cum1 + sqrt_cum2; double resu = cum3_2 / ( 12.0 * cum2_3 ) - + ( log( tilde_cum2 / cum2 ) - - 1.0 + tmp * tmp / tilde_cum2 ) / 2.0 - - ( tilde_cum3 * a1 / 6.0 + tilde_cum4 * a2 / 24.0 + tilde_cum3_2 * a3 / 72.0 ) - - tilde_cum3_2 * ( c6 - 6.0 * c4 / cum2 + 9.0 * c2 / tilde_cum2_2 ) / 72.0 - - 10.0 * cum3 * tilde_cum3 * ( cum1 - tilde_cum1 ) * ( cum2 - tilde_cum2 ) / tilde_cum2_6; + + ( log( tilde_cum2 / cum2 ) + - 1.0 + tmp * tmp / tilde_cum2 ) / 2.0 + - ( tilde_cum3 * a1 / 6.0 + tilde_cum4 * a2 / 24.0 + tilde_cum3_2 * a3 / 72.0 ) + - tilde_cum3_2 * ( c6 - 6.0 * c4 / cum2 + 9.0 * c2 / tilde_cum2_2 ) / 72.0 + - 10.0 * cum3 * tilde_cum3 * ( cum1 - tilde_cum1 ) * ( cum2 - tilde_cum2 ) / tilde_cum2_6; return resu < 0.0 ? 0.0 : resu; } diff --git a/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.h b/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.h index 26c875743c60ae4a9b2a5b200a4023784bf6f353..9f897530d7b7242ffe2f0011510e0d23d577452a 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.h +++ b/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.h @@ -29,83 +29,91 @@ #include "otbBinaryFunctorNeighborhoodVectorImageFilter.h" -namespace otb { +namespace otb +{ - /** \class CumulantsForEdgeworthProfile - * \brief Helper class for KullbackLeiblerProfileImageFilter. Please refer to KullbackLeibleProfileImageFilter. - * - */ +/** \class CumulantsForEdgeworthProfile + * \brief Helper class for KullbackLeiblerProfileImageFilter. Please refer to KullbackLeibleProfileImageFilter. + * + */ template <class TInput> class CumulantsForEdgeworthProfile { - public : - typedef itk::Vector<double,4> CumulantType; - typedef std::vector< CumulantType > CumulantSet; - typedef CumulantSet::iterator Iterator; - - CumulantsForEdgeworthProfile ( const TInput & input, std::vector< itk::Array2D<int> > & mask ); - virtual ~CumulantsForEdgeworthProfile () { } - - // Kullback-Leibler Profile - template <class TInput2> - itk::VariableLengthVector<double> KL_profile ( CumulantsForEdgeworthProfile<TInput2> & cumulants ); - // Kullback-Leibler divergence at a given scale - double KL_profile ( const CumulantType & cumulants1, const CumulantType & cumulants2 ); - // Access to data - inline CumulantType & GetCumulantAtScale( int i ) { return this->fCum[i]; } - - // debug - int m_debug; - - protected : - - // Estimation des moments � partir de voisinnages emboit�s - int MakeSumAndMoments ( const TInput & input, std::vector< itk::Array2D<int> > & mask ); - // Estimation des moments � partir de la petite taille de fenetre - int InitSumAndMoments ( const TInput & input, itk::Array2D<int> & mask ); - // - int ReInitSumAndMoments ( const TInput & input, itk::Array2D<int> & mask, int level ); - // transformation moment -> cumulants (pour Edgeworth) - int MakeCumulants(); - - // Attributs internes � la classe - double fSum0, fSum1, fSum2, fSum3, fSum4; - CumulantSet fMu; - CumulantSet fCum; - - private : - CumulantsForEdgeworthProfile (); // Not implemented - CumulantsForEdgeworthProfile ( const TInput & input ); // Not implemented +public : + typedef itk::Vector<double,4> CumulantType; + typedef std::vector< CumulantType > CumulantSet; + typedef CumulantSet::iterator Iterator; + + CumulantsForEdgeworthProfile ( const TInput & input, std::vector< itk::Array2D<int> > & mask ); + virtual ~CumulantsForEdgeworthProfile () { } + + // Kullback-Leibler Profile + template <class TInput2> + itk::VariableLengthVector<double> KL_profile ( CumulantsForEdgeworthProfile<TInput2> & cumulants ); + // Kullback-Leibler divergence at a given scale + double KL_profile ( const CumulantType & cumulants1, const CumulantType & cumulants2 ); + // Access to data + inline CumulantType & GetCumulantAtScale( int i ) + { + return this->fCum[i]; + } + + // debug + int m_debug; + +protected : + + // Estimation des moments � partir de voisinnages emboit�s + int MakeSumAndMoments ( const TInput & input, std::vector< itk::Array2D<int> > & mask ); + // Estimation des moments � partir de la petite taille de fenetre + int InitSumAndMoments ( const TInput & input, itk::Array2D<int> & mask ); + // + int ReInitSumAndMoments ( const TInput & input, itk::Array2D<int> & mask, int level ); + // transformation moment -> cumulants (pour Edgeworth) + int MakeCumulants(); + + // Attributs internes � la classe + double fSum0, fSum1, fSum2, fSum3, fSum4; + CumulantSet fMu; + CumulantSet fCum; + +private : + CumulantsForEdgeworthProfile (); // Not implemented + CumulantsForEdgeworthProfile ( const TInput & input ); // Not implemented }; -namespace Functor { - /** \class KullbackLeiblerProfile - * \brief Functor for KullbackLeiblerProfileImageFilter. Please refer to KullbackLeiblerProfileImageFilter. - * - */ - template< class TInput1, class TInput2, class TOutput > - class KullbackLeiblerProfile +namespace Functor +{ +/** \class KullbackLeiblerProfile + * \brief Functor for KullbackLeiblerProfileImageFilter. Please refer to KullbackLeiblerProfileImageFilter. + * + */ +template< class TInput1, class TInput2, class TOutput > +class KullbackLeiblerProfile +{ +public : + KullbackLeiblerProfile (); + virtual ~KullbackLeiblerProfile () { } + // Gives the radius min and max of neighborhood + void SetRadius ( const unsigned char & min, const unsigned char & max ); + unsigned char GetRadiusMin(void); + unsigned char GetRadiusMax(void); + // Gives the size of the profile + int GetNumberOfComponentsPerPixel() const { - public : - KullbackLeiblerProfile (); - virtual ~KullbackLeiblerProfile () { } - // Gives the radius min and max of neighborhood - void SetRadius ( const unsigned char & min, const unsigned char & max ); - unsigned char GetRadiusMin(void); - unsigned char GetRadiusMax(void); - // Gives the size of the profile - int GetNumberOfComponentsPerPixel() const { return m_mask.size(); } - // functor - TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ); - protected : - // Make the set of masks to play the increase in window size - void MakeMultiscaleProfile (); - // Internal attributes - unsigned char m_RadiusMin; - unsigned char m_RadiusMax; - std::vector< itk::Array2D<int> > m_mask; - }; + return m_mask.size(); + } + // functor + TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ); +protected : + // Make the set of masks to play the increase in window size + void MakeMultiscaleProfile (); + // Internal attributes + unsigned char m_RadiusMin; + unsigned char m_RadiusMax; + std::vector< itk::Array2D<int> > m_mask; +}; } // Functor /** \class KullbackLeiblerProfileImageFilter @@ -140,36 +148,36 @@ namespace Functor { */ template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT KullbackLeiblerProfileImageFilter : - public BinaryFunctorNeighborhoodVectorImageFilter< + public BinaryFunctorNeighborhoodVectorImageFilter< TInputImage1,TInputImage2,TOutputImage, Functor::KullbackLeiblerProfile< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> > + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> > { - public: - /** Standard class typedefs. */ - typedef KullbackLeiblerProfileImageFilter Self; - typedef /*typename*/ BinaryFunctorNeighborhoodVectorImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::KullbackLeiblerProfile< - typename itk::ConstNeighborhoodIterator<TInputImage1>, - typename itk::ConstNeighborhoodIterator<TInputImage2>, - typename TOutputImage::PixelType> - > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - protected: - KullbackLeiblerProfileImageFilter() {} - virtual ~KullbackLeiblerProfileImageFilter() {} - - private: - KullbackLeiblerProfileImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +public: + /** Standard class typedefs. */ + typedef KullbackLeiblerProfileImageFilter Self; + typedef /*typename*/ BinaryFunctorNeighborhoodVectorImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::KullbackLeiblerProfile< + typename itk::ConstNeighborhoodIterator<TInputImage1>, + typename itk::ConstNeighborhoodIterator<TInputImage2>, + typename TOutputImage::PixelType> + > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + +protected: + KullbackLeiblerProfileImageFilter() {} + virtual ~KullbackLeiblerProfileImageFilter() {} + +private: + KullbackLeiblerProfileImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented }; diff --git a/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.txx b/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.txx index 9eaa2b9c3417db91f8cd687eaefd61eaf5d2534f..441deb6f90cf084a706abee08d59411009bedb18 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.txx +++ b/Code/ChangeDetection/otbKullbackLeiblerProfileImageFilter.txx @@ -26,7 +26,8 @@ #include "otbKullbackLeiblerProfileImageFilter.h" #include "otbMath.h" -namespace otb { +namespace otb +{ /* ******************************************************************* * Classe CumulantsForEdgeworthProfile @@ -109,11 +110,11 @@ CumulantsForEdgeworthProfile<TInput> double tmp = cum1 - tilde_cum1 + sqrt_cum2; double resu = cum3_2 / ( 12.0 * cum2_3 ) - + ( log( tilde_cum2 / cum2 ) - - 1.0 + tmp * tmp / tilde_cum2 ) / 2.0 - - ( tilde_cum3 * a1 / 6.0 + tilde_cum4 * a2 / 24.0 + tilde_cum3_2 * a3 / 72.0 ) - - tilde_cum3_2 * ( c6 - 6.0 * c4 / cum2 + 9.0 * c2 / tilde_cum2_2 ) / 72.0 - - 10.0 * cum3 * tilde_cum3 * ( cum1 - tilde_cum1 ) * ( cum2 - tilde_cum2 ) / tilde_cum2_6; + + ( log( tilde_cum2 / cum2 ) + - 1.0 + tmp * tmp / tilde_cum2 ) / 2.0 + - ( tilde_cum3 * a1 / 6.0 + tilde_cum4 * a2 / 24.0 + tilde_cum3_2 * a3 / 72.0 ) + - tilde_cum3_2 * ( c6 - 6.0 * c4 / cum2 + 9.0 * c2 / tilde_cum2_2 ) / 72.0 + - 10.0 * cum3 * tilde_cum3 * ( cum1 - tilde_cum1 ) * ( cum2 - tilde_cum2 ) / tilde_cum2_6; if ( vnl_math_isnan( resu ) || resu > 1e3 ) resu = 1e3; @@ -160,7 +161,7 @@ CumulantsForEdgeworthProfile<TInput> // for ( unsigned long i = 0; i < input.Size(); i++ ) for (i = 0; i < mask.rows(); i++ ) - { + { for ( j = 0; j < mask.cols(); j++ ) { // std::cerr << "(" << i << "," << j << ") k=" << k << " "; @@ -179,7 +180,7 @@ CumulantsForEdgeworthProfile<TInput> k++; } } - if ( fSum0 == 0.0 ) + if ( fSum0 == 0.0 ) return 1; double mu1, mu2; @@ -203,7 +204,7 @@ CumulantsForEdgeworthProfile<TInput> // for ( unsigned long i = 0; i < input.Size(); i++ ) for ( i = 0; i < mask.rows(); i++ ) - { + { for ( j = 0; j < mask.cols(); j++ ) { if ( mask.get(i,j) == 1 ) @@ -216,7 +217,7 @@ CumulantsForEdgeworthProfile<TInput> } else x++; - } + } } mu3 /= fSum0; @@ -244,10 +245,10 @@ CumulantsForEdgeworthProfile<TInput> fMu[level].Fill(0.0); // mise a jour du comptage... double sum0 = 0.0, - sum1 = 0.0, - sum2 = 0.0, - sum3 = 0.0, - sum4 = 0.0; + sum1 = 0.0, + sum2 = 0.0, + sum3 = 0.0, + sum4 = 0.0; double pixel,pixel_2; @@ -256,7 +257,7 @@ CumulantsForEdgeworthProfile<TInput> // for ( unsigned long i = 0; i < input.Size(); i++ ) for ( i = 0; i < mask.rows(); i++ ) - { + { for ( j = 0; j < mask.cols(); j++ ) { if ( mask.get(i,j) == 1 ) @@ -271,7 +272,7 @@ CumulantsForEdgeworthProfile<TInput> sum4 += pixel_2 * pixel_2; } k++; - } + } } fSum0 += sum0; @@ -294,10 +295,10 @@ CumulantsForEdgeworthProfile<TInput> double sigma_4 = sigma_2 * sigma_2; fMu[level][2] = ( fSum3 - 3.0 * mu * fSum2 + 3.0 * mu_2 * fSum1 - fSum0 * mu_3 ) - / ( sigma_3 * fSum0 ); + / ( sigma_3 * fSum0 ); fMu[level][3] = ( fSum4 - 4.0 * mu * fSum3 + 6.0 * mu_2 * fSum2 - - 4.0 * mu_3 * fSum1 + fSum0 * mu_4 ) - / ( sigma_4 * fSum0 ); + - 4.0 * mu_3 * fSum1 + fSum0 * mu_4 ) + / ( sigma_4 * fSum0 ); return 0; } @@ -325,114 +326,115 @@ CumulantsForEdgeworthProfile<TInput> * ******************************************************************** */ -namespace Functor { +namespace Functor +{ - template< class TInput1, class TInput2, class TOutput > - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::KullbackLeiblerProfile () - { - m_RadiusMin = 1; - m_RadiusMax = 3; - } +template< class TInput1, class TInput2, class TOutput > +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::KullbackLeiblerProfile () +{ + m_RadiusMin = 1; + m_RadiusMax = 3; +} /* =========== Gives the radius min and max of neighborhood ========== */ - template< class TInput1, class TInput2, class TOutput > - void - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::SetRadius ( const unsigned char & min, const unsigned char & max ) - { - m_RadiusMin = min < max ? min : max; - m_RadiusMax = max > min ? max : min; - MakeMultiscaleProfile(); - } +template< class TInput1, class TInput2, class TOutput > +void +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::SetRadius ( const unsigned char & min, const unsigned char & max ) +{ + m_RadiusMin = min < max ? min : max; + m_RadiusMax = max > min ? max : min; + MakeMultiscaleProfile(); +} - template< class TInput1, class TInput2, class TOutput > - unsigned char - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::GetRadiusMin(void) - { - return m_RadiusMin; - } +template< class TInput1, class TInput2, class TOutput > +unsigned char +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::GetRadiusMin(void) +{ + return m_RadiusMin; +} - template< class TInput1, class TInput2, class TOutput > - unsigned char - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::GetRadiusMax(void) - { - return m_RadiusMax; - } +template< class TInput1, class TInput2, class TOutput > +unsigned char +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::GetRadiusMax(void) +{ + return m_RadiusMax; +} /* ====== Make the set of masks to play the increase in window size == */ - template< class TInput1, class TInput2, class TOutput > - void - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::MakeMultiscaleProfile () +template< class TInput1, class TInput2, class TOutput > +void +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::MakeMultiscaleProfile () +{ + m_mask.resize( m_RadiusMax - m_RadiusMin + 1 ); + int lenMax = 2*m_RadiusMax+1; + int i,j,middle = m_RadiusMax; + + // let's begin by the smaller neighborhood + std::vector< itk::Array2D<int> >::iterator outer_iter = m_mask.begin(); + (*outer_iter).SetSize( lenMax, lenMax ); + (*outer_iter).fill(0); + for ( i = middle - m_RadiusMin; i <= middle + m_RadiusMin; i++ ) + for ( j = middle - m_RadiusMin; j <= middle + m_RadiusMin; j++ ) + (*outer_iter).put(i,j,1); + + // std::cerr << "outerIter = " << (*outer_iter) << std::endl; + + // let's continue with increasing neighborhoods + outer_iter++; + for ( int radius = m_RadiusMin+1; radius <= m_RadiusMax; radius++ ) { - m_mask.resize( m_RadiusMax - m_RadiusMin + 1 ); - int lenMax = 2*m_RadiusMax+1; - int i,j,middle = m_RadiusMax; - - // let's begin by the smaller neighborhood - std::vector< itk::Array2D<int> >::iterator outer_iter = m_mask.begin(); (*outer_iter).SetSize( lenMax, lenMax ); (*outer_iter).fill(0); - for ( i = middle - m_RadiusMin; i <= middle + m_RadiusMin; i++ ) - for ( j = middle - m_RadiusMin; j <= middle + m_RadiusMin; j++ ) - (*outer_iter).put(i,j,1); - - // std::cerr << "outerIter = " << (*outer_iter) << std::endl; - // let's continue with increasing neighborhoods - outer_iter++; - for ( int radius = m_RadiusMin+1; radius <= m_RadiusMax; radius++ ) + for ( i = middle - radius; i <= middle + radius; i++ ) { - (*outer_iter).SetSize( lenMax, lenMax ); - (*outer_iter).fill(0); - - for ( i = middle - radius; i <= middle + radius; i++ ) - { - (*outer_iter).put( i, middle-radius, 1 ); - (*outer_iter).put( i, middle+radius, 1 ); - (*outer_iter).put( middle-radius, i, 1 ); - (*outer_iter).put( middle+radius, i, 1 ); - } - - // std::cerr << "outerIter = " << (*outer_iter) << std::endl; - outer_iter++; + (*outer_iter).put( i, middle-radius, 1 ); + (*outer_iter).put( i, middle+radius, 1 ); + (*outer_iter).put( middle-radius, i, 1 ); + (*outer_iter).put( middle+radius, i, 1 ); } + + // std::cerr << "outerIter = " << (*outer_iter) << std::endl; + outer_iter++; } +} /* ========================== Functor ================================ */ - template< class TInput1, class TInput2, class TOutput > - TOutput - KullbackLeiblerProfile<TInput1,TInput2,TOutput> - ::operator () - ( const TInput1 & it1, const TInput2 & it2 ) - { - CumulantsForEdgeworthProfile<TInput1> cum1 ( it1, m_mask ); - CumulantsForEdgeworthProfile<TInput2> cum2 ( it2, m_mask ); - - if ( cum1.m_debug ) - { - itk::VariableLengthVector<double> resu ( m_RadiusMax - m_RadiusMin + 1 ); - resu.Fill( 1e3 ); - return static_cast<TOutput> ( resu ); - } +template< class TInput1, class TInput2, class TOutput > +TOutput +KullbackLeiblerProfile<TInput1,TInput2,TOutput> +::operator () +( const TInput1 & it1, const TInput2 & it2 ) +{ + CumulantsForEdgeworthProfile<TInput1> cum1 ( it1, m_mask ); + CumulantsForEdgeworthProfile<TInput2> cum2 ( it2, m_mask ); - if ( cum2.m_debug ) - { - itk::VariableLengthVector<double> resu ( m_RadiusMax - m_RadiusMin + 1 ); - resu.Fill( 1e3 ); - return static_cast<TOutput> ( resu ); - } + if ( cum1.m_debug ) + { + itk::VariableLengthVector<double> resu ( m_RadiusMax - m_RadiusMin + 1 ); + resu.Fill( 1e3 ); + return static_cast<TOutput> ( resu ); + } - return static_cast<TOutput> ( cum1.KL_profile( cum2 ) + cum2.KL_profile( cum1 ) ); + if ( cum2.m_debug ) + { + itk::VariableLengthVector<double> resu ( m_RadiusMax - m_RadiusMin + 1 ); + resu.Fill( 1e3 ); + return static_cast<TOutput> ( resu ); } + return static_cast<TOutput> ( cum1.KL_profile( cum2 ) + cum2.KL_profile( cum1 ) ); +} + } // Functor } // namespace otb diff --git a/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.h b/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.h index 51aceb6990b4ef4daf5b9f1fb1330ca84f0db177..3167684f2522bce70ef96ba6a29289d354492016 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.h +++ b/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.h @@ -27,7 +27,8 @@ #include "otbROIdataConversion.h" -namespace otb { +namespace otb +{ /** \class KullbackLeiblerSupervizedDistanceImageFilter * \brief Implements KullbackLeibler distance over Edgeworth approximation, @@ -60,98 +61,99 @@ namespace otb { * * \sa CumulantsForEdgeworth */ -namespace Functor { - /** \class KullbackLeiblerSupervizedDistance - * \brief Functor for KullbackLeiblerSupervizedDistanceImageFilter. Please refer to KullbackLeiblerSupervizedDistanceImageFilter. - * - */ - template < class TInput1, class TInput2, class TInputROIImage, class TOutput > - class KullbackLeiblerSupervizedDistance - { - public : - KullbackLeiblerSupervizedDistance (); - virtual ~KullbackLeiblerSupervizedDistance (); +namespace Functor +{ +/** \class KullbackLeiblerSupervizedDistance + * \brief Functor for KullbackLeiblerSupervizedDistanceImageFilter. Please refer to KullbackLeiblerSupervizedDistanceImageFilter. + * + */ +template < class TInput1, class TInput2, class TInputROIImage, class TOutput > +class KullbackLeiblerSupervizedDistance +{ +public : + KullbackLeiblerSupervizedDistance (); + virtual ~KullbackLeiblerSupervizedDistance (); - /** performs the preprocess calculation on the training area */ - void Evaluate ( const typename TInput1::ImageType * img1, - const typename TInput2::ImageType * img2, - const TInputROIImage * imgROI ); + /** performs the preprocess calculation on the training area */ + void Evaluate ( const typename TInput1::ImageType * img1, + const typename TInput2::ImageType * img2, + const TInputROIImage * imgROI ); - /** The functor by itself */ - TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ); + /** The functor by itself */ + TOutput operator () ( const TInput1 & it1, const TInput2 & it2 ); - protected : - typedef ROIdataConversion< - typename TInput1::ImageType, TInputROIImage > ROIConversionType1; +protected : + typedef ROIdataConversion< + typename TInput1::ImageType, TInputROIImage > ROIConversionType1; - typedef itk::ConstNeighborhoodIterator< - typename ROIConversionType1::OutputImageType > ROIInputType1; + typedef itk::ConstNeighborhoodIterator< + typename ROIConversionType1::OutputImageType > ROIInputType1; - typedef ROIdataConversion< - typename TInput2::ImageType, TInputROIImage > ROIConversionType2; + typedef ROIdataConversion< + typename TInput2::ImageType, TInputROIImage > ROIConversionType2; - typedef itk::ConstNeighborhoodIterator< - typename ROIConversionType2::OutputImageType > ROIInputType2; + typedef itk::ConstNeighborhoodIterator< + typename ROIConversionType2::OutputImageType > ROIInputType2; - CumulantsForEdgeworth< ROIInputType1 > * m_CumROI1; - CumulantsForEdgeworth< ROIInputType2 > * m_CumROI2; - private : - KullbackLeiblerSupervizedDistance ( const KullbackLeiblerSupervizedDistance & ); - }; + CumulantsForEdgeworth< ROIInputType1 > * m_CumROI1; + CumulantsForEdgeworth< ROIInputType2 > * m_CumROI2; +private : + KullbackLeiblerSupervizedDistance ( const KullbackLeiblerSupervizedDistance & ); +}; } // Functor template <class TInputImage1, class TInputImage2, class TInputROIImage, class TOutputImage> class ITK_EXPORT KullbackLeiblerSupervizedDistanceImageFilter : - public otb::BinaryFunctorNeighborhoodImageFilter< + public otb::BinaryFunctorNeighborhoodImageFilter< TInputImage1, TInputImage2, TOutputImage, Functor::KullbackLeiblerSupervizedDistance< - typename itk::ConstNeighborhoodIterator< TInputImage1 >, - typename itk::ConstNeighborhoodIterator< TInputImage2 >, - TInputROIImage, - typename TOutputImage::PixelType> > + typename itk::ConstNeighborhoodIterator< TInputImage1 >, + typename itk::ConstNeighborhoodIterator< TInputImage2 >, + TInputROIImage, + typename TOutputImage::PixelType> > { - public: - /** Standard class typedefs. */ - typedef KullbackLeiblerSupervizedDistanceImageFilter Self; - typedef typename otb::BinaryFunctorNeighborhoodImageFilter< - TInputImage1, TInputImage2, TOutputImage, - Functor::KullbackLeiblerSupervizedDistance< - typename itk::ConstNeighborhoodIterator< TInputImage1 >, - typename itk::ConstNeighborhoodIterator< TInputImage2 >, - TInputROIImage, - typename TOutputImage::PixelType > - > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Vectors that hold the training area */ - typedef typename TInputImage1::PixelType MeasurementType1; - typedef typename TInputImage2::PixelType MeasurementType2; - - typedef std::vector< MeasurementType1 > TrainingMeasureType1; - typedef std::vector< MeasurementType2 > TrainingMeasureType2; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Method for creation of the training area and the computation - * of some reference cumulants */ - void SetTrainingArea ( const TInputROIImage * trainingImage ); - - protected: - virtual void BeforeThreadedGenerateData(void); - - KullbackLeiblerSupervizedDistanceImageFilter() - { - this->SetNumberOfRequiredInputs(3); - } - virtual ~KullbackLeiblerSupervizedDistanceImageFilter() {} - - private: - KullbackLeiblerSupervizedDistanceImageFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +public: + /** Standard class typedefs. */ + typedef KullbackLeiblerSupervizedDistanceImageFilter Self; + typedef typename otb::BinaryFunctorNeighborhoodImageFilter< + TInputImage1, TInputImage2, TOutputImage, + Functor::KullbackLeiblerSupervizedDistance< + typename itk::ConstNeighborhoodIterator< TInputImage1 >, + typename itk::ConstNeighborhoodIterator< TInputImage2 >, + TInputROIImage, + typename TOutputImage::PixelType > + > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Vectors that hold the training area */ + typedef typename TInputImage1::PixelType MeasurementType1; + typedef typename TInputImage2::PixelType MeasurementType2; + + typedef std::vector< MeasurementType1 > TrainingMeasureType1; + typedef std::vector< MeasurementType2 > TrainingMeasureType2; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Method for creation of the training area and the computation + * of some reference cumulants */ + void SetTrainingArea ( const TInputROIImage * trainingImage ); + +protected: + virtual void BeforeThreadedGenerateData(void); + + KullbackLeiblerSupervizedDistanceImageFilter() + { + this->SetNumberOfRequiredInputs(3); + } + virtual ~KullbackLeiblerSupervizedDistanceImageFilter() {} + +private: + KullbackLeiblerSupervizedDistanceImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented }; diff --git a/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.txx b/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.txx index f339713728003dd7bb5bdff217c320a885c4be8f..75eba8ca44f2be48700e08222ffdb947d30e959f 100644 --- a/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.txx +++ b/Code/ChangeDetection/otbKullbackLeiblerSupervizedDistanceImageFilter.txx @@ -24,9 +24,11 @@ #include "otbKullbackLeiblerSupervizedDistanceImageFilter.h" -namespace otb { +namespace otb +{ -namespace Functor { +namespace Functor +{ template < class TInput1, class TInput2, class TInputROIImage, class TOutput > KullbackLeiblerSupervizedDistance< TInput1, TInput2, TInputROIImage, TOutput > @@ -51,14 +53,14 @@ template < class TInput1, class TInput2, class TInputROIImage, class TOutput > void KullbackLeiblerSupervizedDistance< TInput1, TInput2, TInputROIImage, TOutput > ::Evaluate ( const typename TInput1::ImageType * img1, - const typename TInput2::ImageType * img2, - const TInputROIImage * imgROI ) + const typename TInput2::ImageType * img2, + const TInputROIImage * imgROI ) { typedef ROIdataConversion< typename TInput1::ImageType, TInputROIImage > - ROIConversionType1; + ROIConversionType1; typedef itk::ConstNeighborhoodIterator< - typename ROIConversionType1::OutputImageType > ROIInputType1; + typename ROIConversionType1::OutputImageType > ROIInputType1; typename ROIConversionType1::Pointer convertion1 = ROIConversionType1::New(); convertion1->SetInputImage( img1 ); @@ -71,10 +73,10 @@ KullbackLeiblerSupervizedDistance< TInput1, TInput2, TInputROIImage, TOutput > m_CumROI1 = new CumulantsForEdgeworth< ROIInputType1 > ( convertion1->GetOutput() ); typedef ROIdataConversion< typename TInput2::ImageType, TInputROIImage > - ROIConversionType2; + ROIConversionType2; typedef itk::ConstNeighborhoodIterator< - typename ROIConversionType2::OutputImageType > ROIInputType2; + typename ROIConversionType2::OutputImageType > ROIInputType2; typename ROIConversionType2::Pointer convertion2 = ROIConversionType2::New(); convertion2->SetInputImage( img2 ); @@ -95,7 +97,7 @@ KullbackLeiblerSupervizedDistance< TInput1, TInput2, TInputROIImage, TOutput > CumulantsForEdgeworth<TInput1> cum1 ( it1 ); CumulantsForEdgeworth<TInput2> cum2 ( it2 ); return static_cast<TOutput> ( m_CumROI1->Divergence( cum1 ) - + m_CumROI2->Divergence( cum2 ) ); + + m_CumROI2->Divergence( cum2 ) ); } } // end of namespace Functor @@ -121,11 +123,11 @@ KullbackLeiblerSupervizedDistanceImageFilter<TInputImage1,TInputImage2,TInputROI ::BeforeThreadedGenerateData(void) { typename TInputImage1::ConstPointer inputPtr1 - = dynamic_cast<const TInputImage1*>( this->GetInput(0) ); + = dynamic_cast<const TInputImage1*>( this->GetInput(0) ); typename TInputImage2::ConstPointer inputPtr2 - = dynamic_cast<const TInputImage2*>( this->GetInput(1) ); + = dynamic_cast<const TInputImage2*>( this->GetInput(1) ); typename TInputROIImage::ConstPointer trainingImage - = static_cast<const TInputROIImage *>( this->itk::ProcessObject::GetInput(2) ); + = static_cast<const TInputROIImage *>( this->itk::ProcessObject::GetInput(2) ); this->GetFunctor().Evaluate( inputPtr1, inputPtr2, trainingImage ); } diff --git a/Code/ChangeDetection/otbLHMIChangeDetector.h b/Code/ChangeDetection/otbLHMIChangeDetector.h index 7edf9ac6e13bec49d207903287298646b3ae52a5..b6d4ebfc5b588c5d9880b62a3bb8c1b5ed35c09b 100644 --- a/Code/ChangeDetection/otbLHMIChangeDetector.h +++ b/Code/ChangeDetection/otbLHMIChangeDetector.h @@ -55,7 +55,8 @@ namespace otb #define epsilon 0.01 -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class LHMI @@ -70,7 +71,7 @@ public: typedef double HistogramFrequencyType; typedef typename itk::Statistics::Histogram<HistogramFrequencyType, 2> HistogramType; typedef typename HistogramType::MeasurementVectorType - MeasurementVectorType; + MeasurementVectorType; typedef typename HistogramType::SizeType HistogramSizeType; typedef typename HistogramType::Iterator HistogramIteratorType; @@ -100,58 +101,58 @@ public: TOutput maxB = itB.GetPixel(0); TOutput minB = itB.GetPixel(0); - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { TOutput value = static_cast<TOutput>(itA.GetPixel(pos)); - if(value > maxA) - maxA = value; + if (value > maxA) + maxA = value; else if (value < minA) - minA = value; + minA = value; value = static_cast<TOutput>(itB.GetPixel(pos)); - if(value > maxB) - maxB = value; + if (value > maxB) + maxB = value; else if (value < minB) - minB = value; + minB = value; - } + } - // Initialize the upper and lower bounds of the histogram. - lowerBound[0] = minA; - lowerBound[1] = minB; - upperBound[0] = - maxA + (maxA - minA ) * upperBoundIncreaseFactor; - upperBound[1] = - maxB + (maxB - minB ) * upperBoundIncreaseFactor; + // Initialize the upper and lower bounds of the histogram. + lowerBound[0] = minA; + lowerBound[1] = minB; + upperBound[0] = + maxA + (maxA - minA ) * upperBoundIncreaseFactor; + upperBound[1] = + maxB + (maxB - minB ) * upperBoundIncreaseFactor; - histogram = HistogramType::New(); + histogram = HistogramType::New(); - histogram->Initialize(histogramSize, lowerBound, upperBound); + histogram->Initialize(histogramSize, lowerBound, upperBound); - for(unsigned long pos = 0; pos< itA.Size(); ++pos) + for (unsigned long pos = 0; pos< itA.Size(); ++pos) { - typename HistogramType::MeasurementVectorType sample; - sample[0] = itA.GetPixel(pos); - sample[1] = itB.GetPixel(pos); - /*if(sample[0]!=NumericTraits<TOutput>::Zero && - sample[1]!=NumericTraits<TOutput>::Zero)*/ - histogram->IncreaseFrequency(sample, 1); + typename HistogramType::MeasurementVectorType sample; + sample[0] = itA.GetPixel(pos); + sample[1] = itB.GetPixel(pos); + /*if(sample[0]!=NumericTraits<TOutput>::Zero && + sample[1]!=NumericTraits<TOutput>::Zero)*/ + histogram->IncreaseFrequency(sample, 1); } - TOutput entropyX = itk::NumericTraits<TOutput>::Zero; - TOutput entropyY = itk::NumericTraits<TOutput>::Zero; - TOutput jointEntropy = itk::NumericTraits<TOutput>::Zero; - HistogramFrequencyType totalFreq = histogram->GetTotalFrequency(); + TOutput entropyX = itk::NumericTraits<TOutput>::Zero; + TOutput entropyY = itk::NumericTraits<TOutput>::Zero; + TOutput jointEntropy = itk::NumericTraits<TOutput>::Zero; + HistogramFrequencyType totalFreq = histogram->GetTotalFrequency(); for (unsigned int i = 0; i < histogram->GetSize()[0]; i++) { @@ -188,7 +189,7 @@ public: } jointEntropy = -jointEntropy/static_cast<TOutput>(totalFreq) + - vcl_log(totalFreq); + vcl_log(totalFreq); return static_cast<TOutput>( jointEntropy/(entropyX + entropyY) ); } @@ -200,22 +201,22 @@ public: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT LHMIChangeDetector : - public BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::LHMI< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::LHMI< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef LHMIChangeDetector Self; typedef BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::LHMI< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::LHMI< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/ChangeDetection/otbMeanDifferenceImageFilter.h b/Code/ChangeDetection/otbMeanDifferenceImageFilter.h index 33596d21a2ee4e478dce212c4ae3b22a4bd021e5..d8426797edb922d56aae327bc3e0fbd5a2a99b84 100644 --- a/Code/ChangeDetection/otbMeanDifferenceImageFilter.h +++ b/Code/ChangeDetection/otbMeanDifferenceImageFilter.h @@ -46,7 +46,8 @@ namespace otb * * \ingroup IntensityImageFilters Multithreaded */ -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class MeanDifference @@ -61,14 +62,14 @@ public: TOutput meanA = 0.0; TOutput meanB = 0.0; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { meanA += static_cast<TOutput>(itA.GetPixel(pos)); meanB += static_cast<TOutput>(itB.GetPixel(pos)); - } + } return static_cast<TOutput>( (meanA-meanB)/itA.Size() ); } }; @@ -76,22 +77,22 @@ public: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT MeanDifferenceImageFilter : - public BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::MeanDifference< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::MeanDifference< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef MeanDifferenceImageFilter Self; typedef BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::MeanDifference< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::MeanDifference< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/ChangeDetection/otbMeanRatioImageFilter.h b/Code/ChangeDetection/otbMeanRatioImageFilter.h index ffa1d1c8b211f5a54fdb7942b8ca703a5a085f4b..31f130ac23e24494e8597dbfbe9db76807facda4 100644 --- a/Code/ChangeDetection/otbMeanRatioImageFilter.h +++ b/Code/ChangeDetection/otbMeanRatioImageFilter.h @@ -44,7 +44,8 @@ namespace otb * * \ingroup IntensityImageFilters Multithreaded */ -namespace Functor { +namespace Functor +{ template< class TInput1, class TInput2, class TOutput> class MeanRatio @@ -59,21 +60,21 @@ public: TOutput meanA = 0.0; TOutput meanB = 0.0; - for(unsigned long pos = 0; pos< itA.Size(); ++pos) - { + for (unsigned long pos = 0; pos< itA.Size(); ++pos) + { meanA += static_cast<TOutput>(itA.GetPixel(pos)); meanB += static_cast<TOutput>(itB.GetPixel(pos)); - } + } meanA /= itA.Size(); meanB /= itB.Size(); TOutput ratio; - if(meanA>meanB) + if (meanA>meanB) ratio = static_cast<TOutput>(1.0 - meanB/meanA); else ratio = static_cast<TOutput>(1.0 - meanA/meanB); @@ -84,22 +85,22 @@ public: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT MeanRatioImageFilter : - public BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::MeanRatio< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> > + public BinaryFunctorNeighborhoodImageFilter< + TInputImage1,TInputImage2,TOutputImage, + Functor::MeanRatio< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef MeanRatioImageFilter Self; typedef BinaryFunctorNeighborhoodImageFilter< - TInputImage1,TInputImage2,TOutputImage, - Functor::MeanRatio< - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, - ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, - ITK_TYPENAME TOutputImage::PixelType> + TInputImage1,TInputImage2,TOutputImage, + Functor::MeanRatio< + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage1>, + ITK_TYPENAME itk::ConstNeighborhoodIterator<TInputImage2>, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/Common/otbArcSpatialObject.h b/Code/Common/otbArcSpatialObject.h index f8de224eff0ea80af6a91ec5cabdbbf83515a056..3083f3601137b0c78fe7a5a15fa630b8246d9e93 100644 --- a/Code/Common/otbArcSpatialObject.h +++ b/Code/Common/otbArcSpatialObject.h @@ -30,7 +30,7 @@ namespace otb */ template <unsigned int VDimension = 2> class ITK_EXPORT ArcSpatialObject - : public itk::SpatialObject<VDimension> + : public itk::SpatialObject<VDimension> { public: /** Standard typedefs */ @@ -62,7 +62,7 @@ public: */ itkSetMacro(Radius,double); itkGetConstReferenceMacro(Radius,double); - /// Set the Start Angle + /// Set the Start Angle itkSetMacro(Angle1,double); itkGetMacro(Angle1,double); @@ -111,7 +111,7 @@ protected: ArcSpatialObject(); /** Destructor */ virtual ~ArcSpatialObject() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/Common/otbArcSpatialObject.txx b/Code/Common/otbArcSpatialObject.txx index 0bb17ba1041c4bf7c1b59bedd31dec9e872aba06..638d419ccdc729bfa9e16b1f445fa01bc302d6f9 100644 --- a/Code/Common/otbArcSpatialObject.txx +++ b/Code/Common/otbArcSpatialObject.txx @@ -48,49 +48,49 @@ ArcSpatialObject< VDimension > ::IsInside( const PointType & point) const { this->ComputeLocalBoundingBox(); - if(!this->GetIndexToWorldTransform()->GetInverse(const_cast<TransformType *>(this->GetInternalInverseTransform()))) - { + if (!this->GetIndexToWorldTransform()->GetInverse(const_cast<TransformType *>(this->GetInternalInverseTransform()))) + { return false; - } + } PointType transformedPoint = this->GetInternalInverseTransform()->TransformPoint(point); double r = 0; - for(unsigned int i=0;i<VDimension;i++) + for (unsigned int i=0;i<VDimension;i++) + { + if (m_Radius!=0.0) { - if(m_Radius!=0.0) - { r += ((transformedPoint[i]*transformedPoint[i])/(m_Radius*m_Radius)); - } - else if(transformedPoint[i]>0.0) // Degenerate ellipse - { + } + else if (transformedPoint[i]>0.0) // Degenerate ellipse + { r = 2; // Keeps function from returning true here - break; - } + break; } - if(r<=1) + } + if (r<=1) { - double angle(0.); - if(transformedPoint[0]!=0) - { - angle=vcl_atan(transformedPoint[1]/transformedPoint[0])*180/PI; - } - else if(transformedPoint[1]>0) - { - angle=90; - } - else if(transformedPoint[1]<0) - { - angle=-90; - } - printf("\n angle=%6.3f ",angle); - if (angle>=m_Angle1 && angle<=m_Angle2) - { - printf("----> OK"); - return true; - } - else return false; + double angle(0.); + if (transformedPoint[0]!=0) + { + angle=vcl_atan(transformedPoint[1]/transformedPoint[0])*180/PI; + } + else if (transformedPoint[1]>0) + { + angle=90; + } + else if (transformedPoint[1]<0) + { + angle=-90; + } + printf("\n angle=%6.3f ",angle); + if (angle>=m_Angle1 && angle<=m_Angle2) + { + printf("----> OK"); + return true; + } + else return false; - } + } return false; } /** @@ -101,22 +101,22 @@ bool ArcSpatialObject< VDimension > ::IsInside( const PointType & point, unsigned int depth, char * name ) const { - // itkDebugMacro( "Checking the point [" << point << "] is inside the Arc" ); +// itkDebugMacro( "Checking the point [" << point << "] is inside the Arc" ); - if(name == NULL) + if (name == NULL) + { + if (IsInside(point)) { - if(IsInside(point)) - { return true; - } } - else if(strstr(typeid(Self).name(), name)) + } + else if (strstr(typeid(Self).name(), name)) + { + if (IsInside(point)) { - if(IsInside(point)) - { return true; - } } + } return Superclass::IsInside(point, depth, name); } /** @@ -128,9 +128,9 @@ ArcSpatialObject< VDimension > ::ComputeLocalBoundingBox() const { itkDebugMacro( "Computing arc bounding box" ); - if( this->GetBoundingBoxChildrenName().empty() - || strstr(typeid(Self).name(), this->GetBoundingBoxChildrenName().c_str()) ) - { + if ( this->GetBoundingBoxChildrenName().empty() + || strstr(typeid(Self).name(), this->GetBoundingBoxChildrenName().c_str()) ) + { // we need to set the minimum and maximum of the bounding box // the center is always inside the bounding box. PointType center; @@ -144,57 +144,57 @@ ArcSpatialObject< VDimension > PointType pntA; PointType pntB; - PointType pntC; - PointType pntD; + PointType pntC; + PointType pntD; - double alpha,longueur,largeur; - alpha=(m_Angle2-m_Angle1); // Difference between 2 angles. + double alpha,longueur,largeur; + alpha=(m_Angle2-m_Angle1); // Difference between 2 angles. - if (alpha<=180) - { - pntA[0]=m_Radius*vcl_cos(m_Angle1*PI/180); - pntA[1]=m_Radius*vcl_sin(m_Angle1*PI/180); - pntB[0]=m_Radius*vcl_cos(m_Angle2*PI/180); - pntB[1]=m_Radius*vcl_sin(m_Angle2*PI/180); + if (alpha<=180) + { + pntA[0]=m_Radius*vcl_cos(m_Angle1*PI/180); + pntA[1]=m_Radius*vcl_sin(m_Angle1*PI/180); + pntB[0]=m_Radius*vcl_cos(m_Angle2*PI/180); + pntB[1]=m_Radius*vcl_sin(m_Angle2*PI/180); - longueur=vcl_sqrt((pntB[0]-pntA[0])*(pntB[0]-pntA[0])+(pntB[1]-pntA[1])*(pntB[1]-pntA[1])); - largeur=m_Radius*(1-vcl_cos((alpha/2)*PI/180)); - pntC[0]=pntB[0]+largeur*(pntB[1]-pntA[1])/longueur; - pntC[1]=pntB[1]-largeur*(pntB[0]-pntA[0])/longueur; - pntD[0]=pntA[0]+largeur*(pntB[1]-pntA[1])/longueur; - pntD[1]=pntA[1]-largeur*(pntB[0]-pntA[0])/longueur; - } - else - { - pntA[0]=m_Radius*vcl_cos(m_Angle1*PI/180); - pntA[1]=m_Radius*vcl_sin(m_Angle1*PI/180); - pntB[0]=m_Radius*vcl_cos(m_Angle2*PI/180); - pntB[1]=m_Radius*vcl_sin(m_Angle2*PI/180); - longueur=vcl_sqrt((pntB[0]-pntA[0])*(pntB[0]-pntA[0])+(pntB[1]-pntA[1])*(pntB[1]-pntA[1])); - largeur=m_Radius*(1-vcl_cos((alpha/2)*PI/180)); - pntA[0]=(m_Radius/2)*(vcl_cos(m_Angle1*PI/180)+vcl_cos(m_Angle2*PI/180))-(m_Radius*m_Radius/longueur)*(vcl_cos(m_Angle1*PI/180)-vcl_cos(m_Angle2*PI/180)); - pntA[1]=(m_Radius/2)*(vcl_sin(m_Angle1*PI/180)+vcl_sin(m_Angle2*PI/180))-(m_Radius*m_Radius/longueur)*(vcl_sin(m_Angle1*PI/180)-vcl_sin(m_Angle2*PI/180)); - pntB[0]=(m_Radius/2)*(vcl_cos(m_Angle1*PI/180)+vcl_cos(m_Angle2*PI/180))+(m_Radius*m_Radius/longueur)*(vcl_cos(m_Angle1*PI/180)-vcl_cos(m_Angle2*PI/180)); - pntB[1]=(m_Radius/2)*(vcl_sin(m_Angle1*PI/180)+vcl_sin(m_Angle2*PI/180))+(m_Radius*m_Radius/longueur)*(vcl_sin(m_Angle1*PI/180)-vcl_sin(m_Angle2*PI/180)); - pntC[0]=pntB[0]-(largeur/(2*m_Radius))*(pntB[1]-pntA[1]); - pntC[1]=pntB[1]+(largeur/(2*m_Radius))*(pntB[0]-pntA[0]); - pntD[0]=pntA[0]-(largeur/(2*m_Radius))*(pntB[1]-pntA[1]); - pntD[1]=pntA[1]+(largeur/(2*m_Radius))*(pntB[0]-pntA[0]); - } - bb->ConsiderPoint(pntA); + longueur=vcl_sqrt((pntB[0]-pntA[0])*(pntB[0]-pntA[0])+(pntB[1]-pntA[1])*(pntB[1]-pntA[1])); + largeur=m_Radius*(1-vcl_cos((alpha/2)*PI/180)); + pntC[0]=pntB[0]+largeur*(pntB[1]-pntA[1])/longueur; + pntC[1]=pntB[1]-largeur*(pntB[0]-pntA[0])/longueur; + pntD[0]=pntA[0]+largeur*(pntB[1]-pntA[1])/longueur; + pntD[1]=pntA[1]-largeur*(pntB[0]-pntA[0])/longueur; + } + else + { + pntA[0]=m_Radius*vcl_cos(m_Angle1*PI/180); + pntA[1]=m_Radius*vcl_sin(m_Angle1*PI/180); + pntB[0]=m_Radius*vcl_cos(m_Angle2*PI/180); + pntB[1]=m_Radius*vcl_sin(m_Angle2*PI/180); + longueur=vcl_sqrt((pntB[0]-pntA[0])*(pntB[0]-pntA[0])+(pntB[1]-pntA[1])*(pntB[1]-pntA[1])); + largeur=m_Radius*(1-vcl_cos((alpha/2)*PI/180)); + pntA[0]=(m_Radius/2)*(vcl_cos(m_Angle1*PI/180)+vcl_cos(m_Angle2*PI/180))-(m_Radius*m_Radius/longueur)*(vcl_cos(m_Angle1*PI/180)-vcl_cos(m_Angle2*PI/180)); + pntA[1]=(m_Radius/2)*(vcl_sin(m_Angle1*PI/180)+vcl_sin(m_Angle2*PI/180))-(m_Radius*m_Radius/longueur)*(vcl_sin(m_Angle1*PI/180)-vcl_sin(m_Angle2*PI/180)); + pntB[0]=(m_Radius/2)*(vcl_cos(m_Angle1*PI/180)+vcl_cos(m_Angle2*PI/180))+(m_Radius*m_Radius/longueur)*(vcl_cos(m_Angle1*PI/180)-vcl_cos(m_Angle2*PI/180)); + pntB[1]=(m_Radius/2)*(vcl_sin(m_Angle1*PI/180)+vcl_sin(m_Angle2*PI/180))+(m_Radius*m_Radius/longueur)*(vcl_sin(m_Angle1*PI/180)-vcl_sin(m_Angle2*PI/180)); + pntC[0]=pntB[0]-(largeur/(2*m_Radius))*(pntB[1]-pntA[1]); + pntC[1]=pntB[1]+(largeur/(2*m_Radius))*(pntB[0]-pntA[0]); + pntD[0]=pntA[0]-(largeur/(2*m_Radius))*(pntB[1]-pntA[1]); + pntD[1]=pntA[1]+(largeur/(2*m_Radius))*(pntB[0]-pntA[0]); + } + bb->ConsiderPoint(pntA); bb->ConsiderPoint(pntB); bb->ConsiderPoint(pntC); bb->ConsiderPoint(pntD); - bb->ComputeBoundingBox(); - PointType pnt = this->GetIndexToWorldTransform()->TransformPoint(pntA); - const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); - pnt = this->GetIndexToWorldTransform()->TransformPoint(pntB); - const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); - pnt = this->GetIndexToWorldTransform()->TransformPoint(pntC); - const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); - pnt = this->GetIndexToWorldTransform()->TransformPoint(pntD); - const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); - } + bb->ComputeBoundingBox(); + PointType pnt = this->GetIndexToWorldTransform()->TransformPoint(pntA); + const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); + pnt = this->GetIndexToWorldTransform()->TransformPoint(pntB); + const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); + pnt = this->GetIndexToWorldTransform()->TransformPoint(pntC); + const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); + pnt = this->GetIndexToWorldTransform()->TransformPoint(pntD); + const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pnt); + } return true; } /** @@ -218,24 +218,24 @@ ArcSpatialObject< VDimension > char * name ) const { // itkDebugMacro( "Getting the value of the arc at " << point ); - if( IsInside(point, 0, name) ) - { + if ( IsInside(point, 0, name) ) + { value = this->GetDefaultInsideValue(); return true; - } + } else + { + if ( Superclass::IsEvaluableAt(point, depth, name) ) { - if( Superclass::IsEvaluableAt(point, depth, name) ) - { Superclass::ValueAt(point, value, depth, name); return true; - } + } else - { + { value = this->GetDefaultOutsideValue(); return false; - } } + } return false; } /** @@ -258,11 +258,11 @@ void ArcSpatialObject< VDimension > { // check if we are the same type const Self* source = dynamic_cast<const Self*>(data); - if(!source) - { + if (!source) + { std::cout << "CopyInformation: objects are not of the same type" << std::endl; return; - } + } // copy the properties Superclass::CopyInformation(data); diff --git a/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.h b/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.h index b7c41e7b8c2876c51019e7c9b9c256f02863510d..af9fb8a8e7135241e0db35e0e7ae40c19b002d94 100644 --- a/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.h +++ b/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.h @@ -35,8 +35,8 @@ namespace otb * \ingroup IntensityImageFilters Multithreaded */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > - class ITK_EXPORT BinaryFunctorNeighborhoodImageFilter : public itk::ImageToImageFilter<TInputImage1,TOutputImage> +class TOutputImage, class TFunction > +class ITK_EXPORT BinaryFunctorNeighborhoodImageFilter : public itk::ImageToImageFilter<TInputImage1,TOutputImage> { public: /** Standard class typedefs. */ @@ -68,7 +68,7 @@ public: typedef typename OutputImageType::Pointer OutputImagePointer; typedef typename OutputImageType::RegionType OutputImageRegionType; typedef typename OutputImageType::PixelType OutputImagePixelType; - + typedef itk::ProcessObject ProcessObjectType; @@ -86,7 +86,10 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -103,9 +106,9 @@ public: typedef itk::ConstNeighborhoodIterator<TInputImage1> - NeighborhoodIteratorType1; + NeighborhoodIteratorType1; typedef itk::ConstNeighborhoodIterator<TInputImage2> - NeighborhoodIteratorType2; + NeighborhoodIteratorType2; typedef typename NeighborhoodIteratorType1::RadiusType RadiusType1; typedef typename NeighborhoodIteratorType2::RadiusType RadiusType2; @@ -129,7 +132,7 @@ protected: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ); + int threadId ); /** * Pad the inputs requested regions by radius diff --git a/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.txx b/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.txx index 4d2929cd49fa3418eda477250c425646a819eaf3..50fdb1ea2a37e448c76f2e244f6089ba155bcaea 100644 --- a/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.txx +++ b/Code/Common/otbBinaryFunctorNeighborhoodImageFilter.txx @@ -31,7 +31,7 @@ namespace otb * Constructor */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::BinaryFunctorNeighborhoodImageFilter() { @@ -44,7 +44,7 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput1( const TInputImage1 * image1 ) @@ -58,7 +58,7 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput2( const TInputImage2 * image2 ) @@ -68,34 +68,34 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > const TInputImage1 * BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GetInput1() { - if(this->GetNumberOfInputs()<1) - { - return 0; - } + if (this->GetNumberOfInputs()<1) + { + return 0; + } return static_cast<const TInputImage1 *>(this->itk::ProcessObject::GetInput(0)); } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > const TInputImage2 * BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GetInput2() { - if(this->GetNumberOfInputs()<2) - { - return 0; - } + if (this->GetNumberOfInputs()<2) + { + return 0; + } return static_cast<const TInputImage2 *>(this->itk::ProcessObject::GetInput(1)); } template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::GenerateInputRequestedRegion() @@ -104,16 +104,16 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output - Input1ImagePointer inputPtr1 = - const_cast< TInputImage1 * >( this->GetInput1()); - Input2ImagePointer inputPtr2 = - const_cast< TInputImage2 * >( this->GetInput2()); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); + Input1ImagePointer inputPtr1 = + const_cast< TInputImage1 * >( this->GetInput1()); + Input2ImagePointer inputPtr2 = + const_cast< TInputImage2 * >( this->GetInput2()); + typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr1 || !inputPtr2 || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage1::RegionType inputRequestedRegion1, inputRequestedRegion2; @@ -125,11 +125,11 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun // crop the input requested region at the input's largest possible region if ( inputRequestedRegion1.Crop(inputPtr1->GetLargestPossibleRegion())) - { + { inputPtr1->SetRequestedRegion( inputRequestedRegion1 ); - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -140,18 +140,18 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << this->GetNameOfClass() - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region of image 1."); e.SetDataObject(inputPtr1); throw e; - } + } if ( inputRequestedRegion2.Crop(inputPtr2->GetLargestPossibleRegion())) - { + { inputPtr2->SetRequestedRegion( inputRequestedRegion2 ); - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -162,12 +162,12 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1,TInputImage2,TOutputImage,TFun itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << this->GetNameOfClass() - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region of image 1."); e.SetDataObject(inputPtr2); throw e; - } + } return; } @@ -189,9 +189,9 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1, TInputImage2, TOutputImage, T // ImageToImageFilter::GetInput(int) always returns a pointer to a // TInputImage1 so it cannot be used for the second input. Input1ImageConstPointer inputPtr1 - = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); + = dynamic_cast<const TInputImage1*>(ProcessObjectType::GetInput(0)); Input2ImageConstPointer inputPtr2 - = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); + = dynamic_cast<const TInputImage2*>(ProcessObjectType::GetInput(1)); OutputImagePointer outputPtr = this->GetOutput(0); @@ -224,7 +224,7 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1, TInputImage2, TOutputImage, T // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit1=faceList1.begin(), fit2=faceList2.begin(); fit1 != faceList1.end(), fit2 != faceList2.end(); ++fit1, ++fit2) - { + { neighInputIt1 = itk::ConstNeighborhoodIterator<TInputImage1>(r1, inputPtr1, *fit1); neighInputIt2 = itk::ConstNeighborhoodIterator<TInputImage2>(r2, inputPtr2, *fit2); // outputIt = itk::ImageRegionIterator<TOutputImage>(outputPtr, outputRegionForThread); @@ -236,7 +236,7 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1, TInputImage2, TOutputImage, T neighInputIt2.GoToBegin(); while ( ! outputIt.IsAtEnd() ) - { + { outputIt.Set( m_Functor( neighInputIt1, neighInputIt2 ) ); @@ -244,8 +244,8 @@ BinaryFunctorNeighborhoodImageFilter<TInputImage1, TInputImage2, TOutputImage, T ++neighInputIt2; ++outputIt; progress.CompletedPixel(); - } } + } diff --git a/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.h b/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.h index aad8bad74623f5d3cf32615db87f509e6169db80..8a19b97276c3e463ecf10a245738a7bc252b65ae 100644 --- a/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.h +++ b/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.h @@ -22,7 +22,8 @@ #include "itkImageRegionIteratorWithIndex.h" #include "itkConstNeighborhoodIterator.h" -namespace otb { +namespace otb +{ /** \class BinaryFunctorNeighborhoodVectorImageFilter * \brief Implements neighborhood-wise generic operation of two images beeing vector images. * @@ -33,9 +34,9 @@ namespace otb { * \ingroup IntensityImageFilters Multithreaded */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > class ITK_EXPORT BinaryFunctorNeighborhoodVectorImageFilter - : public itk::InPlaceImageFilter<TInputImage1,TOutputImage> + : public itk::InPlaceImageFilter<TInputImage1,TOutputImage> { public: /** Standard class typedefs. */ @@ -84,7 +85,10 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -101,9 +105,9 @@ public: typedef itk::ConstNeighborhoodIterator<TInputImage1> - NeighborhoodIteratorType1; + NeighborhoodIteratorType1; typedef itk::ConstNeighborhoodIterator<TInputImage2> - NeighborhoodIteratorType2; + NeighborhoodIteratorType2; typedef typename NeighborhoodIteratorType1::RadiusType RadiusType1; typedef typename NeighborhoodIteratorType2::RadiusType RadiusType2; @@ -127,7 +131,7 @@ protected: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ); + int threadId ); /** * Since the number of components per pixel depends on the radius range, one must reimplement diff --git a/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.txx b/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.txx index 6137ac1fbafdba8006487501340d2d24609e90a2..c0ad277586cc32c654a5089b7b5aba9c602dde73 100644 --- a/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.txx +++ b/Code/Common/otbBinaryFunctorNeighborhoodVectorImageFilter.txx @@ -31,7 +31,7 @@ namespace otb * Constructor */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::BinaryFunctorNeighborhoodVectorImageFilter() { @@ -45,7 +45,7 @@ BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImag * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput1( const TInputImage1 * image1 ) @@ -59,7 +59,7 @@ BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImag * Connect one of the operands for neighborhood-wise operation */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetInput2( const TInputImage2 * image2 ) @@ -72,7 +72,7 @@ BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImag * Connect the interval of radius */ template <class TInputImage1, class TInputImage2, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1,TInputImage2,TOutputImage,TFunction> ::SetRadius( const unsigned char & min, const unsigned char & max ) @@ -92,7 +92,7 @@ BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1, TInputImage2, TOutputIm Superclass::GenerateOutputInformation(); int nbComponents = static_cast<int>(m_Functor.GetRadiusMax())+1 - - static_cast<int>(m_Functor.GetRadiusMin()); + - static_cast<int>(m_Functor.GetRadiusMin()); this->GetOutput()->SetNumberOfComponentsPerPixel(nbComponents); } @@ -148,8 +148,8 @@ BinaryFunctorNeighborhoodVectorImageFilter<TInputImage1, TInputImage2, TOutputIm // Process each of the boundary faces. // Center first and then left, right, up, down borders for ( fit1=faceList1.begin(), fit2=faceList2.begin(); - fit1 != faceList1.end() && fit2 != faceList2.end(); - ++fit1, ++fit2 ) + fit1 != faceList1.end() && fit2 != faceList2.end(); + ++fit1, ++fit2 ) { neighInputIt1 = itk::ConstNeighborhoodIterator<TInputImage1> ( r1, inputPtr1, *fit1 ); neighInputIt1.OverrideBoundaryCondition( &nbc1 ); diff --git a/Code/Common/otbCommandLineArgumentParser.cxx b/Code/Common/otbCommandLineArgumentParser.cxx index 53cd5f42fbbc2c16b4d1e05d0f15f44e48a43454..581e3723b7ddb7d893777e040ee3b8dfc011970a 100644 --- a/Code/Common/otbCommandLineArgumentParser.cxx +++ b/Code/Common/otbCommandLineArgumentParser.cxx @@ -27,190 +27,190 @@ namespace otb // --------- CommandLineArgumentParseResult ---------------------------------------- - void CommandLineArgumentParseResult - ::PrintSelf(std::ostream& os/*, itk::Indent indent*/)const - { +void CommandLineArgumentParseResult +::PrintSelf(std::ostream& os/*, itk::Indent indent*/)const +{ - } +} - bool CommandLineArgumentParseResult - ::IsOptionPresent(std::string option)const - { - return (m_OptionMap.find(option) != m_OptionMap.end()); - } +bool CommandLineArgumentParseResult +::IsOptionPresent(std::string option)const +{ + return (m_OptionMap.find(option) != m_OptionMap.end()); +} - bool CommandLineArgumentParseResult - ::IsOptionInputImagePresent(void)const - { - return (this->IsOptionPresent("--InputImage")); - } - bool CommandLineArgumentParseResult - ::IsOptionOutputImagePresent(void)const - { - return (this->IsOptionPresent("--OutputImage")); - } +bool CommandLineArgumentParseResult +::IsOptionInputImagePresent(void)const +{ + return (this->IsOptionPresent("--InputImage")); +} +bool CommandLineArgumentParseResult +::IsOptionOutputImagePresent(void)const +{ + return (this->IsOptionPresent("--OutputImage")); +} - bool CommandLineArgumentParseResult - ::IsOptionOTBTestingPresent(void)const - { - return (this->IsOptionPresent("--OTBTesting")); - } +bool CommandLineArgumentParseResult +::IsOptionOTBTestingPresent(void)const +{ + return (this->IsOptionPresent("--OTBTesting")); +} - std::string CommandLineArgumentParseResult - ::GetParameterString(std::string option, unsigned int number)const +std::string CommandLineArgumentParseResult +::GetParameterString(std::string option, unsigned int number)const +{ + if ( this->IsOptionPresent(option) == false ) { - if( this->IsOptionPresent(option) == false ) - { - itk::OStringStream msg; - msg<<"GetParameterString(): The following '"<<option<<"' option is unknown !!"; - CommandLineArgumentParserArgumentErrorException e(__FILE__, __LINE__); - e.SetDescription(msg.str().c_str()); - throw e; - } - OptionMapType::const_iterator it = m_OptionMap.begin(); - it = m_OptionMap.find(option); - ParameterArrayType pat = (*it).second; - std::string lString = pat[number]; - return ( lString ); + itk::OStringStream msg; + msg<<"GetParameterString(): The following '"<<option<<"' option is unknown !!"; + CommandLineArgumentParserArgumentErrorException e(__FILE__, __LINE__); + e.SetDescription(msg.str().c_str()); + throw e; } + OptionMapType::const_iterator it = m_OptionMap.begin(); + it = m_OptionMap.find(option); + ParameterArrayType pat = (*it).second; + std::string lString = pat[number]; + return ( lString ); +} - std::string CommandLineArgumentParseResult - ::GetInputImage(void) const - { - return (GetParameterString("--InputImage")); - } +std::string CommandLineArgumentParseResult +::GetInputImage(void) const +{ + return (GetParameterString("--InputImage")); +} - std::string CommandLineArgumentParseResult - ::GetOutputImage(void) const - { - return (GetParameterString("--OutputImage")); - } +std::string CommandLineArgumentParseResult +::GetOutputImage(void) const +{ + return (GetParameterString("--OutputImage")); +} - int CommandLineArgumentParseResult - ::GetNumberOfParameters(std::string option) - { - assert(IsOptionPresent(option)); - return (m_OptionMap[option].size()); - } +int CommandLineArgumentParseResult +::GetNumberOfParameters(std::string option) +{ + assert(IsOptionPresent(option)); + return (m_OptionMap[option].size()); +} - void CommandLineArgumentParseResult - ::Clear() - { - m_OptionMap.clear(); - } +void CommandLineArgumentParseResult +::Clear() +{ + m_OptionMap.clear(); +} - void CommandLineArgumentParseResult - ::AddOption(const std::string &option) - { - ParameterArrayType pat; +void CommandLineArgumentParseResult +::AddOption(const std::string &option) +{ + ParameterArrayType pat; // pat.reserve(nParms); - m_OptionMap[option] = pat; - } + m_OptionMap[option] = pat; +} - void CommandLineArgumentParseResult - ::AddParameter(const std::string &option, const std::string ¶meter) - { - m_OptionMap[option].push_back(parameter); - } +void CommandLineArgumentParseResult +::AddParameter(const std::string &option, const std::string ¶meter) +{ + m_OptionMap[option].push_back(parameter); +} // --------- CommandLineArgumentParser ---------------------------------------- - CommandLineArgumentParser - ::CommandLineArgumentParser() - { - AddOption("--help","Help","-h",0,false); - AddOption("--version","Version","-v",0,false); - AddOptionNParams("--OTBTesting", "Testing purposes only.","-OTBTesting",false); - m_ProgramDescription.clear(); - } +CommandLineArgumentParser +::CommandLineArgumentParser() +{ + AddOption("--help","Help","-h",0,false); + AddOption("--version","Version","-v",0,false); + AddOptionNParams("--OTBTesting", "Testing purposes only.","-OTBTesting",false); + m_ProgramDescription.clear(); +} - void CommandLineArgumentParser - ::AddInputImage(bool obligatory) - { - AddOption("--InputImage","input image file name ","-in",1,obligatory); - } +void CommandLineArgumentParser +::AddInputImage(bool obligatory) +{ + AddOption("--InputImage","input image file name ","-in",1,obligatory); +} - void CommandLineArgumentParser - ::AddOutputImage(bool obligatory) - { - AddOption("--OutputImage","output image file name ","-out",1,obligatory); - } +void CommandLineArgumentParser +::AddOutputImage(bool obligatory) +{ + AddOption("--OutputImage","output image file name ","-out",1,obligatory); +} - void CommandLineArgumentParser - ::AddOption(std::string name, std::string comment, std::string synonim, int nParameters, bool obligatory ) - { +void CommandLineArgumentParser +::AddOption(std::string name, std::string comment, std::string synonim, int nParameters, bool obligatory ) +{ // Create a structure for the command - OptionType option; - option.CommonName = name; - option.Description = comment; - option.Synonim = synonim; - option.NumberOfParameters = nParameters; - option.NumberOfParametersFixed = true; - option.Obligatory = obligatory; - option.Finded = false; + OptionType option; + option.CommonName = name; + option.Description = comment; + option.Synonim = synonim; + option.NumberOfParameters = nParameters; + option.NumberOfParametersFixed = true; + option.Obligatory = obligatory; + option.Finded = false; // Add the option to the map - m_OptionList.push_back(option); + m_OptionList.push_back(option); - } +} - void CommandLineArgumentParser - ::AddOptionNParams(std::string name, std::string comment, std::string synonim, bool obligatory ) - { +void CommandLineArgumentParser +::AddOptionNParams(std::string name, std::string comment, std::string synonim, bool obligatory ) +{ // Create a structure for the command - OptionType option; - option.CommonName = name; - option.Description = comment; - option.Synonim = synonim; - option.NumberOfParameters = -1; - option.NumberOfParametersFixed = false; - option.Obligatory = obligatory; - option.Finded = false; + OptionType option; + option.CommonName = name; + option.Description = comment; + option.Synonim = synonim; + option.NumberOfParameters = -1; + option.NumberOfParametersFixed = false; + option.Obligatory = obligatory; + option.Finded = false; // Add the option to the map - m_OptionList.push_back(option); + m_OptionList.push_back(option); - } +} - void CommandLineArgumentParser - ::ParseGUI(CommandLineArgumentParseResult * outResult,bool failOnUnknownTrailingParameters ) - { -/* OTB Comment : Todo : use OTB_USE_VISU_GUI cmake option for generate this method - Fl_Window *window = new Fl_Window(320,(m_OptionList.size()+2)*50); +void CommandLineArgumentParser +::ParseGUI(CommandLineArgumentParseResult * outResult,bool failOnUnknownTrailingParameters ) +{ + /* OTB Comment : Todo : use OTB_USE_VISU_GUI cmake option for generate this method + Fl_Window *window = new Fl_Window(320,(m_OptionList.size()+2)*50); - std::vector<Fl_Input*> myInputs; - unsigned int pos = 1; - for(ListOptionType::iterator it = m_OptionList.begin();it!=m_OptionList.end();++it,++pos) - { - Fl_Input * tmpInput = new Fl_Input(50,pos*50,200,30,it->CommonName.c_str()); - tmpInput->tooltip(it->Description.c_str()); + std::vector<Fl_Input*> myInputs; + unsigned int pos = 1; + for(ListOptionType::iterator it = m_OptionList.begin();it!=m_OptionList.end();++it,++pos) + { + Fl_Input * tmpInput = new Fl_Input(50,pos*50,200,30,it->CommonName.c_str()); + tmpInput->tooltip(it->Description.c_str()); - } - Fl_Button * button = new Fl_Button(50,pos*50 , 130, 30, "Ok"); - button->tooltip("Validate parameters and exit."); - window->end(); - window->show(); - Fl::run(); + } + Fl_Button * button = new Fl_Button(50,pos*50 , 130, 30, "Ok"); + button->tooltip("Validate parameters and exit."); + window->end(); + window->show(); + Fl::run(); - for(std::vector<Fl_Input * >::iterator flIt =myInputs.begin();flIt!=myInputs.end();++flIt) - { - delete (*flIt); - } - delete button; - delete window; -*/ - } + for(std::vector<Fl_Input * >::iterator flIt =myInputs.begin();flIt!=myInputs.end();++flIt) + { + delete (*flIt); + } + delete button; + delete window; + */ +} void CommandLineArgumentParser ::ParseCommandLine(int argc, char *argv[], - CommandLineArgumentParseResult * outResult, - bool failOnUnknownTrailingParameters ) + CommandLineArgumentParseResult * outResult, + bool failOnUnknownTrailingParameters ) { bool tryParse = TryParseCommandLine(argc, argv, outResult, false, failOnUnknownTrailingParameters); @@ -254,7 +254,7 @@ bool CommandLineArgumentParser::TryParseCommandLine(int argc, char *argv[], int index(0); // Go through the arguments - for(i=1; i < argc; i++) + for (i=1; i < argc; i++) { // Get the next argument std::string arg(argv[i]); @@ -263,10 +263,10 @@ bool CommandLineArgumentParser::TryParseCommandLine(int argc, char *argv[], bool findOption = FindOption( arg, index ); if (findOption == false) { - if(failOnUnknownTrailingParameters) + if (failOnUnknownTrailingParameters) { - // Unknown argument found - if( reportFailedMsg == true) + // Unknown argument found + if ( reportFailedMsg == true) { std::cerr << "The following '" << arg << "' option is unknown !!" << std::endl; } @@ -274,27 +274,27 @@ bool CommandLineArgumentParser::TryParseCommandLine(int argc, char *argv[], } else return true; } - //Check the option + //Check the option m_OptionList[index].Finded = true; - // If the number of parameters is predefined + // If the number of parameters is predefined if (m_OptionList[index].NumberOfParametersFixed == true) { // Check if the number of parameters is correct int nParameters = m_OptionList[index].NumberOfParameters; - if(i+nParameters >= argc) + if (i+nParameters >= argc) { - // Too few parameters - if( reportFailedMsg == true) + // Too few parameters + if ( reportFailedMsg == true) { std::cerr << "Missing one (or more) parameter(s) for the following '" << arg << "' option." << std::endl; } return false; } - // Tell the result that the option has been encountered + // Tell the result that the option has been encountered outResult->AddOption(m_OptionList[index].CommonName); // Pass in the parameters - for(int j=0;j<nParameters;j++,i++) + for (int j=0;j<nParameters;j++,i++) { outResult->AddParameter(m_OptionList[index].CommonName,std::string(argv[i+1])); } @@ -331,12 +331,12 @@ bool CommandLineArgumentParser::TryParseCommandLine(int argc, char *argv[], } // Check that all required arguments are specified - for(unsigned int cpt=0; cpt < m_OptionList.size(); cpt++ ) + for (unsigned int cpt=0; cpt < m_OptionList.size(); cpt++ ) { if ( (m_OptionList[cpt].Obligatory == true) && (m_OptionList[cpt].Finded == false) ) { - // Too few parameters - if( reportFailedMsg == true) + // Too few parameters + if ( reportFailedMsg == true) { std::cerr << "'" << m_OptionList[cpt].CommonName << "' argument is required !!!" << std::endl; } @@ -364,7 +364,7 @@ bool CommandLineArgumentParser::FindOption(const std::string & option, int & ind optionFoundFlag = true; } cpt++; - if( cpt >= m_OptionList.size() ) + if ( cpt >= m_OptionList.size() ) { goOnFlag = false; } @@ -382,18 +382,18 @@ void CommandLineArgumentParser::PrintUsage(std::ostream& os)const } os << " Usage : "<<m_ProgramName<<std::endl; - // Compute the max width for option display + // Compute the max width for option display int largeurmax(-1); unsigned int i; - for(i=0; i < m_OptionList.size(); i++ ) + for (i=0; i < m_OptionList.size(); i++ ) { int largeur = m_OptionList[i].CommonName.size() + m_OptionList[i].Synonim.size(); if ( largeur > largeurmax ) largeurmax = largeur; } // Check that all required arguments are present on the command line - for(i=0; i < m_OptionList.size(); i++ ) + for (i=0; i < m_OptionList.size(); i++ ) { if (m_OptionList[i].CommonName != "--OTBTesting") { @@ -413,16 +413,16 @@ void CommandLineArgumentParser::PrintUsage(std::ostream& os)const os << " : "<<m_OptionList[i].Description; if (m_OptionList[i].NumberOfParametersFixed == true ) { - switch( m_OptionList[i].NumberOfParameters ) + switch ( m_OptionList[i].NumberOfParameters ) { - case 0 : - break; - case 1 : - os << " ("<<m_OptionList[i].NumberOfParameters<<" parameter)"; - break; - default : - os << " ("<<m_OptionList[i].NumberOfParameters<<" parameters)"; - break; + case 0 : + break; + case 1 : + os << " ("<<m_OptionList[i].NumberOfParameters<<" parameter)"; + break; + default : + os << " ("<<m_OptionList[i].NumberOfParameters<<" parameters)"; + break; } } else diff --git a/Code/Common/otbCommandLineArgumentParser.h b/Code/Common/otbCommandLineArgumentParser.h index ecca2a3f9d929a5b326a2cb86850f76841ad1744..abc1e72c632b20814c038470572d14596df5745a 100644 --- a/Code/Common/otbCommandLineArgumentParser.h +++ b/Code/Common/otbCommandLineArgumentParser.h @@ -37,23 +37,23 @@ * \brief This exception is thrown when the help menu is displayed. */ class ITK_EXPORT CommandLineArgumentParserHelpException - : public itk::ExceptionObject + : public itk::ExceptionObject { public: /** Run-time information. */ itkTypeMacro(CommandLineArgumentParserHelpException , ExceptionObject ); /** Constructor. */ - CommandLineArgumentParserHelpException(const char *file, unsigned int line, - const char* message = "Help:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserHelpException(const char *file, unsigned int line, + const char* message = "Help:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} /** Constructor. */ - CommandLineArgumentParserHelpException(const std::string &file, unsigned int line, - const char* message = "Help:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserHelpException(const std::string &file, unsigned int line, + const char* message = "Help:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} }; @@ -61,23 +61,23 @@ public: * \brief This exception is thrown when the version is displayed. */ class ITK_EXPORT CommandLineArgumentParserVersionException - : public itk::ExceptionObject + : public itk::ExceptionObject { public: /** Run-time information. */ itkTypeMacro(CommandLineArgumentParserVersionException , ExceptionObject ); /** Constructor. */ - CommandLineArgumentParserVersionException(const char *file, unsigned int line, - const char* message = "Version:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserVersionException(const char *file, unsigned int line, + const char* message = "Version:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} /** Constructor. */ - CommandLineArgumentParserVersionException(const std::string &file, unsigned int line, - const char* message = "Version:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserVersionException(const std::string &file, unsigned int line, + const char* message = "Version:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} }; @@ -85,23 +85,23 @@ public: * \brief This exception is thrown when the version is displayed. */ class ITK_EXPORT CommandLineArgumentParserArgumentErrorException - : public itk::ExceptionObject + : public itk::ExceptionObject { public: /** Run-time information. */ itkTypeMacro(CommandLineArgumentParserArgumentErrorException , ExceptionObject ); /** Constructor. */ - CommandLineArgumentParserArgumentErrorException(const char *file, unsigned int line, - const char* message = "Argument error:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserArgumentErrorException(const char *file, unsigned int line, + const char* message = "Argument error:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} /** Constructor. */ - CommandLineArgumentParserArgumentErrorException(const std::string &file, unsigned int line, - const char* message = "Argument error:", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + CommandLineArgumentParserArgumentErrorException(const std::string &file, unsigned int line, + const char* message = "Argument error:", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} }; @@ -175,8 +175,8 @@ public: protected: - CommandLineArgumentParseResult(){}; - ~CommandLineArgumentParseResult(){}; + CommandLineArgumentParseResult() {}; + ~CommandLineArgumentParseResult() {}; private: @@ -254,14 +254,14 @@ public: // void AddSynonim(const char *option, const char *synonim); void ParseCommandLine(int argc, char *argv[], - CommandLineArgumentParseResult * outResult, - bool failOnUnknownTrailingParameters = true); + CommandLineArgumentParseResult * outResult, + bool failOnUnknownTrailingParameters = true); void ParseGUI( CommandLineArgumentParseResult * outResult, - bool failOnUnknownTrailingParameters = true); + bool failOnUnknownTrailingParameters = true); protected: CommandLineArgumentParser(); - ~CommandLineArgumentParser(){}; + ~CommandLineArgumentParser() {}; private: @@ -276,7 +276,7 @@ private: bool failOnUnknownTrailingParameters ); typedef struct - { + { std::string CommonName; // option name std::string Description; // option description std::string Synonim; // shortcut @@ -284,7 +284,7 @@ private: int NumberOfParameters; // number of values bool Obligatory; // is the option mandatory ? bool Finded; // check if the option is present - } OptionType; + } OptionType; typedef std::vector< OptionType> ListOptionType; ListOptionType m_OptionList; diff --git a/Code/Common/otbConcatenateVectorImageFilter.h b/Code/Common/otbConcatenateVectorImageFilter.h index d40618c38d81ed90fa909036f0976f91341f01dc..8c9d74092f5cf0f3f47fa25ceed252a7def3b43c 100644 --- a/Code/Common/otbConcatenateVectorImageFilter.h +++ b/Code/Common/otbConcatenateVectorImageFilter.h @@ -29,7 +29,7 @@ namespace otb */ template<class TInputImage1,class TInputImage2,class TOutputImage> class ITK_EXPORT ConcatenateVectorImageFilter -: public itk::ImageToImageFilter<TInputImage1,TOutputImage> + : public itk::ImageToImageFilter<TInputImage1,TOutputImage> { public: /** Standard class typedefs. */ @@ -79,7 +79,7 @@ public: itkStaticConstMacro(InputImage2Dimension, unsigned int, TInputImage2::ImageDimension); itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); - protected: +protected: /** Constructor. */ ConcatenateVectorImageFilter(); /** Destructor. */ diff --git a/Code/Common/otbConcatenateVectorImageFilter.txx b/Code/Common/otbConcatenateVectorImageFilter.txx index c82569f5d459024e522350c2061d85bd9dc7d859..7ee6f8a89ae67c0085768de216d4baf2413a4915 100644 --- a/Code/Common/otbConcatenateVectorImageFilter.txx +++ b/Code/Common/otbConcatenateVectorImageFilter.txx @@ -21,152 +21,153 @@ PURPOSE. See the above copyright notices for more information. #include "otbConcatenateVectorImageFilter.h" #include "itkImageRegionIterator.h" -namespace otb { - /** - * Constructor. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::ConcatenateVectorImageFilter() - { - this->SetNumberOfRequiredInputs(2); - } - /** - * Destructor. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::~ConcatenateVectorImageFilter() - {} - /** - * Set The first input image. - * \param image The first input image. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - void - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::SetInput1(const TInputImage1 * image) - { - this->SetNthInput(0,const_cast<TInputImage1 *>(image)); - } - /** - * Set The second input image. - * \param image The second input image. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - void - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::SetInput2(const TInputImage2 * image) - { - this->SetNthInput(1,const_cast<TInputImage2 *>(image)); - } - /** - * Get the first input image. - * \return The first input image. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - typename ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::InputImage1Type * - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::GetInput1(void) - { - return const_cast<InputImage1Type *>(this->GetInput(0)); - } - /** - * Get the second input image. - * \return The second input image. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - typename ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::InputImage2Type * - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::GetInput2(void) - { - return const_cast<InputImage2Type *>(this->GetInput(1)); - } - /** - * Main computation method. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - void - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::GenerateData() - { - // retrieves inputs and output pointer - InputImage1PointerType input1 = this->GetInput1(); - InputImage2PointerType input2 = this->GetInput2(); - OutputImagePointerType output = this->GetOutput(); +namespace otb +{ +/** + * Constructor. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::ConcatenateVectorImageFilter() +{ + this->SetNumberOfRequiredInputs(2); +} +/** + * Destructor. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::~ConcatenateVectorImageFilter() +{} +/** + * Set The first input image. + * \param image The first input image. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +void +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::SetInput1(const TInputImage1 * image) +{ + this->SetNthInput(0,const_cast<TInputImage1 *>(image)); +} +/** + * Set The second input image. + * \param image The second input image. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +void +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::SetInput2(const TInputImage2 * image) +{ + this->SetNthInput(1,const_cast<TInputImage2 *>(image)); +} +/** + * Get the first input image. + * \return The first input image. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +typename ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::InputImage1Type * +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::GetInput1(void) +{ + return const_cast<InputImage1Type *>(this->GetInput(0)); +} +/** + * Get the second input image. + * \return The second input image. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +typename ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::InputImage2Type * +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::GetInput2(void) +{ + return const_cast<InputImage2Type *>(this->GetInput(1)); +} +/** + * Main computation method. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +void +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::GenerateData() +{ + // retrieves inputs and output pointer + InputImage1PointerType input1 = this->GetInput1(); + InputImage2PointerType input2 = this->GetInput2(); + OutputImagePointerType output = this->GetOutput(); - // Check the requested regions - typename InputImage1Type::RegionType region1 = input1->GetRequestedRegion(); - typename InputImage2Type::RegionType region2 = input2->GetRequestedRegion(); + // Check the requested regions + typename InputImage1Type::RegionType region1 = input1->GetRequestedRegion(); + typename InputImage2Type::RegionType region2 = input2->GetRequestedRegion(); - if(region1!=region2) - { - itkExceptionMacro(<<"InputImage1 and InputImage2 have different requested regions."); - } + if (region1!=region2) + { + itkExceptionMacro(<<"InputImage1 and InputImage2 have different requested regions."); + } - // Iterators typedefs - typedef itk::ImageRegionIterator<InputImage1Type> Input1IteratorType; - typedef itk::ImageRegionIterator<InputImage2Type> Input2IteratorType; - typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; + // Iterators typedefs + typedef itk::ImageRegionIterator<InputImage1Type> Input1IteratorType; + typedef itk::ImageRegionIterator<InputImage2Type> Input2IteratorType; + typedef itk::ImageRegionIterator<OutputImageType> OutputIteratorType; - // Initialize output - output->SetRegions(region1); - output->SetNumberOfComponentsPerPixel(input1->GetNumberOfComponentsPerPixel() - +input2->GetNumberOfComponentsPerPixel()); - output->Allocate(); + // Initialize output + output->SetRegions(region1); + output->SetNumberOfComponentsPerPixel(input1->GetNumberOfComponentsPerPixel() + +input2->GetNumberOfComponentsPerPixel()); + output->Allocate(); - // Iterators declaration - Input1IteratorType input1It(input1,region1); - Input2IteratorType input2It(input2,region1); - OutputIteratorType outputIt(output,region1); + // Iterators declaration + Input1IteratorType input1It(input1,region1); + Input2IteratorType input2It(input2,region1); + OutputIteratorType outputIt(output,region1); - input1It.GoToBegin(); - input2It.GoToBegin(); - outputIt.GoToBegin(); + input1It.GoToBegin(); + input2It.GoToBegin(); + outputIt.GoToBegin(); - // Iterate through the pixel - while(!input1It.IsAtEnd() - &&!input2It.IsAtEnd() - &&!outputIt.IsAtEnd()) - { - // define an output pixel - typename OutputImageType::PixelType output; - // Retrieve the size of each input pixel - unsigned int l1 = input1It.Get().GetSize(); - unsigned int l2 = input2It.Get().GetSize(); - // Set the output pixel size - output.SetSize(l1+l2); - // Loop through each band of the first image - for(unsigned int i=0;i<l1;i++) + // Iterate through the pixel + while (!input1It.IsAtEnd() + &&!input2It.IsAtEnd() + &&!outputIt.IsAtEnd()) + { + // define an output pixel + typename OutputImageType::PixelType output; + // Retrieve the size of each input pixel + unsigned int l1 = input1It.Get().GetSize(); + unsigned int l2 = input2It.Get().GetSize(); + // Set the output pixel size + output.SetSize(l1+l2); + // Loop through each band of the first image + for (unsigned int i=0;i<l1;i++) { // Fill the output pixel output[i]=static_cast<typename OutputImageType::InternalPixelType>(input1It.Get()[i]); } - // Loop though each band of the second image - for(unsigned int i = 0;i<l2;i++) + // Loop though each band of the second image + for (unsigned int i = 0;i<l2;i++) { // Fill the output pixel output[i+l1]=static_cast<typename OutputImageType::InternalPixelType>(input2It.Get()[i]); } - // Set the output pixel - outputIt.Set(output); - // Increment the iterator - ++input1It; - ++input2It; - ++outputIt; - } - } - /** - * PrintSelf method. - */ - template <class TInputImage1,class TInputImage2,class TOutputImage> - void - ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); + // Set the output pixel + outputIt.Set(output); + // Increment the iterator + ++input1It; + ++input2It; + ++outputIt; } +} +/** + * PrintSelf method. + */ +template <class TInputImage1,class TInputImage2,class TOutputImage> +void +ConcatenateVectorImageFilter<TInputImage1,TInputImage2,TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} } // end namespace otb #endif diff --git a/Code/Common/otbDataNode.h b/Code/Common/otbDataNode.h index 10e9c830df00bc7b338a10290b22cfd4cd1bcc40..3822ad24536de4a3140a334ea41d70258265d755 100644 --- a/Code/Common/otbDataNode.h +++ b/Code/Common/otbDataNode.h @@ -32,7 +32,8 @@ namespace otb */ typedef -enum{ +enum +{ ROOT=0, DOCUMENT=1, FOLDER=2, @@ -65,206 +66,207 @@ enum{ */ template <class TPrecision = double, unsigned VDimension = 2, class TValuePrecision = double> class DataNode -: public itk::Object - { - public: - /** Standard class typedef */ - typedef DataNode Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + : public itk::Object +{ +public: + /** Standard class typedef */ + typedef DataNode Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Standard macro */ - itkNewMacro(Self); - itkTypeMacro(DataNode,Object); + /** Standard macro */ + itkNewMacro(Self); + itkTypeMacro(DataNode,Object); - /** Template parameters typedefs */ - typedef TPrecision PrecisionType; - typedef TValuePrecision ValuePrecisionType; - itkStaticConstMacro(Dimension, unsigned int, VDimension); + /** Template parameters typedefs */ + typedef TPrecision PrecisionType; + typedef TValuePrecision ValuePrecisionType; + itkStaticConstMacro(Dimension, unsigned int, VDimension); - /** Internal data typedef */ - typedef itk::Point<PrecisionType,VDimension> PointType; - typedef otb::PolyLineParametricPathWithValue<ValuePrecisionType,VDimension> LineType; - typedef typename LineType::Pointer LinePointerType; - typedef typename LineType::ConstPointer LineConstPointerType; - typedef Polygon<ValuePrecisionType> PolygonType; - typedef typename PolygonType::Pointer PolygonPointerType; - typedef typename PolygonType::ConstPointer PolygonConstPointerType; - typedef ObjectList<PolygonType> PolygonListType; - typedef typename PolygonListType::Pointer PolygonListPointerType; - typedef typename PolygonListType::ConstPointer PolygonListConstPointerType; + /** Internal data typedef */ + typedef itk::Point<PrecisionType,VDimension> PointType; + typedef otb::PolyLineParametricPathWithValue<ValuePrecisionType,VDimension> LineType; + typedef typename LineType::Pointer LinePointerType; + typedef typename LineType::ConstPointer LineConstPointerType; + typedef Polygon<ValuePrecisionType> PolygonType; + typedef typename PolygonType::Pointer PolygonPointerType; + typedef typename PolygonType::ConstPointer PolygonConstPointerType; + typedef ObjectList<PolygonType> PolygonListType; + typedef typename PolygonListType::Pointer PolygonListPointerType; + typedef typename PolygonListType::ConstPointer PolygonListConstPointerType; - /** Fields typedef */ - typedef std::map<std::string,std::string> FieldMapType; - typedef std::pair<std::string,std::string> FieldType; + /** Fields typedef */ + typedef std::map<std::string,std::string> FieldMapType; + typedef std::pair<std::string,std::string> FieldType; - /** Accessors */ - itkGetMacro(NodeType,NodeType); - itkGetStringMacro(NodeId); - itkSetStringMacro(NodeId); + /** Accessors */ + itkGetMacro(NodeType,NodeType); + itkGetStringMacro(NodeId); + itkSetStringMacro(NodeId); - /** - * Set the node type. - * \param type node type. - */ - void SetNodeType(NodeType type); - /** - * \return the node type as a printable string. - */ - std::string GetNodeTypeAsString() const; - /** - * Get the point data, when valid. - * \return The point. - */ - PointType GetPoint() const; - /** - * Get the line data, when valid. - * \return The line. - */ - LinePointerType GetLine() const; - /** - * Get the polygon exterior ring data, when valid. - * \return The polygon exterior ring. - */ - PolygonPointerType GetPolygonExteriorRing() const; - /** - * Get the polygon interior rings data, when valid. - * \return The polygon interior rings list. - */ - PolygonListPointerType GetPolygonInteriorRings() const; - /** - * Set the point data. Node type is automatically set to FEATURE_POINT. - * \param point the point. - */ - void SetPoint(PointType point); - /** - * Set the line data. Node type is automatically set to FEATURE_LINE. - * \param line The line. - */ - void SetLine(LineType* line); - /** - * Set the polygon exterior ring. Node type is automatically set to FEATURE_POLYGON. - * \param polygon The polygon exterior ring. - */ - void SetPolygonExteriorRing(PolygonType* polygon); + /** + * Set the node type. + * \param type node type. + */ + void SetNodeType(NodeType type); + /** + * \return the node type as a printable string. + */ + std::string GetNodeTypeAsString() const; + /** + * Get the point data, when valid. + * \return The point. + */ + PointType GetPoint() const; + /** + * Get the line data, when valid. + * \return The line. + */ + LinePointerType GetLine() const; + /** + * Get the polygon exterior ring data, when valid. + * \return The polygon exterior ring. + */ + PolygonPointerType GetPolygonExteriorRing() const; + /** + * Get the polygon interior rings data, when valid. + * \return The polygon interior rings list. + */ + PolygonListPointerType GetPolygonInteriorRings() const; + /** + * Set the point data. Node type is automatically set to FEATURE_POINT. + * \param point the point. + */ + void SetPoint(PointType point); + /** + * Set the line data. Node type is automatically set to FEATURE_LINE. + * \param line The line. + */ + void SetLine(LineType* line); + /** + * Set the polygon exterior ring. Node type is automatically set to FEATURE_POLYGON. + * \param polygon The polygon exterior ring. + */ + void SetPolygonExteriorRing(PolygonType* polygon); - /** - * Set the polygon interior rings. Node type is automatically set to FEATURE_POLYGON. - * \param polygonList The polygon interior rings list. - */ - void SetPolygonInteriorRings(PolygonListType* polygonList); + /** + * Set the polygon interior rings. Node type is automatically set to FEATURE_POLYGON. + * \param polygonList The polygon interior rings list. + */ + void SetPolygonInteriorRings(PolygonListType* polygonList); - /** - * \return True if node type is DOCUMENT. - */ - bool IsDocument() const; - /** - * \return True if node type is ROOT. - */ - bool IsRoot() const; - /** - * \return True if node type is FOLDER. - */ - bool IsFolder() const; - /** - * \return True if node type is FEATURE_POINT. - */ - bool IsPointFeature() const; - /** - * \return True if node type is FEATURE_LINE. - */ - bool IsLineFeature() const; - /** - * \return True if node type is FEATURE_POLYGON. - */ - bool IsPolygonFeature() const; - /** - * \return True if node type is FEATURE_MULTIPOINT. - */ - bool IsMultiPointFeature() const; - /** - * \return True if node type is FEATURE_MULTILINE. - */ - bool IsMultiLineFeature() const; - /** - * \return True if node type is FEATURE_MULTIPOLYGON. - */ - bool IsMultiPolygonFeature() const; - /** - * \return True if node type is FEATURE_COLLECTION. - */ - bool IsCollectionFeature() const; - /** - * Add a field to the node. - * \param key The name of the field. - * \param value The value of the field. - */ - void SetField(std::string key, std::string value); - /** - * Returns the value associated with a field name. - * \param key The name of the field. - * \return The value of the field. A default value is retuned if the key was not found. - */ - std::string GetField(std::string key) const; - /** - * Remove the field associated with the given key, if possible. - * \param key The name of the field. - */ - void RemoveField(std::string key); - /** - * \return True if the node contains the field named after the given key. - * \param key The name of the field. - */ - bool HasField(std::string key) const; - /** - * \return the nth field of the node as a std::pair of (key,value). - * \param index the index of the field to return. - */ - FieldType GetNthField(unsigned int index) const; - /** - * \return the number of fields in the node. - */ - unsigned int GetNumberOfFields() const; - /** - * Clear all fields. - */ - void ClearFields(); + /** + * \return True if node type is DOCUMENT. + */ + bool IsDocument() const; + /** + * \return True if node type is ROOT. + */ + bool IsRoot() const; + /** + * \return True if node type is FOLDER. + */ + bool IsFolder() const; + /** + * \return True if node type is FEATURE_POINT. + */ + bool IsPointFeature() const; + /** + * \return True if node type is FEATURE_LINE. + */ + bool IsLineFeature() const; + /** + * \return True if node type is FEATURE_POLYGON. + */ + bool IsPolygonFeature() const; + /** + * \return True if node type is FEATURE_MULTIPOINT. + */ + bool IsMultiPointFeature() const; + /** + * \return True if node type is FEATURE_MULTILINE. + */ + bool IsMultiLineFeature() const; + /** + * \return True if node type is FEATURE_MULTIPOLYGON. + */ + bool IsMultiPolygonFeature() const; + /** + * \return True if node type is FEATURE_COLLECTION. + */ + bool IsCollectionFeature() const; + /** + * Add a field to the node. + * \param key The name of the field. + * \param value The value of the field. + */ + void SetField(std::string key, std::string value); + /** + * Returns the value associated with a field name. + * \param key The name of the field. + * \return The value of the field. A default value is retuned if the key was not found. + */ + std::string GetField(std::string key) const; + /** + * Remove the field associated with the given key, if possible. + * \param key The name of the field. + */ + void RemoveField(std::string key); + /** + * \return True if the node contains the field named after the given key. + * \param key The name of the field. + */ + bool HasField(std::string key) const; + /** + * \return the nth field of the node as a std::pair of (key,value). + * \param index the index of the field to return. + */ + FieldType GetNthField(unsigned int index) const; + /** + * \return the number of fields in the node. + */ + unsigned int GetNumberOfFields() const; + /** + * Clear all fields. + */ + void ClearFields(); - protected: - /** Constructor */ - DataNode(); - /** Destructor */ - ~DataNode(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + /** Constructor */ + DataNode(); + /** Destructor */ + ~DataNode() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: - DataNode(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + DataNode(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - /** typedef of the data associated with the node */ - typedef struct { - bool valid; - PointType point; - LinePointerType line; - PolygonPointerType exteriorRing; - PolygonListPointerType interiorRings; - } DataType; + /** typedef of the data associated with the node */ + typedef struct + { + bool valid; + PointType point; + LinePointerType line; + PolygonPointerType exteriorRing; + PolygonListPointerType interiorRings; + } DataType; - /** The node type */ - NodeType m_NodeType; + /** The node type */ + NodeType m_NodeType; - /** The node id */ - std::string m_NodeId; + /** The node id */ + std::string m_NodeId; - /** The data associated with the node */ - DataType m_Data; + /** The data associated with the node */ + DataType m_Data; - /** The fields map */ - FieldMapType m_FieldMap; - }; + /** The fields map */ + FieldMapType m_FieldMap; +}; } // end namespace #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/Common/otbDataNode.txx b/Code/Common/otbDataNode.txx index 4860eda53d4add82acf86933b80228e4c7875b94..b96ac89bb37fb71bb0d9f6ce01ceda6e6eeb669e 100644 --- a/Code/Common/otbDataNode.txx +++ b/Code/Common/otbDataNode.txx @@ -51,7 +51,7 @@ DataNode<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - void DataNode<TPrecision,VDimension,TValuePrecision> +void DataNode<TPrecision,VDimension,TValuePrecision> ::SetLine(LineType* line) { m_NodeType = FEATURE_LINE; @@ -59,30 +59,30 @@ template <class TPrecision, unsigned int VDimension, class TValuePrecision> m_Data.valid = true; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - void +void DataNode<TPrecision,VDimension,TValuePrecision> ::SetPolygonExteriorRing(PolygonType* polygon) { m_NodeType = FEATURE_POLYGON; m_Data.exteriorRing = polygon; - if(!m_Data.interiorRings) - { - m_Data.interiorRings = PolygonListType::New(); - } + if (!m_Data.interiorRings) + { + m_Data.interiorRings = PolygonListType::New(); + } m_Data.valid = true; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - void +void DataNode<TPrecision,VDimension,TValuePrecision> - ::SetPolygonInteriorRings(PolygonListType* polygonList) +::SetPolygonInteriorRings(PolygonListType* polygonList) { m_NodeType = FEATURE_POLYGON; m_Data.interiorRings = polygonList; - if(!m_Data.exteriorRing) - { - m_Data.exteriorRing = PolygonType::New(); - } + if (!m_Data.exteriorRing) + { + m_Data.exteriorRing = PolygonType::New(); + } m_Data.valid = true; } @@ -92,15 +92,15 @@ typename DataNode<TPrecision,VDimension,TValuePrecision> DataNode<TPrecision,VDimension,TValuePrecision> ::GetPoint() const { - if(!IsPointFeature()) - { - itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a point."); - } - if(!m_Data.valid) - { - itkGenericExceptionMacro(<<"Invalid point node."); - } - return m_Data.point; + if (!IsPointFeature()) + { + itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a point."); + } + if (!m_Data.valid) + { + itkGenericExceptionMacro(<<"Invalid point node."); + } + return m_Data.point; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> typename DataNode<TPrecision,VDimension,TValuePrecision> @@ -108,15 +108,15 @@ typename DataNode<TPrecision,VDimension,TValuePrecision> DataNode<TPrecision,VDimension,TValuePrecision> ::GetLine() const { - if(!IsLineFeature()) - { - itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a line."); - } - if(!m_Data.valid) - { - itkGenericExceptionMacro(<<"Invalid line node."); - } - return m_Data.line; + if (!IsLineFeature()) + { + itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a line."); + } + if (!m_Data.valid) + { + itkGenericExceptionMacro(<<"Invalid line node."); + } + return m_Data.line; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> @@ -125,15 +125,15 @@ typename DataNode<TPrecision,VDimension,TValuePrecision> DataNode<TPrecision,VDimension,TValuePrecision> ::GetPolygonExteriorRing() const { - if(!IsPolygonFeature()) - { - itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a polygon."); - } - if(!m_Data.valid || !m_Data.exteriorRing ) - { - itkGenericExceptionMacro(<<"Invalid polygon node."); - } - return m_Data.exteriorRing; + if (!IsPolygonFeature()) + { + itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a polygon."); + } + if (!m_Data.valid || !m_Data.exteriorRing ) + { + itkGenericExceptionMacro(<<"Invalid polygon node."); + } + return m_Data.exteriorRing; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> @@ -142,15 +142,15 @@ typename DataNode<TPrecision,VDimension,TValuePrecision> DataNode<TPrecision,VDimension,TValuePrecision> ::GetPolygonInteriorRings() const { - if(!IsPolygonFeature()) - { - itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a polygon."); - } - if(!m_Data.valid || !m_Data.interiorRings) - { - itkGenericExceptionMacro(<<"Invalid polygon node."); - } - return m_Data.interiorRings; + if (!IsPolygonFeature()) + { + itkGenericExceptionMacro(<<"Node "<<m_NodeId<<" is not a polygon."); + } + if (!m_Data.valid || !m_Data.interiorRings) + { + itkGenericExceptionMacro(<<"Invalid polygon node."); + } + return m_Data.interiorRings; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> @@ -168,58 +168,58 @@ DataNode<TPrecision,VDimension,TValuePrecision> ::GetNodeTypeAsString() const { itk::OStringStream oss; - switch(m_NodeType) + switch (m_NodeType) { - case ROOT: - { - oss<<"Root ("<<m_NodeId<<")"; - break; - } - case DOCUMENT: - { - oss<<"Document ("<<m_NodeId<<")"; - break; - } - case FOLDER: - { - oss<<"Folder ("<<m_NodeId<<")"; - break; - } - case FEATURE_POINT: - { - oss<<"Point ("<<m_NodeId<<") "<<m_Data.point; - break; - } - case FEATURE_LINE: - { - oss<<"Line ("<<m_NodeId<<") "<<m_Data.line->GetVertexList()->Size()<<" points"; - break; - } - case FEATURE_POLYGON: - { - oss<<"Polygon ("<<m_NodeId<<") "<<this->GetPolygonExteriorRing()->GetVertexList()->Size()<<" points, "<<this->GetPolygonInteriorRings()->Size()<<" interior rings"; - break; - } - case FEATURE_MULTIPOINT: - { - oss<<"MultiPoint ("<<m_NodeId<<")"; - break; - } - case FEATURE_MULTILINE: - { - oss<<"MultiLine ("<<m_NodeId<<")"; - break; - } - case FEATURE_MULTIPOLYGON: - { - oss<<"MultiPolygon ("<<m_NodeId<<")"; - break; - } - case FEATURE_COLLECTION: - { - oss<<"Collection ("<<m_NodeId<<")"; - break; - } + case ROOT: + { + oss<<"Root ("<<m_NodeId<<")"; + break; + } + case DOCUMENT: + { + oss<<"Document ("<<m_NodeId<<")"; + break; + } + case FOLDER: + { + oss<<"Folder ("<<m_NodeId<<")"; + break; + } + case FEATURE_POINT: + { + oss<<"Point ("<<m_NodeId<<") "<<m_Data.point; + break; + } + case FEATURE_LINE: + { + oss<<"Line ("<<m_NodeId<<") "<<m_Data.line->GetVertexList()->Size()<<" points"; + break; + } + case FEATURE_POLYGON: + { + oss<<"Polygon ("<<m_NodeId<<") "<<this->GetPolygonExteriorRing()->GetVertexList()->Size()<<" points, "<<this->GetPolygonInteriorRings()->Size()<<" interior rings"; + break; + } + case FEATURE_MULTIPOINT: + { + oss<<"MultiPoint ("<<m_NodeId<<")"; + break; + } + case FEATURE_MULTILINE: + { + oss<<"MultiLine ("<<m_NodeId<<")"; + break; + } + case FEATURE_MULTIPOLYGON: + { + oss<<"MultiPolygon ("<<m_NodeId<<")"; + break; + } + case FEATURE_COLLECTION: + { + oss<<"Collection ("<<m_NodeId<<")"; + break; + } } return oss.str(); } @@ -232,21 +232,21 @@ DataNode<TPrecision,VDimension,TValuePrecision> m_FieldMap[key] = value; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - std::string +std::string DataNode<TPrecision,VDimension,TValuePrecision> ::GetField(std::string key) const { - if(HasField(key)) - { - return (*m_FieldMap.find(key)).second; - } + if (HasField(key)) + { + return (*m_FieldMap.find(key)).second; + } else - { - return "Unknown Key"; - } + { + return "Unknown Key"; + } } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - void +void DataNode<TPrecision,VDimension,TValuePrecision> ::RemoveField(std::string key) { @@ -265,69 +265,69 @@ typename DataNode<TPrecision,VDimension,TValuePrecision> DataNode<TPrecision,VDimension,TValuePrecision> ::GetNthField(unsigned int index) const { - if(index<GetNumberOfFields()) - { - FieldMapType::iterator it = m_FieldMap.begin(); - - for(unsigned int i = 0;i<index;++i) + if (index<GetNumberOfFields()) { - ++it; - } - return (*it); + FieldMapType::iterator it = m_FieldMap.begin(); + + for (unsigned int i = 0;i<index;++i) + { + ++it; } + return (*it); + } return FieldType("No key","No value"); } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - unsigned int +unsigned int DataNode<TPrecision,VDimension,TValuePrecision> ::GetNumberOfFields() const { return m_FieldMap.size(); } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - void +void DataNode<TPrecision,VDimension,TValuePrecision> ::ClearFields() { m_FieldMap.clear(); } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsDocument() const { return m_NodeType == DOCUMENT; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsRoot() const { return m_NodeType == ROOT; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsFolder() const { return m_NodeType == FOLDER; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsPointFeature() const { return m_NodeType == FEATURE_POINT; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsLineFeature() const { return m_NodeType == FEATURE_LINE; } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsPolygonFeature() const { @@ -335,7 +335,7 @@ DataNode<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsMultiPointFeature() const { @@ -343,7 +343,7 @@ DataNode<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsMultiLineFeature() const { @@ -351,7 +351,7 @@ DataNode<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsMultiPolygonFeature() const { @@ -359,7 +359,7 @@ DataNode<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - bool +bool DataNode<TPrecision,VDimension,TValuePrecision> ::IsCollectionFeature() const { diff --git a/Code/Common/otbDifferenceImageFilter.h b/Code/Common/otbDifferenceImageFilter.h index dec5bc04ce1969318a345d0c1b3a21d8798b8183..ced28a1e4ee1e3d01ecb68c4a6d27f9ec212d475 100644 --- a/Code/Common/otbDifferenceImageFilter.h +++ b/Code/Common/otbDifferenceImageFilter.h @@ -21,7 +21,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT DifferenceImageFilter : - public itk::ImageToImageFilter<TInputImage, TOutputImage> + public itk::ImageToImageFilter<TInputImage, TOutputImage> { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbDifferenceImageFilter.txx b/Code/Common/otbDifferenceImageFilter.txx index c39e3064ed85d45a61eefd95a6957dcdf8306192..91dc7d251a1d8acba1deb7c97aa0945c7a865a18 100644 --- a/Code/Common/otbDifferenceImageFilter.txx +++ b/Code/Common/otbDifferenceImageFilter.txx @@ -48,7 +48,7 @@ DifferenceImageFilter<TInputImage, TOutputImage> os << indent << "MeanDifference: " << m_MeanDifference << "\n"; os << indent << "TotalDifference: " << m_TotalDifference << "\n"; os << indent << "NumberOfPixelsWithDifferences: " - << m_NumberOfPixelsWithDifferences << "\n"; + << m_NumberOfPixelsWithDifferences << "\n"; } //---------------------------------------------------------------------------- @@ -76,10 +76,10 @@ DifferenceImageFilter<TInputImage, TOutputImage> ::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); - if(this->GetInput(0)->GetNumberOfComponentsPerPixel()!=this->GetInput(1)->GetNumberOfComponentsPerPixel()) - { - itkExceptionMacro(<<"Image 1 has "<<this->GetInput(0)->GetNumberOfComponentsPerPixel()<<" bands, whereas image 2 has "<<this->GetInput(1)->GetNumberOfComponentsPerPixel()); - } + if (this->GetInput(0)->GetNumberOfComponentsPerPixel()!=this->GetInput(1)->GetNumberOfComponentsPerPixel()) + { + itkExceptionMacro(<<"Image 1 has "<<this->GetInput(0)->GetNumberOfComponentsPerPixel()<<" bands, whereas image 2 has "<<this->GetInput(1)->GetNumberOfComponentsPerPixel()); + } this->GetOutput()->SetNumberOfComponentsPerPixel(this->GetInput(0)->GetNumberOfComponentsPerPixel()); } //---------------------------------------------------------------------------- @@ -103,11 +103,11 @@ DifferenceImageFilter<TInputImage, TOutputImage> m_ThreadNumberOfPixels.SetSize(numberOfThreads); // Initialize the temporaries - for(int i = 0; i<numberOfThreads;++i) - { - m_ThreadDifferenceSum.push_back(m_TotalDifference); - } - m_ThreadNumberOfPixels.Fill(0); + for (int i = 0; i<numberOfThreads;++i) + { + m_ThreadDifferenceSum.push_back(m_TotalDifference); + } + m_ThreadNumberOfPixels.Fill(0); } //---------------------------------------------------------------------------- @@ -135,7 +135,7 @@ DifferenceImageFilter<TInputImage, TOutputImage> // Create a radius of pixels. RadiusType radius; - if(m_ToleranceRadius > 0) + if (m_ToleranceRadius > 0) { radius.Fill(m_ToleranceRadius); } @@ -159,9 +159,9 @@ DifferenceImageFilter<TInputImage, TOutputImage> OutputIterator out(outputPtr, *face); // Iterate over output image. test.OverrideBoundaryCondition(&nbc); - for(valid.GoToBegin(), test.GoToBegin(), out.GoToBegin(); - !valid.IsAtEnd(); - ++valid, ++test, ++out) + for (valid.GoToBegin(), test.GoToBegin(), out.GoToBegin(); + !valid.IsAtEnd(); + ++valid, ++test, ++out) { // Get the current valid pixel. InputPixelType t = valid.Get(); @@ -176,15 +176,15 @@ DifferenceImageFilter<TInputImage, TOutputImage> // sign. RealType difference = static_cast<RealType>(t) - static_cast<RealType>(test.GetPixel(i)); - for(unsigned int j = 0;j<difference.Size();++j) + for (unsigned int j = 0;j<difference.Size();++j) { - if(difference[j]<0) + if (difference[j]<0) { difference[j]*=-1; } ScalarRealType d = static_cast<ScalarRealType>(difference[j]); - if(d < minimumDifference[j]) + if (d < minimumDifference[j]) { minimumDifference[j] = d; // std::cout << std::setprecision(16) << minimumDifference[j] << std::endl; @@ -195,40 +195,40 @@ DifferenceImageFilter<TInputImage, TOutputImage> } } - //for complex and vector type. FIXME: module might be better + //for complex and vector type. FIXME: module might be better // ScalarRealType tMax=vcl_abs(t[0]); ScalarRealType tMax=0.01;//Avoiding the 0 case for neighborhood computing - // NB: still more restrictive than before for small values. + // NB: still more restrictive than before for small values. for (unsigned int j = 0;j<t.Size();++j) { if (vcl_abs(t[j])>tMax) tMax = vcl_abs(t[j]); } - // Check if difference is above threshold - // the threshold is interpreted as relative to the value + // Check if difference is above threshold + // the threshold is interpreted as relative to the value bool isDifferent = false; - for(unsigned int j = 0;j<minimumDifference.Size();++j) + for (unsigned int j = 0;j<minimumDifference.Size();++j) { - if(minimumDifference[j] > m_DifferenceThreshold * tMax) + if (minimumDifference[j] > m_DifferenceThreshold * tMax) { // std::cout << std::setprecision(16) << minimumDifference[j] << std::endl; isDifferent = true; } } - if(isDifferent) + if (isDifferent) { - // Store the minimum difference value in the output image. + // Store the minimum difference value in the output image. out.Set(minimumDifference); - // Update difference image statistics. + // Update difference image statistics. m_ThreadDifferenceSum[threadId] += minimumDifference; m_ThreadNumberOfPixels[threadId]++; } else { - // Difference is below threshold. + // Difference is below threshold. out.Set(itk::NumericTraits<OutputPixelType>::Zero(minimumDifference)); } @@ -245,11 +245,11 @@ DifferenceImageFilter<TInputImage, TOutputImage> { // Set statistics about difference image. int numberOfThreads = this->GetNumberOfThreads(); - for(int i=0; i < numberOfThreads; ++i) - { + for (int i=0; i < numberOfThreads; ++i) + { m_TotalDifference += m_ThreadDifferenceSum[i]; m_NumberOfPixelsWithDifferences += m_ThreadNumberOfPixels[i]; - } + } // Get the total number of pixels processed in the region. // This is different from the m_TotalNumberOfPixels which @@ -260,7 +260,7 @@ DifferenceImageFilter<TInputImage, TOutputImage> // Calculate the mean difference. - m_MeanDifference = m_TotalDifference / numberOfPixels; + m_MeanDifference = m_TotalDifference / numberOfPixels; } } // end namespace otb diff --git a/Code/Common/otbDrawLineSpatialObjectFilter.h b/Code/Common/otbDrawLineSpatialObjectFilter.h index 321be5c194088993c0bde9e805c3993dea8a2415..1e7575907d5472b9d646dbb500fed9e0149a7424 100644 --- a/Code/Common/otbDrawLineSpatialObjectFilter.h +++ b/Code/Common/otbDrawLineSpatialObjectFilter.h @@ -38,15 +38,15 @@ namespace otb template <class TInputImage, class TOutputImage> class ITK_EXPORT DrawLineSpatialObjectFilter : -public itk::SpatialObjectToImageFilter< itk::LineSpatialObject<2>, TOutputImage > + public itk::SpatialObjectToImageFilter< itk::LineSpatialObject<2>, TOutputImage > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); @@ -61,9 +61,9 @@ public: typedef itk::SmartPointer<const Self> ConstPointer; typedef typename Superclass::InputSpatialObjectType InputLineType; - typedef typename InputLineType::PointListType PointListType; - - typedef itk::ProcessObject ProcessObjectType; + typedef typename InputLineType::PointListType PointListType; + + typedef itk::ProcessObject ProcessObjectType; /** Method for management of the "object factory". */ diff --git a/Code/Common/otbDrawLineSpatialObjectFilter.txx b/Code/Common/otbDrawLineSpatialObjectFilter.txx index f6e02cc5f8760b6f76ca0cae1add5568c5e7aa91..9eccb0b75731f63dfaa5b7b411661b16c150048e 100644 --- a/Code/Common/otbDrawLineSpatialObjectFilter.txx +++ b/Code/Common/otbDrawLineSpatialObjectFilter.txx @@ -51,7 +51,7 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> ::SetInputLine(const InputLineType *line) { this->ProcessObjectType::SetNthInput(0, - const_cast< InputLineType * >( line ) ); + const_cast< InputLineType * >( line ) ); } @@ -60,8 +60,8 @@ typename DrawLineSpatialObjectFilter<TInputImage, TOutputImage>::InputLineType * DrawLineSpatialObjectFilter<TInputImage, TOutputImage> ::GetInput(void) { - return static_cast<InputLineType *> - (this->ProcessObjectType::GetInput(0) ); + return static_cast<InputLineType *> + (this->ProcessObjectType::GetInput(0) ); } @@ -71,7 +71,7 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> ::SetInputImage(const InputImageType *image) { this->ProcessObjectType::SetNthInput(1, - const_cast< InputImageType * >( image ) ); + const_cast< InputImageType * >( image ) ); } @@ -81,12 +81,12 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> ::GetInputImage(void) { if (this->GetNumberOfInputs() < 2) - { + { return 0; - } + } return static_cast<const InputImageType *> - (this->ProcessObjectType::GetInput(1) ); + (this->ProcessObjectType::GetInput(1) ); } template <class TInputImage, class TOutputImage> @@ -98,7 +98,7 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> typename InputImageType::ConstPointer input = this->GetInputImage(); typename OutputImageType::Pointer output = this->GetOutput(); - // Get the region + // Get the region typename OutputImageType::RegionType region; @@ -120,7 +120,7 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> // Copy the input image in the output image for ( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt,++inputIt) - outputIt.Set( static_cast<OutputPixelType>(inputIt.Get()) ); + outputIt.Set( static_cast<OutputPixelType>(inputIt.Get()) ); // Get the LineSpatialObject InputLineType * inputLine = this->GetInput(); @@ -153,59 +153,59 @@ DrawLineSpatialObjectFilter<TInputImage, TOutputImage> // of pixels between the two points is most important if ( (DeltaX >= DeltaY) && (DeltaX > 0.) ) - { - double Xmin, Xmax; - /*Xmin = std::min(x1,x2); - Xmax = std::max(x1,x2);*/ - Xmin = x1 < x2 ? x1 : x2; - Xmax = x1 > x2 ? x1 : x2; - - // Slope of the line y=slope*(x-x1)+y1 - double Slope = (y2-y1) / (x2-x1); - - // Set a point for each x value between xmin and xmax - for ( double x = Xmin; x <= Xmax; x++) - { - outputIndex[0] = static_cast<unsigned long>( x ); - outputIndex[1] = static_cast<unsigned long>( Slope*(x-x1) + y1 ); + { + double Xmin, Xmax; + /*Xmin = std::min(x1,x2); + Xmax = std::max(x1,x2);*/ + Xmin = x1 < x2 ? x1 : x2; + Xmax = x1 > x2 ? x1 : x2; + + // Slope of the line y=slope*(x-x1)+y1 + double Slope = (y2-y1) / (x2-x1); + + // Set a point for each x value between xmin and xmax + for ( double x = Xmin; x <= Xmax; x++) + { + outputIndex[0] = static_cast<unsigned long>( x ); + outputIndex[1] = static_cast<unsigned long>( Slope*(x-x1) + y1 ); - // Set the point if the pixel index belongs to the output image - if( region.IsInside( outputIndex ) ) - output->SetPixel( outputIndex, m_Value); + // Set the point if the pixel index belongs to the output image + if ( region.IsInside( outputIndex ) ) + output->SetPixel( outputIndex, m_Value); - } + } - } - else if ( DeltaX < DeltaY ) - { - double Ymin, Ymax; - /*Ymin = std::min(y1,y2); - Ymax = std::max(y1,y2);*/ - Ymin = y1 < y2 ? y1 : y2; - Ymax = y1 > y2 ? y1 : y2; + } + else if ( DeltaX < DeltaY ) + { + double Ymin, Ymax; + /*Ymin = std::min(y1,y2); + Ymax = std::max(y1,y2);*/ + Ymin = y1 < y2 ? y1 : y2; + Ymax = y1 > y2 ? y1 : y2; - double SlopeInv = (x2-x1) / (y2-y1); + double SlopeInv = (x2-x1) / (y2-y1); - for ( double y = Ymin; y <= Ymax; y++) - { - outputIndex[0] = static_cast<unsigned long>( SlopeInv * (y-y1) + x1 ); - outputIndex[1] = static_cast<unsigned long>( y ); + for ( double y = Ymin; y <= Ymax; y++) + { + outputIndex[0] = static_cast<unsigned long>( SlopeInv * (y-y1) + x1 ); + outputIndex[1] = static_cast<unsigned long>( y ); - if( region.IsInside( outputIndex ) ) - output->SetPixel( outputIndex, m_Value); + if ( region.IsInside( outputIndex ) ) + output->SetPixel( outputIndex, m_Value); - } - } + } + } - // Exception -/* else - { - itkExceptionMacro(<< "otb::DrawLineSpatialObjectFilter::GenerateData : " - << "the line is defined by one point : deltaX = deltaY = 0."); - } - */ + // Exception + /* else + { + itkExceptionMacro(<< "otb::DrawLineSpatialObjectFilter::GenerateData : " + << "the line is defined by one point : deltaX = deltaY = 0."); + } + */ } /** diff --git a/Code/Common/otbDrawLineSpatialObjectListFilter.h b/Code/Common/otbDrawLineSpatialObjectListFilter.h index a4d7eb4eaa8bb11281d4762b454c16d5903a1e6f..88ccb44a431551b4801585fe385d3e66705faef0 100644 --- a/Code/Common/otbDrawLineSpatialObjectListFilter.h +++ b/Code/Common/otbDrawLineSpatialObjectListFilter.h @@ -41,15 +41,15 @@ namespace otb template <class TInputImage, class TOutputImage> class ITK_EXPORT DrawLineSpatialObjectListFilter : -public itk::ImageToImageFilter< TInputImage, TOutputImage > + public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); @@ -71,7 +71,7 @@ public: typedef DrawLineSpatialObjectFilter< OutputImageType, OutputImageType > DrawLineType; typedef itk::RescaleIntensityImageFilter< InputImageType, - OutputImageType > RescalerType; + OutputImageType > RescalerType; typedef itk::ProcessObject ProcessObjectType; diff --git a/Code/Common/otbDrawLineSpatialObjectListFilter.txx b/Code/Common/otbDrawLineSpatialObjectListFilter.txx index f734e026b00cd19ebcd9e898ab23f3391f53c5b8..5e000c5464f389f3b3201830ea320111a68f5df3 100644 --- a/Code/Common/otbDrawLineSpatialObjectListFilter.txx +++ b/Code/Common/otbDrawLineSpatialObjectListFilter.txx @@ -51,7 +51,7 @@ DrawLineSpatialObjectListFilter<TInputImage, TOutputImage> ::SetInputLineSpatialObjectList(const LinesListType * list) { this->ProcessObjectType::SetNthInput(1, - const_cast< LinesListType * >( list ) ); + const_cast< LinesListType * >( list ) ); } @@ -61,9 +61,9 @@ typename DrawLineSpatialObjectListFilter<TInputImage, TOutputImage>::LinesListTy DrawLineSpatialObjectListFilter<TInputImage, TOutputImage> ::GetInputLineSpatialObjectList(void) { - //ROMAIN + //ROMAIN return static_cast</*const */LinesListType *> - (this->ProcessObjectType::GetInput(1) ); + (this->ProcessObjectType::GetInput(1) ); } template <class TInputImage, class TOutputImage> @@ -100,16 +100,16 @@ DrawLineSpatialObjectListFilter<TInputImage, TOutputImage> // Draw each line of the list - while( itList != list->end() ) - { + while ( itList != list->end() ) + { - m_DrawLineFilter->SetInputImage( this->GetOutput() ); - m_DrawLineFilter->SetInputLine( *itList ); - m_DrawLineFilter->Update(); + m_DrawLineFilter->SetInputImage( this->GetOutput() ); + m_DrawLineFilter->SetInputLine( *itList ); + m_DrawLineFilter->Update(); - ++itList; + ++itList; - } + } this->GraftOutput( m_DrawLineFilter->GetOutput() ); diff --git a/Code/Common/otbDrawPathListFilter.txx b/Code/Common/otbDrawPathListFilter.txx index 3a004d6cb55bafaf3aa2dac101c90f6a9fb32372..bde5aabde73b3f0125263d370b2bec13393993ed 100644 --- a/Code/Common/otbDrawPathListFilter.txx +++ b/Code/Common/otbDrawPathListFilter.txx @@ -57,9 +57,9 @@ DrawPathListFilter<TInputImage,TInputPath,TOutputImage> ::GetInputPath(void) { if (this->GetNumberOfInputs() < 2) - { + { return 0; - } + } return static_cast<const InputPathListType *>(this->ProcessObjectType::GetInput(1)); } /** @@ -86,18 +86,18 @@ DrawPathListFilter<TInputImage,TInputPath,TOutputImage> OutputIteratorType outIt(outputPtr,outputPtr->GetLargestPossibleRegion()); InputIteratorType inIt(inputPtr,inputPtr->GetLargestPossibleRegion()); - for(outIt.GoToBegin(),inIt.GoToBegin(); - (!outIt.IsAtEnd() && !inIt.IsAtEnd()); - ++outIt,++inIt) + for (outIt.GoToBegin(),inIt.GoToBegin(); + (!outIt.IsAtEnd() && !inIt.IsAtEnd()); + ++outIt,++inIt) { outIt.Set(static_cast<OutputImagePixelType>(inIt.Get())); } // Then we use otb::PolyLineImageIterator to draw polylines - for(PathListIteratorType plIt = pathListPtr->Begin(); plIt!=pathListPtr->End();++plIt) + for (PathListIteratorType plIt = pathListPtr->Begin(); plIt!=pathListPtr->End();++plIt) { - OutputImagePixelType value = itk::NumericTraits<OutputImagePixelType>::Zero; - if(m_UseInternalPathValue && plIt.Get()->GetMetaDataDictionary().HasKey("Value")) + OutputImagePixelType value = itk::NumericTraits<OutputImagePixelType>::Zero; + if (m_UseInternalPathValue && plIt.Get()->GetMetaDataDictionary().HasKey("Value")) { itk::ExposeMetaData<OutputImagePixelType>(plIt.Get()->GetMetaDataDictionary(),"Value",value); } @@ -106,7 +106,7 @@ DrawPathListFilter<TInputImage,TInputPath,TOutputImage> value = static_cast<OutputImagePixelType>(m_PathValue); } PolyLineIteratorType imageIt(outputPtr,plIt.Get()); - for(imageIt.GoToBegin();!imageIt.IsAtEnd();++imageIt) + for (imageIt.GoToBegin();!imageIt.IsAtEnd();++imageIt) { if (m_AddValue) { diff --git a/Code/Common/otbExtractROI.h b/Code/Common/otbExtractROI.h index bca4ab527e741ff8a098c20e246b23f782681a5d..ada262a4c6421ab323cee4431b798bd3dc7741d8 100644 --- a/Code/Common/otbExtractROI.h +++ b/Code/Common/otbExtractROI.h @@ -35,7 +35,7 @@ namespace otb */ template <class TInputPixel, class TOutputPixel> class ITK_EXPORT ExtractROI: - public ExtractROIBase<Image<TInputPixel,2> , Image<TOutputPixel,2> > + public ExtractROIBase<Image<TInputPixel,2> , Image<TOutputPixel,2> > { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbExtractROI.txx b/Code/Common/otbExtractROI.txx index 46565da73ffc14c470169537fe364b40fee354cd..6cff421f3ca0ce48a885a36b6a73d947fbc231e1 100644 --- a/Code/Common/otbExtractROI.txx +++ b/Code/Common/otbExtractROI.txx @@ -61,8 +61,8 @@ void ExtractROI<TInputPixel, TOutputPixel> ::GenerateOutputInformation() { - // Call to the base class method - Superclass::GenerateOutputInformation(); + // Call to the base class method + Superclass::GenerateOutputInformation(); } template <class TInputPixel, class TOutputPixel> @@ -92,14 +92,14 @@ ExtractROI<TInputPixel, TOutputPixel> InputIterator inIt(inputPtr, inputRegionForThread); // walk the output region, and sample the input image - while( !outIt.IsAtEnd() ) - { + while ( !outIt.IsAtEnd() ) + { // copy the input pixel to the output outIt.Set( inIt.Get()); ++outIt; ++inIt; progress.CompletedPixel(); - } + } } diff --git a/Code/Common/otbExtractROIBase.h b/Code/Common/otbExtractROIBase.h index e3256709fd9e39fbc071bbb3283ba7dd4d1580c6..8ea855b4023956cf1522466f52e4fbf1092c3fff 100644 --- a/Code/Common/otbExtractROIBase.h +++ b/Code/Common/otbExtractROIBase.h @@ -41,7 +41,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ExtractROIBase: - public itk::ImageToImageFilter<TInputImage,TOutputImage> + public itk::ImageToImageFilter<TInputImage,TOutputImage> { public: /** Standard class typedefs. */ @@ -82,9 +82,9 @@ public: typedef itk::ImageToImageFilterDetail::ExtractImageFilterRegionCopier<itkGetStaticConstMacro(InputImageDimension), - itkGetStaticConstMacro(OutputImageDimension)> ExtractROIBaseRegionCopierType; + itkGetStaticConstMacro(OutputImageDimension)> ExtractROIBaseRegionCopierType; - itkGetMacro(ExtractionRegion, InputImageRegionType); + itkGetMacro(ExtractionRegion, InputImageRegionType); /** Give the region to extract, same effect as given m_StartX/Y and m_SizeX/Y*/ void SetExtractionRegion(InputImageRegionType roi); @@ -132,7 +132,7 @@ protected: * * \sa ImageToImageFilter::CallCopyRegion() */ virtual void CallCopyOutputRegionToInputRegion(InputImageRegionType &destRegion, - const OutputImageRegionType &srcRegion); + const OutputImageRegionType &srcRegion); /** ExtractROIBase can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() @@ -149,15 +149,15 @@ protected: void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) - { + { - }; + }; - /** Set/Get the output image region. - * If any of the ExtractionRegion.Size = 0 for any particular dimension dim, - * we have to collapse dimension dim. This means the output image will have - * 'c' dimensions less than the input image, where c = # of - * ExtractionRegion.Size = 0. */ + /** Set/Get the output image region. + * If any of the ExtractionRegion.Size = 0 for any particular dimension dim, + * we have to collapse dimension dim. This means the output image will have + * 'c' dimensions less than the input image, where c = # of + * ExtractionRegion.Size = 0. */ void SetInternalExtractionRegion(InputImageRegionType extractRegion); diff --git a/Code/Common/otbExtractROIBase.txx b/Code/Common/otbExtractROIBase.txx index 4e23d1aac3e1277fe9c81efba2b7da3fcf3862ab..7df036e2e79eddf339105a5d08bf73fbf2de2191 100644 --- a/Code/Common/otbExtractROIBase.txx +++ b/Code/Common/otbExtractROIBase.txx @@ -35,10 +35,10 @@ namespace otb template <class TInputImage, class TOutputImage> ExtractROIBase<TInputImage,TOutputImage> ::ExtractROIBase() : itk::ImageToImageFilter<TInputImage,TOutputImage>(), - m_StartX(0), - m_StartY(0), - m_SizeX(0), - m_SizeY(0) + m_StartX(0), + m_StartY(0), + m_SizeX(0), + m_SizeY(0) { } @@ -69,9 +69,9 @@ ExtractROIBase<TInputImage,TOutputImage> OutputImageIndexType index = destRegion.GetIndex(); for (unsigned int i = 0; i < InputImageDimension; ++i) - { - index[i]+=m_ExtractionRegion.GetIndex()[i]; - } + { + index[i]+=m_ExtractionRegion.GetIndex()[i]; + } destRegion.SetIndex(index); } @@ -93,19 +93,19 @@ ExtractROIBase<TInputImage,TOutputImage> * matches the number of dimensions in the output image. **/ for (unsigned int i = 0; i < InputImageDimension; ++i) - { + { if (inputSize[i]) - { + { outputSize[nonzeroSizeCount] = inputSize[i]; outputIndex[nonzeroSizeCount] =0; nonzeroSizeCount++; - } } + } if (nonzeroSizeCount != OutputImageDimension) - { + { itkExceptionMacro("Extraction Region not consistent with output image"); - } + } m_OutputImageRegion.SetSize(outputSize); m_OutputImageRegion.SetIndex(outputIndex); @@ -150,7 +150,7 @@ ExtractROIBase<TInputImage,TOutputImage> InputImageIndexType offset = m_ExtractionRegion.GetIndex(); for (unsigned int i=0; i < InputImageDimension; ++i) - { + { index[i]+=offset[i]; } requestedRegion.SetIndex(index); @@ -182,7 +182,7 @@ ExtractROIBase<TInputImage,TOutputImage> typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); // Check if input exists or not before doing anything - if(!inputPtr) + if (!inputPtr) { return; } @@ -236,7 +236,7 @@ ExtractROIBase<TInputImage,TOutputImage> const itk::ImageBase<InputImageDimension> *phyData; phyData - = dynamic_cast<const itk::ImageBase<InputImageDimension>*>(this->GetInput()); + = dynamic_cast<const itk::ImageBase<InputImageDimension>*>(this->GetInput()); if (phyData) { @@ -245,11 +245,11 @@ ExtractROIBase<TInputImage,TOutputImage> // dimensions to copy unsigned int i; const typename InputImageType::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::DirectionType& - inputDirection = inputPtr->GetDirection(); + inputDirection = inputPtr->GetDirection(); const typename InputImageType::PointType& - inputOrigin = inputPtr->GetOrigin(); + inputOrigin = inputPtr->GetOrigin(); typename OutputImageType::SpacingType outputSpacing; typename OutputImageType::DirectionType outputDirection; @@ -293,7 +293,7 @@ ExtractROIBase<TInputImage,TOutputImage> for (unsigned int dim = 0; dim < OutputImageDimension; ++dim) { outputDirection[nonZeroCount][dim] = - inputDirection[nonZeroCount][dim]; + inputDirection[nonZeroCount][dim]; } nonZeroCount++; } @@ -313,8 +313,8 @@ ExtractROIBase<TInputImage,TOutputImage> { // pointer could not be cast back down itkExceptionMacro(<< "otb::ExtractROIBase::GenerateOutputInformation " - << "cannot cast input to " - << typeid(itk::ImageBase<InputImageDimension>*).name() ); + << "cannot cast input to " + << typeid(itk::ImageBase<InputImageDimension>*).name() ); } diff --git a/Code/Common/otbFilterWatcherBase.cxx b/Code/Common/otbFilterWatcherBase.cxx index 58fb14e197d768f492d9c2fe73c93196c8063ac8..d7769d5daef0cedcae54f4a9ec9f4c474605388d 100644 --- a/Code/Common/otbFilterWatcherBase.cxx +++ b/Code/Common/otbFilterWatcherBase.cxx @@ -33,7 +33,7 @@ FilterWatcherBase FilterWatcherBase ::FilterWatcherBase(itk::ProcessObject* process, - const char *comment) + const char *comment) { // Initialize state m_Process = process; @@ -46,21 +46,21 @@ FilterWatcherBase // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::StartFilter); + &FilterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::EndFilter); + &FilterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::ShowProgress); + &FilterWatcherBase::ShowProgress); // Add the commands as observers m_StartTag = m_Process->AddObserver(itk::StartEvent(), - m_StartFilterCommand); + m_StartFilterCommand); m_EndTag = m_Process->AddObserver(itk::EndEvent(), - m_EndFilterCommand); + m_EndFilterCommand); m_ProgressTag = m_Process->AddObserver(itk::ProgressEvent(), - m_ProgressFilterCommand); + m_ProgressFilterCommand); } FilterWatcherBase @@ -68,20 +68,20 @@ FilterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartFilterCommand) - { - m_Process->RemoveObserver(m_StartTag); - } - if (m_EndFilterCommand) { - m_Process->RemoveObserver(m_EndTag); - } - if (m_ProgressFilterCommand) - { - m_Process->RemoveObserver(m_ProgressTag); - } + if (m_StartFilterCommand) + { + m_Process->RemoveObserver(m_StartTag); + } + if (m_EndFilterCommand) + { + m_Process->RemoveObserver(m_EndTag); + } + if (m_ProgressFilterCommand) + { + m_Process->RemoveObserver(m_ProgressTag); } + } // Initialize state m_TimeProbe = watch.m_TimeProbe; @@ -94,25 +94,25 @@ FilterWatcherBase // Create a series of commands if (m_Process) - { - m_StartFilterCommand = CommandType::New(); - m_EndFilterCommand = CommandType::New(); - m_ProgressFilterCommand = CommandType::New(); - - // Assign the callbacks - m_StartFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::StartFilter); - m_EndFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::EndFilter); - m_ProgressFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::ShowProgress); - - // Add the commands as observers - m_StartTag = m_Process->AddObserver(itk::StartEvent(), m_StartFilterCommand); - m_EndTag = m_Process->AddObserver(itk::EndEvent(), m_EndFilterCommand); - m_ProgressTag - = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); - } + { + m_StartFilterCommand = CommandType::New(); + m_EndFilterCommand = CommandType::New(); + m_ProgressFilterCommand = CommandType::New(); + + // Assign the callbacks + m_StartFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::StartFilter); + m_EndFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::EndFilter); + m_ProgressFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::ShowProgress); + + // Add the commands as observers + m_StartTag = m_Process->AddObserver(itk::StartEvent(), m_StartFilterCommand); + m_EndTag = m_Process->AddObserver(itk::EndEvent(), m_EndFilterCommand); + m_ProgressTag + = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); + } } void @@ -121,20 +121,20 @@ FilterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartFilterCommand) { - m_Process->RemoveObserver(m_StartTag); - } - if (m_EndFilterCommand) - { - m_Process->RemoveObserver(m_EndTag); - } - if (m_ProgressFilterCommand) - { - m_Process->RemoveObserver(m_ProgressTag); - } + if (m_StartFilterCommand) + { + m_Process->RemoveObserver(m_StartTag); + } + if (m_EndFilterCommand) + { + m_Process->RemoveObserver(m_EndTag); } + if (m_ProgressFilterCommand) + { + m_Process->RemoveObserver(m_ProgressTag); + } + } // Initialize state m_TimeProbe = watch.m_TimeProbe; @@ -147,25 +147,25 @@ FilterWatcherBase // Create a series of commands if (m_Process) - { - m_StartFilterCommand = CommandType::New(); - m_EndFilterCommand = CommandType::New(); - m_ProgressFilterCommand = CommandType::New(); - - // Assign the callbacks - m_StartFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::StartFilter); - m_EndFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::EndFilter); - m_ProgressFilterCommand->SetCallbackFunction(this, - &FilterWatcherBase::ShowProgress); - - // Add the commands as observers - m_StartTag = m_Process->AddObserver(itk::StartEvent(), m_StartFilterCommand); - m_EndTag = m_Process->AddObserver(itk::EndEvent(), m_EndFilterCommand); - m_ProgressTag - = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); - } + { + m_StartFilterCommand = CommandType::New(); + m_EndFilterCommand = CommandType::New(); + m_ProgressFilterCommand = CommandType::New(); + + // Assign the callbacks + m_StartFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::StartFilter); + m_EndFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::EndFilter); + m_ProgressFilterCommand->SetCallbackFunction(this, + &FilterWatcherBase::ShowProgress); + + // Add the commands as observers + m_StartTag = m_Process->AddObserver(itk::StartEvent(), m_StartFilterCommand); + m_EndTag = m_Process->AddObserver(itk::EndEvent(), m_EndFilterCommand); + m_ProgressTag + = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); + } } FilterWatcherBase @@ -173,20 +173,20 @@ FilterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartFilterCommand) { - m_Process->RemoveObserver(m_StartTag); - } - if (m_EndFilterCommand) - { - m_Process->RemoveObserver(m_EndTag); - } - if (m_ProgressFilterCommand) - { - m_Process->RemoveObserver(m_ProgressTag); - } + if (m_StartFilterCommand) + { + m_Process->RemoveObserver(m_StartTag); } + if (m_EndFilterCommand) + { + m_Process->RemoveObserver(m_EndTag); + } + if (m_ProgressFilterCommand) + { + m_Process->RemoveObserver(m_ProgressTag); + } + } } } // end namespace otb diff --git a/Code/Common/otbFilterWatcherBase.h b/Code/Common/otbFilterWatcherBase.h index b1ad2c406a3084225cdfc9e65e4d57669fdd99d0..a4740c60acc50f33b17291c09df5809ea8029554 100644 --- a/Code/Common/otbFilterWatcherBase.h +++ b/Code/Common/otbFilterWatcherBase.h @@ -28,91 +28,100 @@ namespace otb { - /** \class FilterWatcherBase - * \brief This class is an abstract class - * Provides an interface to progress task mechanic - * - * Implement your callbacks - * \li ShowProgress : callback called for each completed pixel - * \li StartFilter : callback called at the begin of process - * \li EndFilter : callback called at the end of process - * - */ - class /*ITK_EXPORT*/ FilterWatcherBase - { - public: +/** \class FilterWatcherBase + * \brief This class is an abstract class + * Provides an interface to progress task mechanic + * + * Implement your callbacks + * \li ShowProgress : callback called for each completed pixel + * \li StartFilter : callback called at the begin of process + * \li EndFilter : callback called at the end of process + * + */ +class /*ITK_EXPORT*/ FilterWatcherBase +{ +public: - /** Constructor. Takes a ProcessObject to monitor and an optional - * comment string that is prepended to each event message. */ - FilterWatcherBase(itk::ProcessObject* process, - const char *comment=""); + /** Constructor. Takes a ProcessObject to monitor and an optional + * comment string that is prepended to each event message. */ + FilterWatcherBase(itk::ProcessObject* process, + const char *comment=""); - /** Default constructor */ - FilterWatcherBase(); + /** Default constructor */ + FilterWatcherBase(); - /** Copy constructor */ - FilterWatcherBase(const FilterWatcherBase&); + /** Copy constructor */ + FilterWatcherBase(const FilterWatcherBase&); - /** operator= */ - void operator=(const FilterWatcherBase& ); + /** operator= */ + void operator=(const FilterWatcherBase& ); - /** Destructor. */ - virtual ~FilterWatcherBase(); + /** Destructor. */ + virtual ~FilterWatcherBase(); - /** Methods to access member data */ - /** Get a pointer to the process object being watched. */ - itk::ProcessObject *GetProcess () {return m_Process.GetPointer();} + /** Methods to access member data */ + /** Get a pointer to the process object being watched. */ + itk::ProcessObject *GetProcess () + { + return m_Process.GetPointer(); + } - /** Get the comment for the watcher. */ - std::string GetComment() {return m_Comment;} + /** Get the comment for the watcher. */ + std::string GetComment() + { + return m_Comment; + } - /** Get a reference to the TimeProbe */ - itk::TimeProbe &GetTimeProbe() {return m_TimeProbe;} + /** Get a reference to the TimeProbe */ + itk::TimeProbe &GetTimeProbe() + { + return m_TimeProbe; + } - protected: +protected: - /** Callback method to show the ProgressEvent */ - virtual void ShowProgress() = 0; + /** Callback method to show the ProgressEvent */ + virtual void ShowProgress() = 0; - /** Callback method to show the StartEvent */ - virtual void StartFilter() = 0; + /** Callback method to show the StartEvent */ + virtual void StartFilter() = 0; - /** Callback method to show the EndEvent */ - virtual void EndFilter() = 0; + /** Callback method to show the EndEvent */ + virtual void EndFilter() = 0; - /** Computing time */ - itk::TimeProbe m_TimeProbe; + /** Computing time */ + itk::TimeProbe m_TimeProbe; - /** Associated comment */ - std::string m_Comment; + /** Associated comment */ + std::string m_Comment; - /** Abstract process object */ - itk::ProcessObject::Pointer m_Process; + /** Abstract process object */ + itk::ProcessObject::Pointer m_Process; - /** Internal type */ - typedef itk::SimpleMemberCommand<FilterWatcherBase> CommandType; + /** Internal type */ + typedef itk::SimpleMemberCommand<FilterWatcherBase> CommandType; - /** Start filter callback */ - CommandType::Pointer m_StartFilterCommand; + /** Start filter callback */ + CommandType::Pointer m_StartFilterCommand; - /** End filter callback */ - CommandType::Pointer m_EndFilterCommand; + /** End filter callback */ + CommandType::Pointer m_EndFilterCommand; - /** Progress filter callback */ - CommandType::Pointer m_ProgressFilterCommand; + /** Progress filter callback */ + CommandType::Pointer m_ProgressFilterCommand; - /** Start oberserver */ - unsigned long m_StartTag; + /** Start oberserver */ + unsigned long m_StartTag; - /** End observer */ - unsigned long m_EndTag; + /** End observer */ + unsigned long m_EndTag; - /** Progress observer */ - unsigned long m_ProgressTag; + /** Progress observer */ + unsigned long m_ProgressTag; - private: +private: - }; +}; } // end namespace otb diff --git a/Code/Common/otbGenericInterpolateImageFunction.h b/Code/Common/otbGenericInterpolateImageFunction.h index 11110d8cd53d313c2c968bae2bde3ae5622d7d21..6564d90c9fcff62f60c546a75283994fd8b4d22d 100644 --- a/Code/Common/otbGenericInterpolateImageFunction.h +++ b/Code/Common/otbGenericInterpolateImageFunction.h @@ -34,117 +34,120 @@ namespace otb */ template <class TInputImage, class TFunction, class TBoundaryCondition = itk::ConstantBoundaryCondition<TInputImage>, class TCoordRep = double> class ITK_EXPORT GenericInterpolateImageFunction : -public itk::InterpolateImageFunction<TInputImage,TCoordRep> + public itk::InterpolateImageFunction<TInputImage,TCoordRep> +{ +public: + /** Standard class typedefs. */ + typedef GenericInterpolateImageFunction Self; + typedef itk::InterpolateImageFunction<TInputImage,TCoordRep> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(GenericInterpolateImageFunction, itk::InterpolateImageFunction); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Input and output images typedef definition. */ + typedef typename Superclass::OutputType OutputType; + typedef typename Superclass::InputImageType InputImageType; + + /** Dimension underlying input image. */ + //itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** Index and typedef support. */ + typedef typename Superclass::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename Superclass::RealType RealType; + typedef TFunction FunctionType; + typedef itk::ConstNeighborhoodIterator< InputImageType, TBoundaryCondition> IteratorType; + + /** ContinuousIndex typedef support. */ + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + /** Dimension underlying input image. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + virtual void SetInputImage(const InputImageType *image); + + /** Evaluate the function at a ContinuousIndex position + * + * Returns the interpolated image intensity at a + * specified point position. No bounds checking is done. + * The point is assume to lie within the image buffer. + * + * ImageFunction::IsInsideBuffer() can be used to check bounds before + * calling the method. */ + virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const; + + + /** Set/Get the window radius*/ + void SetRadius(unsigned int rad); + unsigned int GetRadius() const + { + return m_Function.GetRadius(); + }; + //unsigned int GetRadius() { return this->GetFunction().GetRadius();}; + + /** Set/Get the window radius*/ + // Don't have to be used here, just declared for the inheritance classes. + //virtual void SetWindowSize(unsigned int win){ m_WindowSize = win; }; + + /** Get the functor list */ + FunctionType& GetFunction(void) { - public: - /** Standard class typedefs. */ - typedef GenericInterpolateImageFunction Self; - typedef itk::InterpolateImageFunction<TInputImage,TCoordRep> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(GenericInterpolateImageFunction, itk::InterpolateImageFunction); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Input and output images typedef definition. */ - typedef typename Superclass::OutputType OutputType; - typedef typename Superclass::InputImageType InputImageType; - - /** Dimension underlying input image. */ - //itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - /** Index and typedef support. */ - typedef typename Superclass::IndexType IndexType; - typedef typename InputImageType::SizeType SizeType; - typedef typename Superclass::RealType RealType; - typedef TFunction FunctionType; - typedef itk::ConstNeighborhoodIterator< InputImageType, TBoundaryCondition> IteratorType; - - /** ContinuousIndex typedef support. */ - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - - /** Dimension underlying input image. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); - - virtual void SetInputImage(const InputImageType *image); - - /** Evaluate the function at a ContinuousIndex position - * - * Returns the interpolated image intensity at a - * specified point position. No bounds checking is done. - * The point is assume to lie within the image buffer. - * - * ImageFunction::IsInsideBuffer() can be used to check bounds before - * calling the method. */ - virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const; - - - /** Set/Get the window radius*/ - void SetRadius(unsigned int rad); - unsigned int GetRadius() const { return m_Function.GetRadius(); }; - //unsigned int GetRadius() { return this->GetFunction().GetRadius();}; - - /** Set/Get the window radius*/ - // Don't have to be used here, just declared for the inheritance classes. - //virtual void SetWindowSize(unsigned int win){ m_WindowSize = win; }; - - /** Get the functor list */ - FunctionType& GetFunction(void) - { - return m_Function; - } - - /** Delete tables.*/ - void ResetOffsetTable() const; - /** Initialize used tables*/ - void InitializeTables() const; - /** Fill the weight offset table*/ - void FillWeightOffsetTable() const; - - /** Weights normalization accessors*/ - itkSetMacro(NormalizeWeight, bool); - itkGetMacro(NormalizeWeight, bool); - - protected: - GenericInterpolateImageFunction(); - ~GenericInterpolateImageFunction(); - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Call the superclass implementation and set the TablesHaveBeenGenerated - * flag to false */ - virtual void Modified(void); - - private: - GenericInterpolateImageFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - /** Store the window radius. */ - //unsigned int m_Radius; - // Constant to store twice the radius - unsigned int m_WindowSize; - - /** Used function */ - FunctionType m_Function; - /** Store the image dimension.*/ - unsigned int m_ImageDimension; - - /** These members are declared mutable so that they can be + return m_Function; + } + + /** Delete tables.*/ + void ResetOffsetTable() const; + /** Initialize used tables*/ + void InitializeTables() const; + /** Fill the weight offset table*/ + void FillWeightOffsetTable() const; + + /** Weights normalization accessors*/ + itkSetMacro(NormalizeWeight, bool); + itkGetMacro(NormalizeWeight, bool); + +protected: + GenericInterpolateImageFunction(); + ~GenericInterpolateImageFunction(); + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** Call the superclass implementation and set the TablesHaveBeenGenerated + * flag to false */ + virtual void Modified(void); + +private: + GenericInterpolateImageFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + /** Store the window radius. */ + //unsigned int m_Radius; + // Constant to store twice the radius + unsigned int m_WindowSize; + + /** Used function */ + FunctionType m_Function; + /** Store the image dimension.*/ + unsigned int m_ImageDimension; + + /** These members are declared mutable so that they can be regenerated seamlessly inside the EvaluateAtContinuousIndex method if they need to */ - /** Size of the offset table */ - mutable unsigned int m_OffsetTableSize; - /** The offset array, used to keep a list of relevant - * offsets in the neihborhoodIterator */ - mutable unsigned int *m_OffsetTable; - /** Index into the weights array for each offset */ - mutable unsigned int **m_WeightOffsetTable; - /** True if internal statistics have been generated */ - mutable bool m_TablesHaveBeenGenerated; - /** Weights normalization */ - bool m_NormalizeWeight; - }; + /** Size of the offset table */ + mutable unsigned int m_OffsetTableSize; + /** The offset array, used to keep a list of relevant + * offsets in the neihborhoodIterator */ + mutable unsigned int *m_OffsetTable; + /** Index into the weights array for each offset */ + mutable unsigned int **m_WeightOffsetTable; + /** True if internal statistics have been generated */ + mutable bool m_TablesHaveBeenGenerated; + /** Weights normalization */ + bool m_NormalizeWeight; +}; } // end namespace itk diff --git a/Code/Common/otbGenericInterpolateImageFunction.txx b/Code/Common/otbGenericInterpolateImageFunction.txx index 9ed1832a0d2e43530b9d1ecee00bfec90b7baba1..71cbcf75815358c20b78e6316eed11a0de4fa0d7 100644 --- a/Code/Common/otbGenericInterpolateImageFunction.txx +++ b/Code/Common/otbGenericInterpolateImageFunction.txx @@ -51,22 +51,22 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo ::ResetOffsetTable() const { // Clear the offset table - if(m_OffsetTable!=NULL) - { - delete [] m_OffsetTable; - m_OffsetTable=NULL; - } + if (m_OffsetTable!=NULL) + { + delete [] m_OffsetTable; + m_OffsetTable=NULL; + } // Clear the weights tales - if(m_WeightOffsetTable!=NULL) - { - for(unsigned int i=0; i < m_OffsetTableSize; i++) + if (m_WeightOffsetTable!=NULL) { - delete [] m_WeightOffsetTable[i]; - } - delete[] m_WeightOffsetTable; - m_WeightOffsetTable = NULL; + for (unsigned int i=0; i < m_OffsetTableSize; i++) + { + delete [] m_WeightOffsetTable[i]; } + delete[] m_WeightOffsetTable; + m_WeightOffsetTable = NULL; + } } @@ -78,10 +78,10 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo { // Call the parent implementation Superclass::SetInputImage(image); - if( image == NULL ) - { - return; - } + if ( image == NULL ) + { + return; + } } template<class TInputImage, class TFunction, class TBoundaryCondition, class TCoordRep> @@ -113,20 +113,20 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo { // Compute the offset table size m_OffsetTableSize = 1; - for(unsigned dim=0;dim<ImageDimension;dim++) - { - m_OffsetTableSize *= m_WindowSize; - } + for (unsigned dim=0;dim<ImageDimension;dim++) + { + m_OffsetTableSize *= m_WindowSize; + } // Allocate the offset table m_OffsetTable = new unsigned int[m_OffsetTableSize]; // Allocate the weights tables m_WeightOffsetTable = new unsigned int *[m_OffsetTableSize]; - for(unsigned int i=0;i<m_OffsetTableSize;i++) - { - m_WeightOffsetTable[i] = new unsigned int[ImageDimension]; - } + for (unsigned int i=0;i<m_OffsetTableSize;i++) + { + m_WeightOffsetTable[i] = new unsigned int[ImageDimension]; + } } /** Fill the weight offset table*/ @@ -139,48 +139,48 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo SizeType radius; radius.Fill(this->GetRadius()); if (this->GetInputImage() != NULL) - { - IteratorType it = IteratorType(radius, this->GetInputImage(), this->GetInputImage()->GetBufferedRegion()); - // Compute the offset tables (we ignore all the zero indices - // in the neighborhood) - unsigned int iOffset = 0; - int empty = static_cast<int>(this->GetRadius()); - - for(unsigned int iPos = 0; iPos < it.Size(); iPos++) { - // Get the offset (index) - typename IteratorType::OffsetType off = it.GetOffset(iPos); + IteratorType it = IteratorType(radius, this->GetInputImage(), this->GetInputImage()->GetBufferedRegion()); + // Compute the offset tables (we ignore all the zero indices + // in the neighborhood) + unsigned int iOffset = 0; + int empty = static_cast<int>(this->GetRadius()); - // Check if the offset has zero weights - bool nonzero = true; - for(unsigned int dim = 0; dim < ImageDimension; dim++) + for (unsigned int iPos = 0; iPos < it.Size(); iPos++) { - if(off[dim] == -empty) + // Get the offset (index) + typename IteratorType::OffsetType off = it.GetOffset(iPos); + + // Check if the offset has zero weights + bool nonzero = true; + for (unsigned int dim = 0; dim < ImageDimension; dim++) + { + if (off[dim] == -empty) { - nonzero = false; - break; + nonzero = false; + break; } - } - // Only use offsets with non-zero indices - if(nonzero) - { - // Set the offset index - m_OffsetTable[iOffset] = iPos; + } + // Only use offsets with non-zero indices + if (nonzero) + { + // Set the offset index + m_OffsetTable[iOffset] = iPos; - // Set the weight table indices - for(unsigned int dim = 0; dim < ImageDimension; dim++) + // Set the weight table indices + for (unsigned int dim = 0; dim < ImageDimension; dim++) { - m_WeightOffsetTable[iOffset][dim] = off[dim] + this->GetRadius() - 1; + m_WeightOffsetTable[iOffset][dim] = off[dim] + this->GetRadius() - 1; } - // Increment the index - iOffset++; + // Increment the index + iOffset++; + } } } - } else - { - itkExceptionMacro(<< "An input has to be set"); - } + { + itkExceptionMacro(<< "An input has to be set"); + } } /** Evaluate at image index position */ @@ -189,16 +189,16 @@ typename GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondit GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoordRep> ::EvaluateAtContinuousIndex(const ContinuousIndexType& index) const { - if(!m_TablesHaveBeenGenerated) - { - // Delete existing tables - this->ResetOffsetTable(); - // Tables initialization - this->InitializeTables(); - // fill the weigth table - this->FillWeightOffsetTable(); - m_TablesHaveBeenGenerated = true; - } + if (!m_TablesHaveBeenGenerated) + { + // Delete existing tables + this->ResetOffsetTable(); + // Tables initialization + this->InitializeTables(); + // fill the weigth table + this->FillWeightOffsetTable(); + m_TablesHaveBeenGenerated = true; + } //unsigned int dim; IndexType baseIndex; @@ -206,26 +206,26 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo // Compute the integer index based on the continuous one by // 'flooring' the index - for( unsigned int 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 + for ( unsigned int dim = 0; dim < ImageDimension; dim++ ) { - long tIndex = (long) index[dim]; - if (double(tIndex) != index[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 + { + long tIndex = (long) index[dim]; + if (double(tIndex) != index[dim]) { tIndex--; } - baseIndex[dim] = tIndex; - } - distance[dim] = index[dim] - double( baseIndex[dim] ); + baseIndex[dim] = tIndex; } + distance[dim] = index[dim] - double( baseIndex[dim] ); + } // Position the neighborhood at the index of interest @@ -235,72 +235,72 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo nit.SetLocation( baseIndex ); const unsigned int twiceRadius = static_cast<const unsigned int>(2*this->GetRadius()); -/* double xWeight[ImageDimension][ twiceRadius];*/ + /* double xWeight[ImageDimension][ twiceRadius];*/ std::vector< std::vector<double> > xWeight; xWeight.resize(ImageDimension); - for(unsigned int cpt=0; cpt < xWeight.size(); cpt++) - { - xWeight[cpt].resize(twiceRadius); - } + for (unsigned int cpt=0; cpt < xWeight.size(); cpt++) + { + xWeight[cpt].resize(twiceRadius); + } - for( unsigned int dim = 0; dim < ImageDimension; dim++ ) - { + for ( unsigned int dim = 0; dim < ImageDimension; dim++ ) + { // x is the offset, hence the parameter of the kernel - double x = distance[dim] + this->GetRadius(); + double x = distance[dim] + this->GetRadius(); // If distance is zero, i.e. the index falls precisely on the // pixel boundary, the weights form a delta function. - /* + /* if(distance[dim] == 0.0) + { + for( unsigned int i = 0; i < m_WindowSize; i++) { - for( unsigned int i = 0; i < m_WindowSize; i++) - { xWeight[dim][i] = static_cast<int>(i) == (static_cast<int>(this->GetRadius()) - 1) ? 1. : 0.; - } } + } else - { - */ - // i is the relative offset in dimension dim. - for( unsigned int i = 0; i < m_WindowSize; i++) - { - // Increment the offset, taking it through the range - // (dist + rad - 1, ..., dist - rad), i.e. all x - // such that vcl_abs(x) <= rad - x -= 1.0; - // Compute the weight for this m - xWeight[dim][i] = m_Function(x); - } - //} + { + */ + // i is the relative offset in dimension dim. + for ( unsigned int i = 0; i < m_WindowSize; i++) + { + // Increment the offset, taking it through the range + // (dist + rad - 1, ..., dist - rad), i.e. all x + // such that vcl_abs(x) <= rad + x -= 1.0; + // Compute the weight for this m + xWeight[dim][i] = m_Function(x); } + //} + } if (m_NormalizeWeight == true) - { - for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { - double sum = 0.; - // Compute the weights sum - for( unsigned int i = 0; i < m_WindowSize; i++) + for ( unsigned int dim = 0; dim < ImageDimension; dim++ ) + { + double sum = 0.; + // Compute the weights sum + for ( unsigned int i = 0; i < m_WindowSize; i++) { sum += xWeight[dim][i]; } - if (sum != 1.) + if (sum != 1.) { // Normalize the weights - for( unsigned int i = 0; i < m_WindowSize; i++) - { - xWeight[dim][i] = xWeight[dim][i]/sum; - } + for ( unsigned int i = 0; i < m_WindowSize; i++) + { + xWeight[dim][i] = xWeight[dim][i]/sum; + } } - } } + } // Iterate over the neighborhood, taking the correct set // of weights in each dimension double xPixelValue = 0.0; - for(unsigned int j = 0; j < m_OffsetTableSize; j++) - { + for (unsigned int j = 0; j < m_OffsetTableSize; j++) + { // Get the offset for this neighbor unsigned int off = m_OffsetTable[j]; @@ -309,14 +309,14 @@ GenericInterpolateImageFunction<TInputImage, TFunction, TBoundaryCondition, TCoo // Multiply the intensity by each of the weights. Gotta hope // that the compiler will unwrap this loop and pipeline this! - for(unsigned int dim = 0; dim < ImageDimension; dim++) - { + for (unsigned int dim = 0; dim < ImageDimension; dim++) + { xVal *= xWeight[ dim ][ m_WeightOffsetTable[j][dim] ]; - } + } // Increment the pixel value xPixelValue += xVal; - } + } // Return the interpolated value return static_cast<OutputType>(xPixelValue); diff --git a/Code/Common/otbHistogramStatisticsFunction.h b/Code/Common/otbHistogramStatisticsFunction.h index 25246244ccfd8f1efc5e6fbccdc128351988b065..3cff62570fb524fef92a64c220712f47facd5cec 100644 --- a/Code/Common/otbHistogramStatisticsFunction.h +++ b/Code/Common/otbHistogramStatisticsFunction.h @@ -69,12 +69,12 @@ public: /** Stores the histogram pointer */ void SetInputHistogram( const TInputHistogram * histogram ) { - if ( m_InputHistogram != histogram ) - { - m_InputHistogram = histogram; - this->Modified(); - m_IsModified = true; - } + if ( m_InputHistogram != histogram ) + { + m_InputHistogram = histogram; + this->Modified(); + m_IsModified = true; + } } protected: diff --git a/Code/Common/otbHistogramStatisticsFunction.txx b/Code/Common/otbHistogramStatisticsFunction.txx index 279cb59af4b9e5f9c26a2600dd5a4677a86d334b..7f3929826f7f582cf3f2827b1928a35749ea2b43 100644 --- a/Code/Common/otbHistogramStatisticsFunction.txx +++ b/Code/Common/otbHistogramStatisticsFunction.txx @@ -36,7 +36,7 @@ typename HistogramStatisticsFunction< TInputHistogram, TOutput>::OutputType HistogramStatisticsFunction< TInputHistogram, TOutput> ::GetEntropy() { - if(m_IsModified == true) + if (m_IsModified == true) { this->Update(); } @@ -48,7 +48,7 @@ typename HistogramStatisticsFunction< TInputHistogram, TOutput>::OutputType HistogramStatisticsFunction< TInputHistogram, TOutput> ::GetMean() { - if(m_IsModified == true) + if (m_IsModified == true) { this->Update(); } @@ -60,7 +60,7 @@ typename HistogramStatisticsFunction< TInputHistogram, TOutput>::OutputType HistogramStatisticsFunction< TInputHistogram, TOutput> ::GetCovariance() { - if(m_IsModified == true) + if (m_IsModified == true) { this->Update(); } @@ -80,20 +80,20 @@ HistogramStatisticsFunction< TInputHistogram, TOutput> RealType entropy = itk::NumericTraits<RealType>::Zero; FrequencyType globalFrequency = histogram->GetTotalFrequency(); - if(globalFrequency == 0) - { + if (globalFrequency == 0) + { itkExceptionMacro(<<"Histogram must contain at least 1 element."); - } + } while (iter != end) - { + { RealType Proba = static_cast<RealType>(iter.GetFrequency()); Proba /= static_cast<RealType>(globalFrequency); - if(Proba !=0.0) - { + if (Proba !=0.0) + { entropy -= Proba * vcl_log(Proba); - } - ++iter; } + ++iter; + } m_entropy.resize(1); m_entropy[0] = static_cast<TOutput>(entropy); } @@ -110,28 +110,28 @@ HistogramStatisticsFunction< TInputHistogram, TOutput> unsigned int NumberOfDimension = histogram->GetSize().GetSizeDimension(); m_mean.resize(NumberOfDimension); - if(histogram->GetTotalFrequency() == 0) - { + if (histogram->GetTotalFrequency() == 0) + { itkExceptionMacro(<<"Histogram must contain at least 1 element."); - } + } - if(NumberOfDimension > 2) - { + if (NumberOfDimension > 2) + { itkExceptionMacro(<<"Histogram must have 1 or 2 dimension."); - } + } - for( unsigned int noDim = 0; noDim < NumberOfDimension; noDim++ ) - { + for ( unsigned int noDim = 0; noDim < NumberOfDimension; noDim++ ) + { MeasurementType mean = itk::NumericTraits<MeasurementType>::Zero; for (unsigned int i = 0; i < histogram->GetSize()[noDim]; i++) - { + { MeasurementType val = histogram->GetMeasurement(i, noDim); FrequencyType freq = histogram->GetFrequency(i, noDim); mean += val*freq; - } + } mean /= histogram->GetTotalFrequency(); m_mean[noDim] = static_cast<TOutput>(mean); - } + } } template< class TInputHistogram, class TOutput > @@ -146,29 +146,29 @@ HistogramStatisticsFunction< TInputHistogram, TOutput> unsigned int NumberOfDimension = histogram->GetSize().GetSizeDimension(); m_covariance.resize(NumberOfDimension*NumberOfDimension); - if(histogram->GetTotalFrequency() == 0) - { + if (histogram->GetTotalFrequency() == 0) + { itkExceptionMacro(<<"Histogram must contain at least 1 element."); - } + } - for( unsigned int noDimX = 0; noDimX < NumberOfDimension; noDimX++ ) - for( unsigned int noDimY = 0; noDimY < NumberOfDimension; noDimY++ ) + for ( unsigned int noDimX = 0; noDimX < NumberOfDimension; noDimX++ ) + for ( unsigned int noDimY = 0; noDimY < NumberOfDimension; noDimY++ ) { - MeasurementType covariance = itk::NumericTraits<MeasurementType>::Zero; - for (unsigned int i = 0; i < histogram->GetSize()[noDimX]; i++) - for (unsigned int j = 0; j < histogram->GetSize()[noDimY]; j++) - { - MeasurementType valX = histogram->GetMeasurement(i, noDimX); - MeasurementType valY = histogram->GetMeasurement(j, noDimY); - FrequencyType freqX = histogram->GetFrequency(i, noDimX); - FrequencyType freqY = histogram->GetFrequency(j, noDimY); - - valX -= static_cast<MeasurementType>(m_mean[noDimX]); - valY -= static_cast<MeasurementType>(m_mean[noDimY]); - covariance += ( (valX*freqX)*(valY*freqY) ); - } - covariance /= histogram->GetTotalFrequency(); - m_covariance[noDimX*NumberOfDimension+noDimY] = static_cast<TOutput>(covariance); + MeasurementType covariance = itk::NumericTraits<MeasurementType>::Zero; + for (unsigned int i = 0; i < histogram->GetSize()[noDimX]; i++) + for (unsigned int j = 0; j < histogram->GetSize()[noDimY]; j++) + { + MeasurementType valX = histogram->GetMeasurement(i, noDimX); + MeasurementType valY = histogram->GetMeasurement(j, noDimY); + FrequencyType freqX = histogram->GetFrequency(i, noDimX); + FrequencyType freqY = histogram->GetFrequency(j, noDimY); + + valX -= static_cast<MeasurementType>(m_mean[noDimX]); + valY -= static_cast<MeasurementType>(m_mean[noDimY]); + covariance += ( (valX*freqX)*(valY*freqY) ); + } + covariance /= histogram->GetTotalFrequency(); + m_covariance[noDimX*NumberOfDimension+noDimY] = static_cast<TOutput>(covariance); } } @@ -179,7 +179,7 @@ HistogramStatisticsFunction< TInputHistogram, TOutput> ::GenerateData() { - CalculateEntropy(); + CalculateEntropy(); CalculateMean(); CalculateCovariance(); m_IsModified = false; diff --git a/Code/Common/otbImageList.h b/Code/Common/otbImageList.h index c80566bf05348f8bfb26989f305595a0a4cc5828..86044ee2adb58bf9229c539552e558d5ade2c676 100644 --- a/Code/Common/otbImageList.h +++ b/Code/Common/otbImageList.h @@ -32,52 +32,52 @@ namespace otb template <class TImage> class ITK_EXPORT ImageList - : public ObjectList<TImage> + : public ObjectList<TImage> +{ +public: + /** Standard typedefs */ + typedef ImageList Self; + typedef ObjectList<TImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkTypeMacro(ImageList,ObjectList); + + /** Creation through object factory macro */ + itkNewMacro(Self); + + /** Template parameter typedefs */ + typedef TImage ImageType; + typedef typename Superclass::ObjectPointerType ImagePointerType; + typedef typename Superclass::Iterator Iterator; + typedef typename Superclass::ConstIterator ConstIterator; + typedef typename Superclass::ReverseIterator ReverseIterator; + typedef typename Superclass::ReverseConstIterator ReverseConstIterator; + + /** + * Update images in the list. + */ + virtual void UpdateOutputInformation(void); + virtual void PropagateRequestedRegion(void) throw (itk::InvalidRequestedRegionError); + virtual void UpdateOutputData(void); + + +protected: + /** Constructor */ + ImageList() {}; + /** Destructor */ + ~ImageList() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const { - public: - /** Standard typedefs */ - typedef ImageList Self; - typedef ObjectList<TImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkTypeMacro(ImageList,ObjectList); - - /** Creation through object factory macro */ - itkNewMacro(Self); - - /** Template parameter typedefs */ - typedef TImage ImageType; - typedef typename Superclass::ObjectPointerType ImagePointerType; - typedef typename Superclass::Iterator Iterator; - typedef typename Superclass::ConstIterator ConstIterator; - typedef typename Superclass::ReverseIterator ReverseIterator; - typedef typename Superclass::ReverseConstIterator ReverseConstIterator; - - /** - * Update images in the list. - */ - virtual void UpdateOutputInformation(void); - virtual void PropagateRequestedRegion(void) throw (itk::InvalidRequestedRegionError); - virtual void UpdateOutputData(void); - - - protected: - /** Constructor */ - ImageList(){}; - /** Destructor */ - ~ImageList(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; - - private: - ImageList(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + Superclass::PrintSelf(os,indent); }; + +private: + ImageList(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // End namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/Common/otbImageList.txx b/Code/Common/otbImageList.txx index 3f35a2428e22ce84bcd4cc766e93acb4b32239c4..4ba2c849970181cb41c8c2e35e3e3a4ba27da178 100644 --- a/Code/Common/otbImageList.txx +++ b/Code/Common/otbImageList.txx @@ -29,18 +29,18 @@ ImageList<TImage> ::UpdateOutputData() { Superclass::UpdateOutputData(); - for(ConstIterator it = this->Begin(); it!=this->End();++it) - { - if(it.Get()->GetUpdateMTime() < it.Get()->GetPipelineMTime() - || it.Get()->GetDataReleased() - || it.Get()->RequestedRegionIsOutsideOfTheBufferedRegion()) + for (ConstIterator it = this->Begin(); it!=this->End();++it) { - if(it.Get()->GetSource()) + if (it.Get()->GetUpdateMTime() < it.Get()->GetPipelineMTime() + || it.Get()->GetDataReleased() + || it.Get()->RequestedRegionIsOutsideOfTheBufferedRegion()) + { + if (it.Get()->GetSource()) { it.Get()->GetSource()->UpdateOutputData(it.Get()); } - } } + } } template <class TImage> @@ -49,30 +49,30 @@ ImageList<TImage> ::PropagateRequestedRegion() throw (itk::InvalidRequestedRegionError) { Superclass::PropagateRequestedRegion(); - for(ConstIterator it = this->Begin(); it!=this->End();++it) - { - if(it.Get()->GetUpdateMTime() < it.Get()->GetPipelineMTime() - || it.Get()->GetDataReleased() - || it.Get()->RequestedRegionIsOutsideOfTheBufferedRegion()) + for (ConstIterator it = this->Begin(); it!=this->End();++it) { - if(it.Get()->GetSource()) + if (it.Get()->GetUpdateMTime() < it.Get()->GetPipelineMTime() + || it.Get()->GetDataReleased() + || it.Get()->RequestedRegionIsOutsideOfTheBufferedRegion()) + { + if (it.Get()->GetSource()) { it.Get()->GetSource()->PropagateRequestedRegion(it.Get()); } - } + } - // Check that the requested region lies within the largest possible region - if ( ! it.Get()->VerifyRequestedRegion() ) + // Check that the requested region lies within the largest possible region + if ( ! it.Get()->VerifyRequestedRegion() ) { - // invalid requested region, throw an exception - itk::InvalidRequestedRegionError e(__FILE__, __LINE__); - e.SetLocation(ITK_LOCATION); - e.SetDataObject(it.Get()); - e.SetDescription("Requested region is (at least partially) outside the largest possible region."); + // invalid requested region, throw an exception + itk::InvalidRequestedRegionError e(__FILE__, __LINE__); + e.SetLocation(ITK_LOCATION); + e.SetDataObject(it.Get()); + e.SetDescription("Requested region is (at least partially) outside the largest possible region."); - throw e; - } + throw e; } + } } template <class TImage> @@ -83,17 +83,17 @@ ImageList<TImage> // otbMsgDebugMacro(<<"ImageList: Call to UpdateOutputInformation()"); Superclass::UpdateOutputInformation(); - if(this->GetSource()) - { - this->GetSource()->UpdateOutputInformation(); - } - for(ConstIterator it = this->Begin(); it!=this->End();++it) - { - if(it.Get()->GetSource()) + if (this->GetSource()) { - it.Get()->GetSource()->UpdateOutputInformation(); + this->GetSource()->UpdateOutputInformation(); } + for (ConstIterator it = this->Begin(); it!=this->End();++it) + { + if (it.Get()->GetSource()) + { + it.Get()->GetSource()->UpdateOutputInformation(); } + } } diff --git a/Code/Common/otbImageListSource.h b/Code/Common/otbImageListSource.h index 2a855079f91fb2ac6ed9b7edd7e8b0639ae44645..90622436ec752de84d28d135b36db321433c78b3 100644 --- a/Code/Common/otbImageListSource.h +++ b/Code/Common/otbImageListSource.h @@ -33,7 +33,7 @@ namespace otb */ template <class TOutputImage> class ITK_EXPORT ImageListSource - : public itk::ProcessObject + : public itk::ProcessObject { public: /** Standard typedefs */ diff --git a/Code/Common/otbImageListSource.txx b/Code/Common/otbImageListSource.txx index 3f6d501a73c943dc9fe34db4e335c962f73b0c41..d8938b8b0e6f941f815d8e2106ffec3bfc69d32b 100644 --- a/Code/Common/otbImageListSource.txx +++ b/Code/Common/otbImageListSource.txx @@ -41,10 +41,10 @@ typename ImageListSource<TOutputImage>::OutputImageListType * ImageListSource<TOutputImage> ::GetOutput(void) { - if(this->GetNumberOfOutputs()<1) - { + if (this->GetNumberOfOutputs()<1) + { return 0; - } + } return static_cast<OutputImageListType *> (this->ProcessObject::GetOutput(0)); } /** diff --git a/Code/Common/otbImageListToImageFilter.h b/Code/Common/otbImageListToImageFilter.h index 2e242e009dbf8321c53ac70e72d7f2d90cb07b20..0b8156f9279a83c5186e69208d1404f7c1e723b5 100644 --- a/Code/Common/otbImageListToImageFilter.h +++ b/Code/Common/otbImageListToImageFilter.h @@ -33,7 +33,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageListToImageFilter - : public itk::ImageSource<TOutputImage> + : public itk::ImageSource<TOutputImage> { public: /** Standard typedefs */ @@ -70,7 +70,7 @@ protected: ImageListToImageFilter(); /** Destructor */ virtual ~ImageListToImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/Common/otbImageListToImageFilter.txx b/Code/Common/otbImageListToImageFilter.txx index 5c1215c0d099297636ab9bc1efd9440ab2eee2af..30d6eb0be528a71ae8effbb4d81b3378a2c934aa 100644 --- a/Code/Common/otbImageListToImageFilter.txx +++ b/Code/Common/otbImageListToImageFilter.txx @@ -54,13 +54,13 @@ ImageListToImageFilter<TInputImage,TOutputImage> { // If there is no input if (this->GetNumberOfInputs()<1) - { + { // exit return 0; - } + } // else return the first input return static_cast<InputImageListType * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** * PrintSelf Method diff --git a/Code/Common/otbImageListToImageListFilter.h b/Code/Common/otbImageListToImageListFilter.h index e0af5927cad2e75616942626d41b4bd6953a91cc..8176ccf2e22e27fb523e71a4967f861b1bf1f236 100644 --- a/Code/Common/otbImageListToImageListFilter.h +++ b/Code/Common/otbImageListToImageListFilter.h @@ -30,7 +30,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageListToImageListFilter - : public ImageListSource<TOutputImage> + : public ImageListSource<TOutputImage> { public: /** Standard typedefs */ @@ -68,7 +68,7 @@ protected: ImageListToImageListFilter(); /** Destructor */ virtual ~ImageListToImageListFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/Common/otbImageListToImageListFilter.txx b/Code/Common/otbImageListToImageListFilter.txx index 9410d2a395f1613b3efc676a2299f1ccdf1462ee..cf852b5186b94f2230036ebd4d0408a789c052a3 100644 --- a/Code/Common/otbImageListToImageListFilter.txx +++ b/Code/Common/otbImageListToImageListFilter.txx @@ -54,13 +54,13 @@ ImageListToImageListFilter<TInputImage,TOutputImage> { // If there is no input if (this->GetNumberOfInputs()<1) - { + { // exit return 0; - } + } // else return the first input return static_cast<InputImageListType * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** * PrintSelf Method diff --git a/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.h b/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.h index 6fe5cfdedf06b351cb6d92c92b2263bf4d051e1b..0a70115ecee5c324e2e04c86cb3542c4944eb289 100644 --- a/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.h +++ b/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.h @@ -33,7 +33,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageOfVectorsToMonoChannelExtractROI: - public ExtractROIBase< TInputImage , TOutputImage > + public ExtractROIBase< TInputImage , TOutputImage > { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.txx b/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.txx index ea2e3f2b5abdbd90933824a9b05498363df3c875..5469388037100f38cecf8c560f3650ae6e8dd6f2 100644 --- a/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.txx +++ b/Code/Common/otbImageOfVectorsToMonoChannelExtractROI.txx @@ -59,17 +59,17 @@ void ImageOfVectorsToMonoChannelExtractROI<TInputImage,TOutputImage> ::GenerateOutputInformation() { - typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); - // Analyse du canal traité - if ( (m_Channel <= 0) || (m_Channel > InputImagePixelType::Dimension ) ) - { - itkExceptionMacro(<< "otb::ExtractImImageOfVectorsToMonoChannelExtractROIageFilter::GenerateOutputInformation " + typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); + // Analyse du canal traité + if ( (m_Channel <= 0) || (m_Channel > InputImagePixelType::Dimension ) ) + { + itkExceptionMacro(<< "otb::ExtractImImageOfVectorsToMonoChannelExtractROIageFilter::GenerateOutputInformation " << " Channel must be in the following range: [1;"<< InputImagePixelType::Dimension <<"] " << typeid(itk::ImageBase<InputImageDimension>*).name() ); - } + } - // Appel à la methode de la classe de base - Superclass::GenerateOutputInformation(); + // Appel à la methode de la classe de base + Superclass::GenerateOutputInformation(); } @@ -103,15 +103,15 @@ ImageOfVectorsToMonoChannelExtractROI<TInputImage,TOutputImage> unsigned int channelIn(m_Channel-1); InputImagePixelType pixelInput; - while( !outIt.IsAtEnd() ) + while ( !outIt.IsAtEnd() ) { - OutputImagePixelType pixelOutput; - pixelInput = inIt.Get(); - pixelOutput = static_cast<OutputValueType>(pixelInput[channelIn]); - outIt.Set( pixelOutput ); - ++outIt; - ++inIt; - progress.CompletedPixel(); + OutputImagePixelType pixelOutput; + pixelInput = inIt.Get(); + pixelOutput = static_cast<OutputValueType>(pixelInput[channelIn]); + outIt.Set( pixelOutput ); + ++outIt; + ++inIt; + progress.CompletedPixel(); } } diff --git a/Code/Common/otbImageRegionNonUniformMultidimensionalSplitter.txx b/Code/Common/otbImageRegionNonUniformMultidimensionalSplitter.txx index 5af5ef49ebebcaada1495336fc2f51221050e3b1..4eb724d8a2efd3688c2db621f835e617b4f17d74 100644 --- a/Code/Common/otbImageRegionNonUniformMultidimensionalSplitter.txx +++ b/Code/Common/otbImageRegionNonUniformMultidimensionalSplitter.txx @@ -55,7 +55,7 @@ ImageRegionNonUniformMultidimensionalSplitter<VImageDimension> splitsPerDimension[j-1]=numberOfPiecesLeft; } numberOfPiecesLeft = (unsigned int) - ::ceil(numberOfPiecesLeft/splitsPerDimension[j-1]); + ::ceil(numberOfPiecesLeft/splitsPerDimension[j-1]); numPieces *= (unsigned int) splitsPerDimension[j-1]; } @@ -117,7 +117,7 @@ ImageRegionNonUniformMultidimensionalSplitter<VImageDimension> splitsPerDimension[j-1]=numberOfPiecesLeft; } numberOfPiecesLeft = (unsigned int) - ::ceil(numberOfPiecesLeft/splitsPerDimension[j-1]); + ::ceil(numberOfPiecesLeft/splitsPerDimension[j-1]); } // if a given dimension has fewer pixels that splitsPerDimension, then @@ -128,46 +128,46 @@ ImageRegionNonUniformMultidimensionalSplitter<VImageDimension> unsigned int offsetTable[VImageDimension]; numPieces = 1; for (j=0; j < VImageDimension; ++j) - { + { offsetTable[j] = numPieces; if (regionSize[j] < splitsPerDimension[j]) - { + { splits[j] = regionSize[j]; pixelsPerSplit[j] = 1; numPieces *= regionSize[j]; - } + } else - { + { splits[j] = (unsigned int) splitsPerDimension[j]; pixelsPerSplit[j] = (unsigned int) ::ceil(regionSize[j] - / (double) splits[j]); + / (double) splits[j]); numPieces *= (unsigned int) splitsPerDimension[j]; - } } + } // determine which split we are in unsigned int offset = i; for (j=VImageDimension-1; j > 0; j--) - { + { ijk[j] = offset / offsetTable[j]; offset -= (ijk[j] * offsetTable[j]); - } + } ijk[0] = offset; // compute the split for (j=0; j < VImageDimension; j++) - { + { splitIndex[j] += ijk[j]*pixelsPerSplit[j]; if (ijk[j] < splits[j] - 1) - { + { splitSize[j] = pixelsPerSplit[j]; - } + } else - { + { // this dimension is falling off the edge of the image splitSize[j] = splitSize[j] - ijk[j]*pixelsPerSplit[j]; - } } + } // set the split region ivars splitRegion.SetIndex( splitIndex ); diff --git a/Code/Common/otbImageRegionTileMapSplitter.h b/Code/Common/otbImageRegionTileMapSplitter.h index ea3abd58953341452e25fe0f80c5dbcdffa2865b..dfc52281390484e73bd5fa025f2344b9d6a0c5ca 100644 --- a/Code/Common/otbImageRegionTileMapSplitter.h +++ b/Code/Common/otbImageRegionTileMapSplitter.h @@ -67,39 +67,41 @@ namespace otb * \ingroup DataProcessing */ - template <unsigned int VImageDimension> - class ITK_EXPORT ImageRegionTileMapSplitter: public itk::ImageRegionSplitter<VImageDimension> - { - public: - /** Standard class typedefs. */ - typedef ImageRegionTileMapSplitter Self; - typedef itk::ImageRegionSplitter<VImageDimension> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +template <unsigned int VImageDimension> +class ITK_EXPORT ImageRegionTileMapSplitter: public itk::ImageRegionSplitter<VImageDimension> +{ +public: + /** Standard class typedefs. */ + typedef ImageRegionTileMapSplitter Self; + typedef itk::ImageRegionSplitter<VImageDimension> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(ImageRegionTileMapSplitter,itk::Object); + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageRegionTileMapSplitter,itk::Object); - /** Dimension of the image available at compile time. */ - itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); + /** Dimension of the image available at compile time. */ + itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); - /** Dimension of the image available at run time. */ - static unsigned int GetImageDimension() - { return VImageDimension; } + /** Dimension of the image available at run time. */ + static unsigned int GetImageDimension() + { + return VImageDimension; + } - /** Index typedef support. An index is used to access pixel values. */ - typedef itk::Index<VImageDimension> IndexType; - typedef typename IndexType::IndexValueType IndexValueType; + /** Index typedef support. An index is used to access pixel values. */ + typedef itk::Index<VImageDimension> IndexType; + typedef typename IndexType::IndexValueType IndexValueType; - /** Size typedef support. A size is used to define region bounds. */ - typedef itk::Size<VImageDimension> SizeType; - typedef typename SizeType::SizeValueType SizeValueType; + /** Size typedef support. A size is used to define region bounds. */ + typedef itk::Size<VImageDimension> SizeType; + typedef typename SizeType::SizeValueType SizeValueType; - /** Region typedef support. */ - typedef itk::ImageRegion<VImageDimension> RegionType; + /** Region typedef support. */ + typedef itk::ImageRegion<VImageDimension> RegionType; /** How many pieces can the specifed region be split? A given region * cannot always be divided into the requested number of pieces. For @@ -107,25 +109,25 @@ namespace otb * a certain dimensions, then some splits will not be possible. This * method returns a number less than or equal to the requested number * of pieces. */ - virtual unsigned int GetNumberOfSplits(const RegionType ®ion, - unsigned int requestedNumber); + virtual unsigned int GetNumberOfSplits(const RegionType ®ion, + 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 * GetNumberOfSplits() returns. */ - virtual RegionType GetSplit(unsigned int i, unsigned int numberOfPieces, - const RegionType ®ion); + virtual RegionType GetSplit(unsigned int i, unsigned int numberOfPieces, + const RegionType ®ion); - protected: - ImageRegionTileMapSplitter() {} - ~ImageRegionTileMapSplitter() {} - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + ImageRegionTileMapSplitter() {} + ~ImageRegionTileMapSplitter() {} + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: - ImageRegionTileMapSplitter(const ImageRegionTileMapSplitter&); //purposely not implemented - void operator=(const ImageRegionTileMapSplitter&); //purposely not implemented +private: + ImageRegionTileMapSplitter(const ImageRegionTileMapSplitter&); //purposely not implemented + void operator=(const ImageRegionTileMapSplitter&); //purposely not implemented - }; +}; } // end namespace itk diff --git a/Code/Common/otbImageRegionTileMapSplitter.txx b/Code/Common/otbImageRegionTileMapSplitter.txx index f37f287ea45cbbba3e11265aeedd27ef5e4fece1..1fa85027437b941a7117afcee9a4feacf8cb9c50 100644 --- a/Code/Common/otbImageRegionTileMapSplitter.txx +++ b/Code/Common/otbImageRegionTileMapSplitter.txx @@ -27,116 +27,116 @@ namespace otb /** * */ - template <unsigned int VImageDimension> - unsigned int - ImageRegionTileMapSplitter<VImageDimension> - ::GetNumberOfSplits(const RegionType ®ion, unsigned int requestedNumber) - { - int splitAxis; - const SizeType ®ionSize = region.GetSize(); +template <unsigned int VImageDimension> +unsigned int +ImageRegionTileMapSplitter<VImageDimension> +::GetNumberOfSplits(const RegionType ®ion, unsigned int requestedNumber) +{ + int splitAxis; + const SizeType ®ionSize = region.GetSize(); // split on the outermost dimension available - splitAxis = VImageDimension - 1; - while (regionSize[splitAxis] == 1) - { - --splitAxis; - if (splitAxis < 0) - { // cannot split - itkDebugMacro(" Cannot Split"); - return 1; - } + splitAxis = VImageDimension - 1; + while (regionSize[splitAxis] == 1) + { + --splitAxis; + if (splitAxis < 0) + { // cannot split + itkDebugMacro(" Cannot Split"); + return 1; } + } // determine the actual number of pieces that will be generated - SizeValueType range = regionSize[splitAxis]; - int valuesPerPiece = ((int)::ceil(range/((double)requestedNumber*256))) * 256; - int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece); + SizeValueType range = regionSize[splitAxis]; + int valuesPerPiece = ((int)::ceil(range/((double)requestedNumber*256))) * 256; + int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece); - return maxPieceUsed + 1; - } + return maxPieceUsed + 1; +} /** * */ - template <unsigned int VImageDimension> - itk::ImageRegion<VImageDimension> - ImageRegionTileMapSplitter<VImageDimension> - ::GetSplit(unsigned int i, unsigned int numberOfPieces, const RegionType ®ion) - { - int splitAxis; - RegionType splitRegion; - IndexType splitIndex; - SizeType splitSize, regionSize; +template <unsigned int VImageDimension> +itk::ImageRegion<VImageDimension> +ImageRegionTileMapSplitter<VImageDimension> +::GetSplit(unsigned int i, unsigned int numberOfPieces, const RegionType ®ion) +{ + int splitAxis; + RegionType splitRegion; + IndexType splitIndex; + SizeType splitSize, regionSize; // Initialize the splitRegion to the requested region - splitRegion = region; - splitIndex = splitRegion.GetIndex(); - splitSize = splitRegion.GetSize(); + splitRegion = region; + splitIndex = splitRegion.GetIndex(); + splitSize = splitRegion.GetSize(); - regionSize = region.GetSize(); + regionSize = region.GetSize(); // split on the outermost dimension available - splitAxis = VImageDimension - 1; - while (regionSize[splitAxis] == 1) - { - --splitAxis; - if (splitAxis < 0) - { // cannot split - itkDebugMacro(" Cannot Split"); - return splitRegion; - } - } + splitAxis = VImageDimension - 1; + while (regionSize[splitAxis] == 1) + { + --splitAxis; + if (splitAxis < 0) + { // cannot split + itkDebugMacro(" Cannot Split"); + return splitRegion; + } + } // determine the actual number of pieces that will be generated - SizeValueType range = regionSize[splitAxis]; - int valuesPerPiece = ((int)::ceil(range/((double)numberOfPieces*256))) * 256; - int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece); + SizeValueType range = regionSize[splitAxis]; + int valuesPerPiece = ((int)::ceil(range/((double)numberOfPieces*256))) * 256; + int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece); // Split the region - if ((int) i == maxPieceUsed-1) - { - splitIndex[splitAxis] += i*valuesPerPiece; + if ((int) i == maxPieceUsed-1) + { + splitIndex[splitAxis] += i*valuesPerPiece; // last piece needs to process the "rest" dimension being split // splitSize[splitAxis] = splitSize[splitAxis] - i*valuesPerPiece; - splitSize[splitAxis] = regionSize[splitAxis] - splitIndex[splitAxis]; - } - if (((int) i == 0) && ((int) i != maxPieceUsed-1)) - { + splitSize[splitAxis] = regionSize[splitAxis] - splitIndex[splitAxis]; + } + if (((int) i == 0) && ((int) i != maxPieceUsed-1)) + { //First piece may not contain a whole piece //splitIndex stay at splitRegion.GetIndex(); - splitSize[splitAxis] = (((int)::floor(splitIndex[splitAxis]/valuesPerPiece))+1) - *valuesPerPiece - splitIndex[splitAxis]; - } - if ((int) i < maxPieceUsed-1) - { - splitIndex[splitAxis] += i*valuesPerPiece; - splitSize[splitAxis] = valuesPerPiece; - } + splitSize[splitAxis] = (((int)::floor(splitIndex[splitAxis]/valuesPerPiece))+1) + *valuesPerPiece - splitIndex[splitAxis]; + } + if ((int) i < maxPieceUsed-1) + { + splitIndex[splitAxis] += i*valuesPerPiece; + splitSize[splitAxis] = valuesPerPiece; + } // set the split region ivars - splitRegion.SetIndex( splitIndex ); - splitRegion.SetSize( splitSize ); + splitRegion.SetIndex( splitIndex ); + splitRegion.SetSize( splitSize ); - itkDebugMacro(" Split Piece: " << splitRegion ); + itkDebugMacro(" Split Piece: " << splitRegion ); - return splitRegion; - } + return splitRegion; +} /** * */ - template <unsigned int VImageDimension> - void - ImageRegionTileMapSplitter<VImageDimension> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template <unsigned int VImageDimension> +void +ImageRegionTileMapSplitter<VImageDimension> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} } // end namespace itk diff --git a/Code/Common/otbImageToImageListFilter.h b/Code/Common/otbImageToImageListFilter.h index 627cca7252b2c4dabf8e15544925dd8a6f7201b5..7c6529a21368a5056995c74e5ff286ce350580cf 100644 --- a/Code/Common/otbImageToImageListFilter.h +++ b/Code/Common/otbImageToImageListFilter.h @@ -32,7 +32,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageToImageListFilter - : public ImageListSource<TOutputImage> + : public ImageListSource<TOutputImage> { public: /** Standard typedefs */ @@ -66,7 +66,7 @@ protected: ImageToImageListFilter(); /** Destructor */ virtual ~ImageToImageListFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/Common/otbImageToImageListFilter.txx b/Code/Common/otbImageToImageListFilter.txx index 36b92a9b417f2b365340a54b1bc4ac8605122c96..3358d596f821c6ef3b038ffd4b25c7bf0c5baff6 100644 --- a/Code/Common/otbImageToImageListFilter.txx +++ b/Code/Common/otbImageToImageListFilter.txx @@ -54,13 +54,13 @@ ImageToImageListFilter<TInputImage,TOutputImage> { // If there is no input if (this->GetNumberOfInputs()<1) - { + { // exit return 0; - } + } // else return the first input return static_cast<TInputImage * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** * PrintSelf Method diff --git a/Code/Common/otbImageToLineSpatialObjectListFilter.h b/Code/Common/otbImageToLineSpatialObjectListFilter.h index e7dc393aa66ca0db6971b5aa2c44c9e9312379da..cd3ea4f81351b8a56c148d957b1c1943d0b9e784 100644 --- a/Code/Common/otbImageToLineSpatialObjectListFilter.h +++ b/Code/Common/otbImageToLineSpatialObjectListFilter.h @@ -44,7 +44,7 @@ public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); diff --git a/Code/Common/otbImageToLineSpatialObjectListFilter.txx b/Code/Common/otbImageToLineSpatialObjectListFilter.txx index 79073d799932a015cd0b9b73280f9c32b62bcdea..941b05c33ebd12b6295a709a6f2e7e06a5dad758 100644 --- a/Code/Common/otbImageToLineSpatialObjectListFilter.txx +++ b/Code/Common/otbImageToLineSpatialObjectListFilter.txx @@ -29,11 +29,11 @@ namespace otb template<class TInputImage> ImageToLineSpatialObjectListFilter<TInputImage>::ImageToLineSpatialObjectListFilter() { - this->SetNumberOfRequiredInputs(1); - this->SetNumberOfRequiredOutputs(1); + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); - typename LinesListType::Pointer list = LinesListType::New(); - this->SetOutput( list ); + typename LinesListType::Pointer list = LinesListType::New(); + this->SetOutput( list ); } @@ -43,7 +43,7 @@ ImageToLineSpatialObjectListFilter<TInputImage> ::SetInput(const InputImageType *image) { this->itk::ProcessObject::SetNthInput(0, - const_cast< InputImageType * >( image ) ); + const_cast< InputImageType * >( image ) ); } @@ -52,8 +52,8 @@ const typename ImageToLineSpatialObjectListFilter<TInputImage>::InputImageType * ImageToLineSpatialObjectListFilter<TInputImage> ::GetInput(void) { - return static_cast<const InputImageType *> - (this->itk::ProcessObject::GetInput(0) ); + return static_cast<const InputImageType *> + (this->itk::ProcessObject::GetInput(0) ); } @@ -61,10 +61,10 @@ template <class TInputImage> void ImageToLineSpatialObjectListFilter<TInputImage> ::SetOutput(const LinesListType *list) - { - this->ProcessObjectType::SetNthOutput(0, - const_cast< LinesListType * >( list ) ); - } +{ + this->ProcessObjectType::SetNthOutput(0, + const_cast< LinesListType * >( list ) ); +} template <class TInputImage> @@ -72,8 +72,8 @@ typename ImageToLineSpatialObjectListFilter<TInputImage>::LinesListType * ImageToLineSpatialObjectListFilter<TInputImage> ::GetOutput(void) { - return static_cast<LinesListType *> - (this->ProcessObjectType::GetOutput(0) ); + return static_cast<LinesListType *> + (this->ProcessObjectType::GetOutput(0) ); } diff --git a/Code/Common/otbImageToPathFilter.h b/Code/Common/otbImageToPathFilter.h index 2ffb69ce45f6d71a28d4ec25980e9e827b8c9d03..cbfd5c223949946062b8c5a28518c652bafcac34 100644 --- a/Code/Common/otbImageToPathFilter.h +++ b/Code/Common/otbImageToPathFilter.h @@ -29,7 +29,7 @@ namespace otb */ template <class TInputImage, class TOutputPath> class ITK_EXPORT ImageToPathFilter - : public itk::PathSource<TOutputPath> + : public itk::PathSource<TOutputPath> { public: /// Standard class typedefs @@ -55,7 +55,7 @@ public: protected: ImageToPathFilter(); - virtual ~ImageToPathFilter(){}; + virtual ~ImageToPathFilter() {}; virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/Common/otbImageToPathListFilter.txx b/Code/Common/otbImageToPathListFilter.txx index 65f565894b441e96fc18a105be4b8329040d88d0..09366ba9174df7b08ce51c4906dfed64e3bd8dd6 100644 --- a/Code/Common/otbImageToPathListFilter.txx +++ b/Code/Common/otbImageToPathListFilter.txx @@ -44,8 +44,8 @@ void ImageToPathListFilter<TInputImage,TOutputPath> ::SetInput(const InputImageType *image) { - // We have 1 input: an image - + // We have 1 input: an image + // Process object is not const-correct so the const_cast is required here this->ProcessObjectType::SetNthInput(0,const_cast< InputImageType * >( image ) ); } @@ -55,15 +55,15 @@ const typename ImageToPathListFilter<TInputImage,TOutputPath>::InputImageType * ImageToPathListFilter<TInputImage,TOutputPath> ::GetInput(void) { - - + + if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<const TInputImage * > - (this->ProcessObjectType::GetInput(0) ); + (this->ProcessObjectType::GetInput(0) ); } /** diff --git a/Code/Common/otbImageToVectorImageCastFilter.h b/Code/Common/otbImageToVectorImageCastFilter.h index c26d3c3041da24112c0c8cdf591f553de29a9eeb..3813631d962dc0dd5dfda7c16055ca61eb137727 100644 --- a/Code/Common/otbImageToVectorImageCastFilter.h +++ b/Code/Common/otbImageToVectorImageCastFilter.h @@ -24,90 +24,90 @@ namespace otb { namespace Functor - { - /** - * \class VectorCast - * \brief This functor can be used to convert scalar value to VariableLengthVector with another precision - * a size of 1. - * \ingroup Functor - * - */ - template <class TInput, class TOutput> - class VectorCast - { - public: +{ +/** + * \class VectorCast + * \brief This functor can be used to convert scalar value to VariableLengthVector with another precision + * a size of 1. + * \ingroup Functor + * + */ +template <class TInput, class TOutput> +class VectorCast +{ +public: typedef typename TOutput::ValueType OutputValueType; VectorCast() {}; - ~VectorCast(){}; + ~VectorCast() {}; bool operator!=(const VectorCast&) const - { - return false; - } + { + return false; + } bool operator==(const VectorCast& other) const - { - return(*this != other); - } + { + return(*this != other); + } inline TOutput operator () (const TInput & A) - { - TOutput output; - output.SetSize(1); - output[0] = static_cast<OutputValueType>(A); - return output; - } - }; - } // End namespace Functor - /** - * \class ImageToVectorImageCastFilter - * \brief This is a helper class that convert an otb::Image into a single-channel otb::VectorImage. - * \ingroup Singlethreaded - * - */ + { + TOutput output; + output.SetSize(1); + output[0] = static_cast<OutputValueType>(A); + return output; + } +}; +} // End namespace Functor +/** + * \class ImageToVectorImageCastFilter + * \brief This is a helper class that convert an otb::Image into a single-channel otb::VectorImage. + * \ingroup Singlethreaded + * + */ template <class TInputImage, class TOutputVectorImage> class ITK_EXPORT ImageToVectorImageCastFilter - : public itk::UnaryFunctorImageFilter<TInputImage, TOutputVectorImage, - Functor::VectorCast<typename TInputImage::PixelType, typename TOutputVectorImage::PixelType> > - { - public: - /// Standard class typedefs - typedef ImageToVectorImageCastFilter Self; - typedef itk::UnaryFunctorImageFilter<TInputImage, TOutputVectorImage, Functor::VectorCast<typename TInputImage::PixelType, - typename TOutputVectorImage::PixelType> > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + : public itk::UnaryFunctorImageFilter<TInputImage, TOutputVectorImage, + Functor::VectorCast<typename TInputImage::PixelType, typename TOutputVectorImage::PixelType> > +{ +public: + /// Standard class typedefs + typedef ImageToVectorImageCastFilter Self; + typedef itk::UnaryFunctorImageFilter<TInputImage, TOutputVectorImage, Functor::VectorCast<typename TInputImage::PixelType, + typename TOutputVectorImage::PixelType> > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /// Method for creation through the object factory - itkNewMacro(Self); + /// Method for creation through the object factory + itkNewMacro(Self); - /// Runtime information - itkTypeMacro(ImageToVectorImageCastFilter,itk::UnaryFunctorImageFilter); + /// Runtime information + itkTypeMacro(ImageToVectorImageCastFilter,itk::UnaryFunctorImageFilter); - protected: - /// Constructor - ImageToVectorImageCastFilter() {} - /// Detructor - virtual ~ImageToVectorImageCastFilter() {} - /// Additionnal output information for allocation - virtual void GenerateOutputInformation(void) - { - Superclass::GenerateOutputInformation(); - this->GetOutput()->SetNumberOfComponentsPerPixel(1); - } - /// Copy output requested region to input requested region - virtual void GenerateInputRequestedRegion(void) - { - if(this->GetInput()) +protected: + /// Constructor + ImageToVectorImageCastFilter() {} + /// Detructor + virtual ~ImageToVectorImageCastFilter() {} + /// Additionnal output information for allocation + virtual void GenerateOutputInformation(void) + { + Superclass::GenerateOutputInformation(); + this->GetOutput()->SetNumberOfComponentsPerPixel(1); + } + /// Copy output requested region to input requested region + virtual void GenerateInputRequestedRegion(void) + { + if (this->GetInput()) { typename TInputImage::Pointer input = const_cast<TInputImage *>(this->GetInput()); typename TInputImage::RegionType inputRegion; this->CallCopyOutputRegionToInputRegion(inputRegion,this->GetOutput()->GetRequestedRegion()); input->SetRequestedRegion(inputRegion); } - } + } - private: - ImageToVectorImageCastFilter(const Self&); //purposely not implemented - void operator = (const Self&); // purposely not implemented - }; +private: + ImageToVectorImageCastFilter(const Self&); //purposely not implemented + void operator = (const Self&); // purposely not implemented +}; }// end namespace otb #endif diff --git a/Code/Common/otbLineSpatialObject.h b/Code/Common/otbLineSpatialObject.h index d09adc1497d035c2bdb15816968d7eef4356dede..c32e8ab8e4976be2bbe6441fbb69726b6e8c37a7 100644 --- a/Code/Common/otbLineSpatialObject.h +++ b/Code/Common/otbLineSpatialObject.h @@ -32,7 +32,7 @@ namespace otb */ template < unsigned int VDimension = 3 > class ITK_EXPORT LineSpatialObject - : public itk::PointBasedSpatialObject<VDimension> + : public itk::PointBasedSpatialObject<VDimension> { public: /** Standard typedefs */ @@ -44,7 +44,7 @@ public: /** Type macro */ itkNewMacro(Self); - /** Method for creation through the object factory. */ + /** Method for creation through the object factory. */ itkTypeMacro( LineSpatialObject, PointBasedSpatialObject ); /** Superclass typedefs */ @@ -67,13 +67,22 @@ public: void SetPoints( PointListType & newPoints ); /** Return a point in the list given the index */ - const SpatialObjectPointType* GetPoint(unsigned long id) const {return &(m_Points[id]);} + const SpatialObjectPointType* GetPoint(unsigned long id) const + { + return &(m_Points[id]); + } /** Return a point in the list given the index */ - SpatialObjectPointType* GetPoint(unsigned long id) {return &(m_Points[id]);} + SpatialObjectPointType* GetPoint(unsigned long id) + { + return &(m_Points[id]); + } /** Return the number of points in the list */ - unsigned long GetNumberOfPoints(void) const {return m_Points.size();} + unsigned long GetNumberOfPoints(void) const + { + return m_Points.size(); + } /** Returns true if the line is evaluable at the requested point, * false otherwise. */ diff --git a/Code/Common/otbLineSpatialObject.txx b/Code/Common/otbLineSpatialObject.txx index bdaded8ac8cef9826205f2d8958200ca43717c3b..970f4f3754097a34eceae4bdcc59daf3008cba54 100644 --- a/Code/Common/otbLineSpatialObject.txx +++ b/Code/Common/otbLineSpatialObject.txx @@ -70,11 +70,11 @@ LineSpatialObject< VDimension > typename PointListType::iterator it,end; it = points.begin(); end = points.end(); - while(it != end) - { + while (it != end) + { m_Points.push_back(*it); it++; - } + } this->ComputeBoundingBox(); this->Modified(); @@ -99,39 +99,39 @@ LineSpatialObject< VDimension > ::ComputeLocalBoundingBox() const { // tbMsgDevMacro( "Computing tube bounding box" ); - if( this->GetBoundingBoxChildrenName().empty() - || strstr(typeid(Self).name(), this->GetBoundingBoxChildrenName().c_str()) ) + if ( this->GetBoundingBoxChildrenName().empty() + || strstr(typeid(Self).name(), this->GetBoundingBoxChildrenName().c_str()) ) + { + typename PointListType::const_iterator it = m_Points.begin(); + typename PointListType::const_iterator end = m_Points.end(); + + if (it == end) + { + return false; + } + else + { + PointType pt = this->GetIndexToWorldTransform()->TransformPoint((*it).GetPosition()); + PointType ptmin; + PointType ptmax; + ptmin[0]=pt[0]-1; + ptmin[1]=pt[1]-1; + ptmax[0]=pt[0]+1; + ptmax[1]=pt[1]+1; + const_cast<BoundingBoxType *>(this->GetBounds())->SetMinimum(ptmin); + const_cast<BoundingBoxType *>(this->GetBounds())->SetMaximum(ptmax); + it++; + while (it!= end) { - typename PointListType::const_iterator it = m_Points.begin(); - typename PointListType::const_iterator end = m_Points.end(); - if(it == end) - { - return false; - } - else - { - PointType pt = this->GetIndexToWorldTransform()->TransformPoint((*it).GetPosition()); - PointType ptmin; - PointType ptmax; - ptmin[0]=pt[0]-1; - ptmin[1]=pt[1]-1; - ptmax[0]=pt[0]+1; - ptmax[1]=pt[1]+1; - const_cast<BoundingBoxType *>(this->GetBounds())->SetMinimum(ptmin); - const_cast<BoundingBoxType *>(this->GetBounds())->SetMaximum(ptmax); + PointType pt = this->GetIndexToWorldTransform()->TransformPoint((*it).GetPosition()); + const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pt); it++; - while(it!= end) - { - - PointType pt = this->GetIndexToWorldTransform()->TransformPoint((*it).GetPosition()); - const_cast<BoundingBoxType *>(this->GetBounds())->ConsiderPoint(pt); - it++; - } - - } } + } + } + return true; } @@ -147,50 +147,50 @@ LineSpatialObject< VDimension > typename PointListType::const_iterator it1 = m_Points.begin(); typename PointListType::const_iterator end = m_Points.end(); typename PointListType::const_iterator it2 = it1+1; - if(!this->GetIndexToWorldTransform()->GetInverse(const_cast<TransformType *>(this->GetInternalInverseTransform()))) - { + if (!this->GetIndexToWorldTransform()->GetInverse(const_cast<TransformType *>(this->GetInternalInverseTransform()))) + { return false; - } + } PointType transformedPoint = this->GetInternalInverseTransform()->TransformPoint(point); - if( this->GetBounds()->IsInside(transformedPoint) ) + if ( this->GetBounds()->IsInside(transformedPoint) ) + { + while (it2 != end) { - while(it2 != end) + if ((*it1).GetPosition()[0] < (*it2).GetPosition()[0]) { - if((*it1).GetPosition()[0] < (*it2).GetPosition()[0]) - { - if( transformedPoint[1]==(int) ((*it1).GetPosition()[1]+(((*it2).GetPosition()[1]-(*it1).GetPosition()[1])/((*it2).GetPosition()[0]-(*it1).GetPosition()[0]))*(transformedPoint[0]-(*it1).GetPosition()[0])) && transformedPoint[0]>=(*it1).GetPosition()[0] && transformedPoint[0]<=(*it2).GetPosition()[0]) - { - return true; - } - } - else - { - if(transformedPoint[1]==(int) ((((*it2).GetPosition()[1]-(*it1).GetPosition()[1])/((*it1).GetPosition()[0]-(*it2).GetPosition()[0]))*((*it1).GetPosition()[0]-transformedPoint[0])+(*it1).GetPosition()[1]) && transformedPoint[0]>=(*it2).GetPosition()[0] && transformedPoint[0]<=(*it1).GetPosition()[0]) - { - return true; - } - } - if((*it1).GetPosition()[1]<(*it2).GetPosition()[1]) - { - if(transformedPoint[0]==(int) ((((*it2).GetPosition()[0]-(*it1).GetPosition()[0])/((*it2).GetPosition()[1]-(*it1).GetPosition()[1]))*(transformedPoint[1]-(*it1).GetPosition()[1])+(*it1).GetPosition()[0]) && transformedPoint[1]>=(*it1).GetPosition()[1] && transformedPoint[1]<=(*it2).GetPosition()[1]) - { - return true; - } - } - else - { - if(transformedPoint[0]==(int) ((((*it2).GetPosition()[0]-(*it1).GetPosition()[0])/((*it1).GetPosition()[1]-(*it2).GetPosition()[1]))*((*it1).GetPosition()[1]-transformedPoint[1])+(*it1).GetPosition()[0]) && transformedPoint[1]>=(*it2).GetPosition()[1] && transformedPoint[1]<=(*it1).GetPosition()[1]) - { - return true; - } - } - it1++; - it2++; - } - + if ( transformedPoint[1]==(int) ((*it1).GetPosition()[1]+(((*it2).GetPosition()[1]-(*it1).GetPosition()[1])/((*it2).GetPosition()[0]-(*it1).GetPosition()[0]))*(transformedPoint[0]-(*it1).GetPosition()[0])) && transformedPoint[0]>=(*it1).GetPosition()[0] && transformedPoint[0]<=(*it2).GetPosition()[0]) + { + return true; + } + } + else + { + if (transformedPoint[1]==(int) ((((*it2).GetPosition()[1]-(*it1).GetPosition()[1])/((*it1).GetPosition()[0]-(*it2).GetPosition()[0]))*((*it1).GetPosition()[0]-transformedPoint[0])+(*it1).GetPosition()[1]) && transformedPoint[0]>=(*it2).GetPosition()[0] && transformedPoint[0]<=(*it1).GetPosition()[0]) + { + return true; } + } + if ((*it1).GetPosition()[1]<(*it2).GetPosition()[1]) + { + if (transformedPoint[0]==(int) ((((*it2).GetPosition()[0]-(*it1).GetPosition()[0])/((*it2).GetPosition()[1]-(*it1).GetPosition()[1]))*(transformedPoint[1]-(*it1).GetPosition()[1])+(*it1).GetPosition()[0]) && transformedPoint[1]>=(*it1).GetPosition()[1] && transformedPoint[1]<=(*it2).GetPosition()[1]) + { + return true; + } + } + else + { + if (transformedPoint[0]==(int) ((((*it2).GetPosition()[0]-(*it1).GetPosition()[0])/((*it1).GetPosition()[1]-(*it2).GetPosition()[1]))*((*it1).GetPosition()[1]-transformedPoint[1])+(*it1).GetPosition()[0]) && transformedPoint[1]>=(*it2).GetPosition()[1] && transformedPoint[1]<=(*it1).GetPosition()[1]) + { + return true; + } + } + it1++; + it2++; + } + + } return false; } @@ -203,20 +203,20 @@ LineSpatialObject< VDimension > { // otbMsgDevMacro( "Checking the point [" << point << "] is on the Line" ); - if(name == NULL) + if (name == NULL) + { + if (IsInside(point)) { - if(IsInside(point)) - { return true; - } } - else if(strstr(typeid(Self).name(), name)) + } + else if (strstr(typeid(Self).name(), name)) + { + if (IsInside(point)) { - if(IsInside(point)) - { return true; - } } + } return Superclass::IsInside(point, depth, name); } @@ -243,24 +243,24 @@ LineSpatialObject< VDimension > { // otbMsgDevMacro( "Getting the value of the tube at " << point ); - if( IsInside(point, 0, name) ) - { + if ( IsInside(point, 0, name) ) + { value = this->GetDefaultInsideValue(); return true; - } + } else + { + if ( Superclass::IsEvaluableAt(point, depth, name) ) { - if( Superclass::IsEvaluableAt(point, depth, name) ) - { Superclass::ValueAt(point, value, depth, name); return true; - } + } else - { + { value = this->GetDefaultOutsideValue(); return false; - } } + } return false; } } // end namespace otb diff --git a/Code/Common/otbLineSpatialObjectList.h b/Code/Common/otbLineSpatialObjectList.h index 68cc0e098e2506a4082eef657814d4261cee2d77..1bc0bb670a51558ba87c702864cb6e549f4a3735 100644 --- a/Code/Common/otbLineSpatialObjectList.h +++ b/Code/Common/otbLineSpatialObjectList.h @@ -33,7 +33,7 @@ namespace otb */ class ITK_EXPORT LineSpatialObjectList : public std::list< itk::LineSpatialObject<2>::Pointer >, - public itk::DataObject + public itk::DataObject { public: @@ -54,7 +54,7 @@ public: typedef itk::LineSpatialObject<2> LineType; protected : - LineSpatialObjectList(){}; + LineSpatialObjectList() {}; ~LineSpatialObjectList() {}; private: diff --git a/Code/Common/otbList.h b/Code/Common/otbList.h index 0e0b34d117e5012ada4b20f3a546cf28f045b67d..4657558603d2b2b9ac4bec13b22254f12799596b 100644 --- a/Code/Common/otbList.h +++ b/Code/Common/otbList.h @@ -32,9 +32,9 @@ namespace otb */ template <class TObject> class ITK_EXPORT List - : public itk::DataObject + : public itk::DataObject { - public: +public: /** Standard typedefs */ typedef List Self; typedef itk::DataObject Superclass; @@ -109,10 +109,10 @@ class ITK_EXPORT List } - /** - * Return the first element of the list. - * \return The first element of the list. - */ + /** + * Return the first element of the list. + * \return The first element of the list. + */ ObjectType* Front(void); /** * Return the first element of the const list. @@ -146,351 +146,351 @@ class ITK_EXPORT List * \brief Iterator of the object list. */ class Iterator + { + public: + friend class List; + friend class ConstIterator; + /** typedef of the internal iterator */ + typedef typename InternalContainerType::iterator InternalIteratorType; + /** Constructor */ + Iterator() {}; + /** Constructor with iternal iterator parameter */ + Iterator(InternalIteratorType iter) { - public: - friend class List; - friend class ConstIterator; - /** typedef of the internal iterator */ - typedef typename InternalContainerType::iterator InternalIteratorType; - /** Constructor */ - Iterator(){}; - /** Constructor with iternal iterator parameter */ - Iterator(InternalIteratorType iter) - { - m_Iter=iter; - } - /** - * Get the current object. - * \return The current object pointed by the iterator. - */ - ObjectPointerType Get(void) - { - return (*m_Iter); - } - /** - * Increment. - */ - Iterator& operator++() - { - ++m_Iter; + m_Iter=iter; + } + /** + * Get the current object. + * \return The current object pointed by the iterator. + */ + ObjectPointerType Get(void) + { + return (*m_Iter); + } + /** + * Increment. + */ + Iterator& operator++() + { + ++m_Iter; return *this; - } - /** - * Decrement. - */ - Iterator& operator--() - { - --m_Iter; + } + /** + * Decrement. + */ + Iterator& operator--() + { + --m_Iter; return *this; - } - /** - * Add - */ - Iterator operator+(int i) - { - Iterator lIter(m_Iter+1); + } + /** + * Add + */ + Iterator operator+(int i) + { + Iterator lIter(m_Iter+1); return lIter; - } + } - /** - * Remove - */ - Iterator operator-(int i) - { - Iterator lIter(m_Iter-i); + /** + * Remove + */ + Iterator operator-(int i) + { + Iterator lIter(m_Iter-i); return lIter; - } - /** - * Difference comparison operator. - */ - bool operator!=(const Iterator &it) - { - return (m_Iter != it.m_Iter); - } - /** - * Equality comparison operator. - */ - bool operator==(const Iterator &it) - { - return (m_Iter == it.m_Iter); - } - /** - * Instantiation operator. - */ - Iterator& operator=(const Iterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Difference comparison operator. + */ + bool operator!=(const Iterator &it) + { + return (m_Iter != it.m_Iter); + } + /** + * Equality comparison operator. + */ + bool operator==(const Iterator &it) + { + return (m_Iter == it.m_Iter); + } + /** + * Instantiation operator. + */ + Iterator& operator=(const Iterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Copy operator. - */ - Iterator(const Iterator &it) - { - m_Iter=it.m_Iter; - } + } + /** + * Copy operator. + */ + Iterator(const Iterator &it) + { + m_Iter=it.m_Iter; + } /** * Get the current internal iterator */ InternalIteratorType & GetIter(void) { - return(m_Iter); + return(m_Iter); } - private: - // Internal iterator. - InternalIteratorType m_Iter; - }; + private: + // Internal iterator. + InternalIteratorType m_Iter; + }; /** \class ConstIterator * \brief ConstIterator of the object list. */ class ConstIterator + { + public: + /** typedef of the internal iterator */ + typedef typename InternalContainerType::const_iterator InternalConstIteratorType; + /** Constructor */ + ConstIterator() {}; + /** Constructor with iternal iterator parameter */ + ConstIterator(InternalConstIteratorType iter) + { + m_Iter=iter; + } + /** + * Get the current object. + * \return The current object pointed by the iterator. + */ + ObjectPointerType Get(void) { - public: - /** typedef of the internal iterator */ - typedef typename InternalContainerType::const_iterator InternalConstIteratorType; - /** Constructor */ - ConstIterator(){}; - /** Constructor with iternal iterator parameter */ - ConstIterator(InternalConstIteratorType iter) - { - m_Iter=iter; - } - /** - * Get the current object. - * \return The current object pointed by the iterator. - */ - ObjectPointerType Get(void) - { - return (*m_Iter); - } - /** - * Increment. - */ - ConstIterator& operator++() - { - ++m_Iter; + return (*m_Iter); + } + /** + * Increment. + */ + ConstIterator& operator++() + { + ++m_Iter; return *this; - } - /** - * Decrement. - */ - ConstIterator& operator--() - { - --m_Iter; + } + /** + * Decrement. + */ + ConstIterator& operator--() + { + --m_Iter; return *this; - } - /** - * Difference comparison operator. - */ - bool operator!=(const ConstIterator &it) - { - return (m_Iter != it.m_Iter); - } - /** - * Equality comparison operator. - */ - bool operator==(const ConstIterator &it) - { - return (m_Iter == it.m_Iter); - } - /** - * Instantiation operator. - */ - ConstIterator& operator=(const ConstIterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Difference comparison operator. + */ + bool operator!=(const ConstIterator &it) + { + return (m_Iter != it.m_Iter); + } + /** + * Equality comparison operator. + */ + bool operator==(const ConstIterator &it) + { + return (m_Iter == it.m_Iter); + } + /** + * Instantiation operator. + */ + ConstIterator& operator=(const ConstIterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Instantiation operator. - */ - ConstIterator& operator=(const Iterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Instantiation operator. + */ + ConstIterator& operator=(const Iterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Copy operator. - */ - ConstIterator(const ConstIterator &it) - { - m_Iter=it.m_Iter; - } - /** - * Copy operator. - */ - ConstIterator(const Iterator &it) - { - m_Iter=it.m_Iter; - } + } + /** + * Copy operator. + */ + ConstIterator(const ConstIterator &it) + { + m_Iter=it.m_Iter; + } + /** + * Copy operator. + */ + ConstIterator(const Iterator &it) + { + m_Iter=it.m_Iter; + } - private: - // Internal iterator. - InternalConstIteratorType m_Iter; - }; + private: + // Internal iterator. + InternalConstIteratorType m_Iter; + }; /** \class ReverseIterator * \brief ReverseIterator of the object list. */ class ReverseIterator + { + public: + friend class ReverseConstIterator; + /** typedef of the internal iterator */ + typedef typename InternalContainerType::reverse_iterator InternalReverseIteratorType; + /** Constructor */ + ReverseIterator() {}; + /** Constructor with iternal iterator parameter */ + ReverseIterator(InternalReverseIteratorType iter) + { + m_Iter=iter; + } + /** + * Get the current object. + * \return The current object pointed by the iterator. + */ + ObjectPointerType Get(void) { - public: - friend class ReverseConstIterator; - /** typedef of the internal iterator */ - typedef typename InternalContainerType::reverse_iterator InternalReverseIteratorType; - /** Constructor */ - ReverseIterator(){}; - /** Constructor with iternal iterator parameter */ - ReverseIterator(InternalReverseIteratorType iter) - { - m_Iter=iter; - } - /** - * Get the current object. - * \return The current object pointed by the iterator. - */ - ObjectPointerType Get(void) - { - return (*m_Iter); - } - /** - * Increment. - */ - ReverseIterator& operator++() - { - ++m_Iter; + return (*m_Iter); + } + /** + * Increment. + */ + ReverseIterator& operator++() + { + ++m_Iter; return *this; - } - /** - * Decrement. - */ - ReverseIterator& operator--() - { - --m_Iter; + } + /** + * Decrement. + */ + ReverseIterator& operator--() + { + --m_Iter; return *this; - } - /** - * Difference comparison operator. - */ - bool operator!=(const ReverseIterator &it) - { - return (m_Iter != it.m_Iter); - } - /** - * Equality comparison operator. - */ - bool operator==(const ReverseIterator &it) - { - return (m_Iter == it.m_Iter); - } - /** - * Instantiation operator. - */ - ReverseIterator& operator=(const ReverseIterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Difference comparison operator. + */ + bool operator!=(const ReverseIterator &it) + { + return (m_Iter != it.m_Iter); + } + /** + * Equality comparison operator. + */ + bool operator==(const ReverseIterator &it) + { + return (m_Iter == it.m_Iter); + } + /** + * Instantiation operator. + */ + ReverseIterator& operator=(const ReverseIterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Copy operator. - */ - ReverseIterator(const ReverseIterator &it) - { - m_Iter=it.m_Iter; - } + } + /** + * Copy operator. + */ + ReverseIterator(const ReverseIterator &it) + { + m_Iter=it.m_Iter; + } - private: - // Internal iterator. - InternalReverseIteratorType m_Iter; - }; + private: + // Internal iterator. + InternalReverseIteratorType m_Iter; + }; /** \class ReverseConstIterator * \brief ReverseConstIterator of the object list. */ class ReverseConstIterator + { + public: + /** typedef of the internal iterator */ + typedef typename InternalContainerType::reverse_iterator InternalReverseConstIteratorType; + /** Constructor */ + ReverseConstIterator() {}; + /** Constructor with iternal iterator parameter */ + ReverseConstIterator(InternalReverseConstIteratorType iter) + { + m_Iter=iter; + } + /** + * Get the current object. + * \return The current object pointed by the iterator. + */ + ObjectPointerType Get(void) { - public: - /** typedef of the internal iterator */ - typedef typename InternalContainerType::reverse_iterator InternalReverseConstIteratorType; - /** Constructor */ - ReverseConstIterator(){}; - /** Constructor with iternal iterator parameter */ - ReverseConstIterator(InternalReverseConstIteratorType iter) - { - m_Iter=iter; - } - /** - * Get the current object. - * \return The current object pointed by the iterator. - */ - ObjectPointerType Get(void) - { - return (*m_Iter); - } - /** - * Increment. - */ - ReverseConstIterator& operator++() - { - ++m_Iter; + return (*m_Iter); + } + /** + * Increment. + */ + ReverseConstIterator& operator++() + { + ++m_Iter; return *this; - } - /** - * Decrement. - */ - ReverseConstIterator& operator--() - { - --m_Iter; + } + /** + * Decrement. + */ + ReverseConstIterator& operator--() + { + --m_Iter; return *this; - } - /** - * Difference comparison operator. - */ - bool operator!=(const ReverseConstIterator &it) - { - return (m_Iter != it.m_Iter); - } - /** - * Equality comparison operator. - */ - bool operator==(const ReverseConstIterator &it) - { - return (m_Iter == it.m_Iter); - } - /** - * Instantiation operator. - */ - ReverseConstIterator& operator=(const ReverseConstIterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Difference comparison operator. + */ + bool operator!=(const ReverseConstIterator &it) + { + return (m_Iter != it.m_Iter); + } + /** + * Equality comparison operator. + */ + bool operator==(const ReverseConstIterator &it) + { + return (m_Iter == it.m_Iter); + } + /** + * Instantiation operator. + */ + ReverseConstIterator& operator=(const ReverseConstIterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Instantiation operator. - */ - ReverseConstIterator& operator=(const ReverseIterator &it) - { - m_Iter = it.m_Iter; + } + /** + * Instantiation operator. + */ + ReverseConstIterator& operator=(const ReverseIterator &it) + { + m_Iter = it.m_Iter; return *this; - } - /** - * Copy operator. - */ - ReverseConstIterator(const ReverseConstIterator &it) - { - m_Iter=it.m_Iter; - } - /** - * Copy operator. - */ - ReverseConstIterator(const ReverseIterator &it) - { - m_Iter=it.m_Iter; - } + } + /** + * Copy operator. + */ + ReverseConstIterator(const ReverseConstIterator &it) + { + m_Iter=it.m_Iter; + } + /** + * Copy operator. + */ + ReverseConstIterator(const ReverseIterator &it) + { + m_Iter=it.m_Iter; + } - private: - // Internal iterator. - InternalReverseConstIteratorType m_Iter; - }; + private: + // Internal iterator. + InternalReverseConstIteratorType m_Iter; + }; /** * Get an Iterator that points to the beginning of the container. * \return The iterator. @@ -511,10 +511,10 @@ class ITK_EXPORT List * \return The iterator. */ ReverseConstIterator ReverseBegin(void) const; - /** - * Get an Iterator that points past-the-end of the container. - * \return The iterator. - */ + /** + * Get an Iterator that points past-the-end of the container. + * \return The iterator. + */ Iterator End(void); /** * Get a ConstIterator that points past-the-end of the container. @@ -538,15 +538,15 @@ class ITK_EXPORT List */ void Erase(Iterator begin, Iterator end); - protected: +protected: /** Constructor */ List(); /** Destructor */ - ~List(){}; + ~List() {}; /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: List(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented /** The internal std::vector object container */ diff --git a/Code/Common/otbList.txx b/Code/Common/otbList.txx index 871cfcab505487d414dc79ffb35b83e567ceebcf..642fe209d0e6128b2dfa433a548d4156e4930bf9 100644 --- a/Code/Common/otbList.txx +++ b/Code/Common/otbList.txx @@ -22,110 +22,110 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TObject> - List<TObject> - ::List() - {} - /** - * Set the minimum capacity of the vector. - * \param size Size of the vector to reserve. - */ - template <class TObject> - void - List<TObject> - ::Reserve(unsigned int size) - { - m_InternalContainer.reserve(size); - } - /** - * Get the capacity of the vector. - * \return The capacity of the vector. - */ - template <class TObject> - unsigned int - List<TObject> - ::Capacity(void) - { - return m_InternalContainer.capacity(); - } - /** - * Get the number of elements in the vector. - * \return The number of elements in the vector. - */ - template <class TObject> - unsigned int - List<TObject> - ::Size(void) - { - return m_InternalContainer.size(); - } - /** - * Resize the maximal list capacity. - * \param size The new maximal size of the list. - */ - template <class TObject> - void - List<TObject> - ::Resize(unsigned int size) - { - m_InternalContainer.resize(size); - } - /** - * Append an element to the list. - * \param element Pointer to the element to append. - */ - template <class TObject> - void - List<TObject> - ::PushBack(const ObjectType* element) - { - m_InternalContainer.push_back(const_cast<ObjectType*>(element)); - } - /** - * Delete the last element to the list. - */ - template <class TObject> - void - List<TObject> - ::PopBack(void) - { - if( m_InternalContainer.size() > 0 ) - { - m_InternalContainer.pop_back(); - } - } - /** - * Set the nth element of the list. - * \param index The index where to put the element. - * \param element Pointer to the element to set. - */ - template <class TObject> - void - List<TObject> - ::SetNthElement(unsigned int index,const ObjectType * element) - { - m_InternalContainer[index]=const_cast<ObjectType*>(element); - } - /** - * Get the nth element of the list. - * \param index The index of the object to get. - * \return The pointer to the nth element of the list. - */ - template <class TObject> - typename List<TObject>::ObjectType * - List<TObject> - ::GetNthElement(unsigned int index) +/** + * Constructor + */ +template <class TObject> +List<TObject> +::List() +{} +/** + * Set the minimum capacity of the vector. + * \param size Size of the vector to reserve. + */ +template <class TObject> +void +List<TObject> +::Reserve(unsigned int size) +{ + m_InternalContainer.reserve(size); +} +/** + * Get the capacity of the vector. + * \return The capacity of the vector. + */ +template <class TObject> +unsigned int +List<TObject> +::Capacity(void) +{ + return m_InternalContainer.capacity(); +} +/** + * Get the number of elements in the vector. + * \return The number of elements in the vector. + */ +template <class TObject> +unsigned int +List<TObject> +::Size(void) +{ + return m_InternalContainer.size(); +} +/** + * Resize the maximal list capacity. + * \param size The new maximal size of the list. + */ +template <class TObject> +void +List<TObject> +::Resize(unsigned int size) +{ + m_InternalContainer.resize(size); +} +/** + * Append an element to the list. + * \param element Pointer to the element to append. + */ +template <class TObject> +void +List<TObject> +::PushBack(const ObjectType* element) +{ + m_InternalContainer.push_back(const_cast<ObjectType*>(element)); +} +/** + * Delete the last element to the list. + */ +template <class TObject> +void +List<TObject> +::PopBack(void) +{ + if ( m_InternalContainer.size() > 0 ) { - return m_InternalContainer[index].GetPointer(); + m_InternalContainer.pop_back(); } - /** - * Get the nth element of the const list. - * \param index The index of the object to get. - * \return The pointer to the nth element of the list. - */ +} +/** + * Set the nth element of the list. + * \param index The index where to put the element. + * \param element Pointer to the element to set. + */ +template <class TObject> +void +List<TObject> +::SetNthElement(unsigned int index,const ObjectType * element) +{ + m_InternalContainer[index]=const_cast<ObjectType*>(element); +} +/** + * Get the nth element of the list. + * \param index The index of the object to get. + * \return The pointer to the nth element of the list. + */ +template <class TObject> +typename List<TObject>::ObjectType * +List<TObject> +::GetNthElement(unsigned int index) +{ + return m_InternalContainer[index].GetPointer(); +} +/** + * Get the nth element of the const list. + * \param index The index of the object to get. + * \return The pointer to the nth element of the list. + */ /* template <class TObject> typename const List<TObject>::ObjectType * List<TObject> @@ -137,13 +137,13 @@ namespace otb * Return the first element of the list. * \return The first element of the list. */ - template <class TObject> - typename List<TObject>::ObjectType * - List<TObject> - ::Front(void) - { - return m_InternalContainer.front().GetPointer(); - } +template <class TObject> +typename List<TObject>::ObjectType * +List<TObject> +::Front(void) +{ + return m_InternalContainer.front().GetPointer(); +} /** * Return the first element of the const list. * \return The first element of the list. @@ -155,21 +155,21 @@ namespace otb { return m_InternalContainer.front().GetPointer(); }*/ - /** - * Return the last element of the list. - * \return The last element of the list. - */ - template <class TObject> - typename List<TObject>::ObjectType * - List<TObject> - ::Back(void) - { - return m_InternalContainer.back().GetPointer(); - } - /** - * Return the last element of the const list. - * \return The last element of the list. - */ +/** + * Return the last element of the list. + * \return The last element of the list. + */ +template <class TObject> +typename List<TObject>::ObjectType * +List<TObject> +::Back(void) +{ + return m_InternalContainer.back().GetPointer(); +} +/** + * Return the last element of the const list. + * \return The last element of the list. + */ /* template <class TObject> typename const List<TObject>::ObjectType * List<TObject> @@ -177,155 +177,155 @@ namespace otb { return m_InternalContainer.back().GetPointer(); }*/ - /** - * Erase the nth element in the list. - * \param index The index of the element to erase. - */ - template <class TObject> - void - List<TObject> - ::Erase(unsigned int index) - { - m_InternalContainer.erase(m_InternalContainer.begin()+index); - } - /** - * Clear the object list. - */ - template <class TObject> - void - List<TObject> - ::Clear(void) - { - m_InternalContainer.clear(); - } +/** + * Erase the nth element in the list. + * \param index The index of the element to erase. + */ +template <class TObject> +void +List<TObject> +::Erase(unsigned int index) +{ + m_InternalContainer.erase(m_InternalContainer.begin()+index); +} +/** + * Clear the object list. + */ +template <class TObject> +void +List<TObject> +::Clear(void) +{ + m_InternalContainer.clear(); +} - /** - * Get an Iterator that points to the beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::Iterator - List<TObject> - ::Begin(void) - { - Iterator iter(m_InternalContainer.begin()); - return iter; - } - /** - * Get a ConstIterator that points to the beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ConstIterator - List<TObject> - ::Begin(void) const - { - ConstIterator iter(m_InternalContainer.begin()); - return iter; - } - /** - * Get a ReverseIterator that points to the reverse beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ReverseIterator - List<TObject> - :: ReverseBegin(void) - { - ReverseIterator iter(m_InternalContainer.rbegin()); - return iter; - } - /** - * Get a ReverseConstIterator that points to the reverse beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ReverseConstIterator - List<TObject> - ::ReverseBegin(void) const - { - ReverseConstIterator iter(m_InternalContainer.rbegin()); - return iter; - } - /** - * Get an Iterator that points past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::Iterator - List<TObject> - :: End(void) - { - Iterator iter(m_InternalContainer.end()); - return iter; - } - /** - * Get a ConstIterator that points past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ConstIterator - List<TObject> - ::End(void) const - { - ConstIterator iter(m_InternalContainer.end()); - return iter; - } - /** - * Get a ReverseIterator that points to the reverse past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ReverseIterator - List<TObject> - ::ReverseEnd(void) - { - ReverseIterator iter(m_InternalContainer.rend()); - return iter; - } - /** - * Get a ReverseConstIterator that points to the reverse past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename List<TObject>::ReverseConstIterator - List<TObject> - ::ReverseEnd(void) const - { - ReverseConstIterator iter(m_InternalContainer.rend()); - return iter; - } - /** - * Erase elements from begin to last. - * \param begin Iterator pointing on first object to erase. - * \param end Iterator pointing past the last object to erase. - */ - template <class TObject> - void - List<TObject> - ::Erase(Iterator begin, Iterator end) - { - m_InternalContainer.erase(begin.GetIter(),end.GetIter()); - } - /**PrintSelf method */ - template <class TObject> - void - List<TObject> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "Size: " << m_InternalContainer.size() << std::endl; - os << indent << "List contains : " << std::endl; - ConstIterator iter = this->Begin(); - while(iter!=this->End()) +/** + * Get an Iterator that points to the beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::Iterator +List<TObject> +::Begin(void) +{ + Iterator iter(m_InternalContainer.begin()); + return iter; +} +/** + * Get a ConstIterator that points to the beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ConstIterator +List<TObject> +::Begin(void) const +{ + ConstIterator iter(m_InternalContainer.begin()); + return iter; +} +/** + * Get a ReverseIterator that points to the reverse beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ReverseIterator +List<TObject> +:: ReverseBegin(void) +{ + ReverseIterator iter(m_InternalContainer.rbegin()); + return iter; +} +/** + * Get a ReverseConstIterator that points to the reverse beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ReverseConstIterator +List<TObject> +::ReverseBegin(void) const +{ + ReverseConstIterator iter(m_InternalContainer.rbegin()); + return iter; +} +/** + * Get an Iterator that points past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::Iterator +List<TObject> +:: End(void) +{ + Iterator iter(m_InternalContainer.end()); + return iter; +} +/** + * Get a ConstIterator that points past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ConstIterator +List<TObject> +::End(void) const +{ + ConstIterator iter(m_InternalContainer.end()); + return iter; +} +/** + * Get a ReverseIterator that points to the reverse past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ReverseIterator +List<TObject> +::ReverseEnd(void) +{ + ReverseIterator iter(m_InternalContainer.rend()); + return iter; +} +/** + * Get a ReverseConstIterator that points to the reverse past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename List<TObject>::ReverseConstIterator +List<TObject> +::ReverseEnd(void) const +{ + ReverseConstIterator iter(m_InternalContainer.rend()); + return iter; +} +/** + * Erase elements from begin to last. + * \param begin Iterator pointing on first object to erase. + * \param end Iterator pointing past the last object to erase. + */ +template <class TObject> +void +List<TObject> +::Erase(Iterator begin, Iterator end) +{ + m_InternalContainer.erase(begin.GetIter(),end.GetIter()); +} +/**PrintSelf method */ +template <class TObject> +void +List<TObject> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Size: " << m_InternalContainer.size() << std::endl; + os << indent << "List contains : " << std::endl; + ConstIterator iter = this->Begin(); + while (iter!=this->End()) { - os << indent.GetNextIndent() << iter.Get().GetPointer() << std::endl; - os << indent.GetNextIndent() << iter.Get() << std::endl; + os << indent.GetNextIndent() << iter.Get().GetPointer() << std::endl; + os << indent.GetNextIndent() << iter.Get() << std::endl; // iter.Get()->PrintSelf(os,indent.GetNextIndent()); // iter.Get()->Print(os,indent.GetNextIndent()); - ++iter; - } + ++iter; } +} } // end namespace otb #endif diff --git a/Code/Common/otbMacro.h b/Code/Common/otbMacro.h old mode 100755 new mode 100644 index 13e4858ec3828a2779d59aebb1f25341e64b8540..e226ccbd2cdf7566197201b85ff438162922a136 --- a/Code/Common/otbMacro.h +++ b/Code/Common/otbMacro.h @@ -59,17 +59,17 @@ #if defined(OTB_LEAN_AND_MEAN) || defined(__BORLANDC__) #define otbGenericMsgDebugMacro(x) #else - #ifndef NDEBUG - #define otbGenericMsgDebugMacro(x) \ +#ifndef NDEBUG +#define otbGenericMsgDebugMacro(x) \ { \ if ( ::itk::Object::GetGlobalWarningDisplay()) \ { ::itk::OStringStream itkmsg; \ itkmsg << " Generic Msg Debug: " x << "\n"; \ ::itk::OutputWindowDisplayDebugText(itkmsg.str().c_str());} \ } - #else - #define otbGenericMsgDebugMacro(x) - #endif +#else +#define otbGenericMsgDebugMacro(x) +#endif #endif #define otbGenericMsgTestingMacro(x) \ @@ -81,15 +81,15 @@ #if defined(OTB_LEAN_AND_MEAN) || defined(__BORLANDC__) #define otbMsgDevMacro(x) #else - #ifdef OTB_SHOW_ALL_MSG_DEBUG - #define otbMsgDevMacro(x) \ +#ifdef OTB_SHOW_ALL_MSG_DEBUG +#define otbMsgDevMacro(x) \ { { ::itk::OStringStream itkmsg; \ itkmsg << " Msg Dev: " x << "\n"; \ ::itk::OutputWindowDisplayDebugText(itkmsg.str().c_str());} \ } - #else - #define otbMsgDevMacro(x) - #endif +#else +#define otbMsgDevMacro(x) +#endif #endif @@ -301,15 +301,18 @@ private: #else namespace StringStreamDetail { - class Cleanup +class Cleanup +{ +public: + Cleanup(std::strstream& ostr): m_StrStream(ostr) {} + ~Cleanup() { - public: - Cleanup(std::strstream& ostr): m_StrStream(ostr) {} - ~Cleanup() { m_StrStream.rdbuf()->freeze(0); } - static void IgnoreUnusedVariable(const Cleanup&) {} - protected: - std::strstream& m_StrStream; - }; + m_StrStream.rdbuf()->freeze(0); + } + static void IgnoreUnusedVariable(const Cleanup&) {} +protected: + std::strstream& m_StrStream; +}; }//namespace OStringStreamDetail class StringStream: public std::strstream @@ -318,13 +321,13 @@ public: typedef std::strstream Superclass; StringStream() {} std::string str() - { - StringStreamDetail::Cleanup cleanup(*this); - StringStreamDetail::Cleanup::IgnoreUnusedVariable(cleanup); - int pcount = this->pcount(); - const char* ptr = this->Superclass::str(); - return std::string(ptr?ptr:"", pcount); - } + { + StringStreamDetail::Cleanup cleanup(*this); + StringStreamDetail::Cleanup::IgnoreUnusedVariable(cleanup); + int pcount = this->pcount(); + const char* ptr = this->Superclass::str(); + return std::string(ptr?ptr:"", pcount); + } private: StringStream(const StringStream&); void operator=(const StringStream&); diff --git a/Code/Common/otbMirrorBoundaryCondition.h b/Code/Common/otbMirrorBoundaryCondition.h index 2c6d594b75fd4ee1e0236e1a670f77e478964ab9..fd3b68ee53c4ef89b5d3f55467d150b5e3017499 100644 --- a/Code/Common/otbMirrorBoundaryCondition.h +++ b/Code/Common/otbMirrorBoundaryCondition.h @@ -40,7 +40,7 @@ namespace otb */ template<class TImage> class ITK_EXPORT MirrorBoundaryCondition - : public itk::ImageBoundaryCondition<TImage> + : public itk::ImageBoundaryCondition<TImage> { public: /** Standard class typedefs. */ @@ -55,7 +55,7 @@ public: typedef typename Superclass::NeighborhoodType NeighborhoodType; typedef typename Superclass::NeighborhoodAccessorFunctorType - NeighborhoodAccessorFunctorType; + NeighborhoodAccessorFunctorType; /** Extract information from the image type. */ itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); @@ -72,10 +72,10 @@ public: /** Computes and returns the appropriate pixel value from * neighborhood iterator data, using the functor. */ virtual PixelType operator()( - const OffsetType& point_index, - const OffsetType& boundary_offset, - const NeighborhoodType *data, - const NeighborhoodAccessorFunctorType &neighborhoodAccessorFunctor) const; + const OffsetType& point_index, + const OffsetType& boundary_offset, + const NeighborhoodType *data, + const NeighborhoodAccessorFunctorType &neighborhoodAccessorFunctor) const; }; } // end namespace itk diff --git a/Code/Common/otbMirrorBoundaryCondition.txx b/Code/Common/otbMirrorBoundaryCondition.txx index 24a69515987204202e8af1423f0dabf00f8c87b3..1f7ed88bf92434b54ac9f4db0788cfad603946e7 100644 --- a/Code/Common/otbMirrorBoundaryCondition.txx +++ b/Code/Common/otbMirrorBoundaryCondition.txx @@ -32,7 +32,7 @@ MirrorBoundaryCondition<TImage> { typedef typename OffsetType::OffsetValueType OffsetValueType; const itk::ConstNeighborhoodIterator<TImage> * iterator - = dynamic_cast<const itk::ConstNeighborhoodIterator<TImage> *>(data); + = dynamic_cast<const itk::ConstNeighborhoodIterator<TImage> *>(data); typename TImage::InternalPixelType *ptr; int linear_index = 0; unsigned int i; @@ -41,9 +41,9 @@ MirrorBoundaryCondition<TImage> // Return the value of the pixel at the closest boundary point. for (i = 0; i < ImageDimension; ++i) - { + { linear_index += (point_index[i] + boundary_offset[i]) * data->GetStride(i); - } + } ptr =data->operator[](linear_index); // Wrap the pointer around the image in the necessary dimensions. If we have @@ -53,25 +53,25 @@ MirrorBoundaryCondition<TImage> // These are the step sizes for increments in each dimension of the image. const typename TImage::OffsetValueType * offset_table - = iterator->GetImagePointer()->GetOffsetTable(); + = iterator->GetImagePointer()->GetOffsetTable(); for (i = 0; i < ImageDimension; ++i) - { + { if (boundary_offset[i] != 0) - { - // If the neighborhood overlaps on the low edge, then wrap from the - // high edge of the image. - if (point_index[i] < static_cast<OffsetValueType>(iterator->GetRadius(i))) - { - ptr += boundary_offset[i] * offset_table[i]; - } - else // wrap from the low side of the image { - ptr -= boundary_offset[i] * offset_table[i]; - } + // If the neighborhood overlaps on the low edge, then wrap from the + // high edge of the image. + if (point_index[i] < static_cast<OffsetValueType>(iterator->GetRadius(i))) + { + ptr += boundary_offset[i] * offset_table[i]; + } + else // wrap from the low side of the image + { + ptr -= boundary_offset[i] * offset_table[i]; } } + } return *reinterpret_cast<PixelType *>(ptr); } @@ -85,7 +85,7 @@ MirrorBoundaryCondition<TImage> { typedef typename OffsetType::OffsetValueType OffsetValueType; const itk::ConstNeighborhoodIterator<TImage> * iterator - = dynamic_cast<const itk::ConstNeighborhoodIterator<TImage> *>(data); + = dynamic_cast<const itk::ConstNeighborhoodIterator<TImage> *>(data); typename TImage::InternalPixelType *ptr; int linear_index = 0; unsigned int i; @@ -97,9 +97,9 @@ MirrorBoundaryCondition<TImage> // Return the value of the pixel at the closest boundary point. for (i = 0; i < ImageDimension; ++i) - { + { linear_index += (point_index[i] + boundary_offset[i]) * data->GetStride(i); - } + } ptr = data->operator[](linear_index); // Wrap the pointer around the image in the necessary dimensions. If we have @@ -109,25 +109,25 @@ MirrorBoundaryCondition<TImage> // These are the step sizes for increments in each dimension of the image. const typename TImage::OffsetValueType * offset_table - = iterator->GetImagePointer()->GetOffsetTable(); + = iterator->GetImagePointer()->GetOffsetTable(); for (i = 0; i < ImageDimension; ++i) - { + { if (boundary_offset[i] != 0) - { - // If the neighborhood overlaps on the low edge, then wrap from the - // high edge of the image. - if (point_index[i] < static_cast<OffsetValueType>(iterator->GetRadius(i))) - { - ptr += boundary_offset[i] * offset_table[i]; - } - else // wrap from the low side of the image { - ptr -= boundary_offset[i] * offset_table[i]; - } + // If the neighborhood overlaps on the low edge, then wrap from the + // high edge of the image. + if (point_index[i] < static_cast<OffsetValueType>(iterator->GetRadius(i))) + { + ptr += boundary_offset[i] * offset_table[i]; + } + else // wrap from the low side of the image + { + ptr -= boundary_offset[i] * offset_table[i]; } } + } return neighborhoodAccessorFunctor.Get(ptr); } diff --git a/Code/Common/otbMultiChannelExtractROI.h b/Code/Common/otbMultiChannelExtractROI.h index 39617fe18ec9d69fdcba577488ef4f4b4e40173f..a7c25a4e8abf3c4e144dc27da8738828787a0ade 100644 --- a/Code/Common/otbMultiChannelExtractROI.h +++ b/Code/Common/otbMultiChannelExtractROI.h @@ -39,7 +39,7 @@ namespace otb */ template <class TInputPixelType, class TOutputPixelType> class ITK_EXPORT MultiChannelExtractROI: - public ExtractROIBase< VectorImage<TInputPixelType,2> , VectorImage<TOutputPixelType,2> > + public ExtractROIBase< VectorImage<TInputPixelType,2> , VectorImage<TOutputPixelType,2> > { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbMultiChannelExtractROI.txx b/Code/Common/otbMultiChannelExtractROI.txx index 068550152c6766f8fc21406236bf38bbd5f6f85d..3ca9687efc2d1840c6780d92bbb6034addeb46d5 100644 --- a/Code/Common/otbMultiChannelExtractROI.txx +++ b/Code/Common/otbMultiChannelExtractROI.txx @@ -36,10 +36,10 @@ namespace otb template<class TInputPixelType, class TOutputPixelType> MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::MultiChannelExtractROI() : - ExtractROIBase< VectorImage<TInputPixelType,2> , VectorImage<TOutputPixelType,2> >(), - m_FirstChannel(0), - m_LastChannel(0), - m_ChannelsKind(0) + ExtractROIBase< VectorImage<TInputPixelType,2> , VectorImage<TOutputPixelType,2> >(), + m_FirstChannel(0), + m_LastChannel(0), + m_ChannelsKind(0) { ClearChannels(); } @@ -53,15 +53,15 @@ void MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::SetChannel(unsigned int channel) { - if(m_ChannelsKind==1) - { - itkExceptionMacro(<< "m_Channels already set using channels interval."); - } + if (m_ChannelsKind==1) + { + itkExceptionMacro(<< "m_Channels already set using channels interval."); + } m_Channels.push_back( channel ); - if(m_ChannelsKind==0) - { - m_ChannelsKind = 2; - } + if (m_ChannelsKind==0) + { + m_ChannelsKind = 2; + } this->Modified(); } @@ -71,16 +71,16 @@ void MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::SetFirstChannel(unsigned int id) { - if(m_ChannelsKind==2) - { - itkExceptionMacro(<< "m_Channels already set using SetChannels method."); - } + if (m_ChannelsKind==2) + { + itkExceptionMacro(<< "m_Channels already set using SetChannels method."); + } m_FirstChannel = id; - if(m_ChannelsKind==0) - { - m_ChannelsKind = 1; - } - this->Modified(); + if (m_ChannelsKind==0) + { + m_ChannelsKind = 1; + } + this->Modified(); } @@ -90,15 +90,15 @@ void MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::SetLastChannel(unsigned int id) { - if(m_ChannelsKind==2) - { - itkExceptionMacro(<< "m_Channels already set using SetChannels method."); - } + if (m_ChannelsKind==2) + { + itkExceptionMacro(<< "m_Channels already set using SetChannels method."); + } m_LastChannel = id; - if(m_ChannelsKind==0) - { - m_ChannelsKind = 1; - } + if (m_ChannelsKind==0) + { + m_ChannelsKind = 1; + } this->Modified(); } @@ -141,40 +141,40 @@ MultiChannelExtractROI<TInputPixelType,TOutputPixelType> // The following conditions can be gathered but we'd loose in comprehension m_ChannelsWorks.clear(); // First passage in the method: - if( m_Channels.empty() == true ) - { - // - User SetFirst/LastChannel() - if( m_ChannelsKind == 1) + if ( m_Channels.empty() == true ) { - this->SetChannelsWorkWithLimits(); - } - else - { - // - User called SetChannels() - if( m_Channels.empty() == true && m_ChannelsKind == 2) + // - User SetFirst/LastChannel() + if ( m_ChannelsKind == 1) + { + this->SetChannelsWorkWithLimits(); + } + else + { + // - User called SetChannels() + if ( m_Channels.empty() == true && m_ChannelsKind == 2) { m_ChannelsWorks = m_Channels; } - } } + } // Second passage in the method: Update already donne else - { - // - User SetFirst/LastChannel() - if( m_ChannelsKind == 1) { - m_Channels.clear(); - this->SetChannelsWorkWithLimits(); - } - else - { - // - User called SetChannels() - if( m_ChannelsKind == 2) + // - User SetFirst/LastChannel() + if ( m_ChannelsKind == 1) + { + m_Channels.clear(); + this->SetChannelsWorkWithLimits(); + } + else + { + // - User called SetChannels() + if ( m_ChannelsKind == 2) { m_ChannelsWorks = m_Channels; } - } } + } } template<class TInputPixelType, class TOutputPixelType> @@ -183,22 +183,22 @@ MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::SetChannelsWorkWithLimits() { if ((m_FirstChannel == 0) || (m_LastChannel == 0)) - { - itkExceptionMacro(<< "otb::ExtractImageFilter::GenerateOutputInformation " - << "Channels must reside into [1...] " - << typeid(itk::ImageBase<InputImageDimension>*).name() ); - } + { + itkExceptionMacro(<< "otb::ExtractImageFilter::GenerateOutputInformation " + << "Channels must reside into [1...] " + << typeid(itk::ImageBase<InputImageDimension>*).name() ); + } if ( m_FirstChannel > m_LastChannel ) - { - itkExceptionMacro(<< "otb::ExtractImageFilter::GenerateOutputInformation " - << "FirstChannel is greater than LastChannel" - << typeid(itk::ImageBase<InputImageDimension>*).name() ); - } + { + itkExceptionMacro(<< "otb::ExtractImageFilter::GenerateOutputInformation " + << "FirstChannel is greater than LastChannel" + << typeid(itk::ImageBase<InputImageDimension>*).name() ); + } - for( unsigned int channel = m_FirstChannel; channel <= m_LastChannel; channel ++ ) - { - m_ChannelsWorks.push_back(channel); - } + for ( unsigned int channel = m_FirstChannel; channel <= m_LastChannel; channel ++ ) + { + m_ChannelsWorks.push_back(channel); + } m_Channels = m_ChannelsWorks; } @@ -218,7 +218,7 @@ void MultiChannelExtractROI<TInputPixelType,TOutputPixelType> ::GenerateOutputInformation() { - // Call to the superclass implementation + // Call to the superclass implementation Superclass::GenerateOutputInformation(); this->ChannelsReInitialization(); @@ -227,41 +227,41 @@ MultiChannelExtractROI<TInputPixelType,TOutputPixelType> unsigned int nbComponentsPerPixel = inputPtr->GetNumberOfComponentsPerPixel(); - if( m_ChannelsKind != 0 ) - { - // Test if the asked channels index exists in the input image - ChannelsType m_BadChannels; - m_BadChannels.clear(); - for(unsigned int i=0; i < m_ChannelsWorks.size(); i++) + if ( m_ChannelsKind != 0 ) { - if( ( m_ChannelsWorks[i] < 1 )||(m_ChannelsWorks[i] > nbComponentsPerPixel) ) + // Test if the asked channels index exists in the input image + ChannelsType m_BadChannels; + m_BadChannels.clear(); + for (unsigned int i=0; i < m_ChannelsWorks.size(); i++) + { + if ( ( m_ChannelsWorks[i] < 1 )||(m_ChannelsWorks[i] > nbComponentsPerPixel) ) { bool isInsideBadChannels = false; - for(unsigned int j=0; j < m_BadChannels.size(); j++) - { - if ( m_BadChannels[j]==m_ChannelsWorks[i] ) - isInsideBadChannels = true; + for (unsigned int j=0; j < m_BadChannels.size(); j++) + { + if ( m_BadChannels[j]==m_ChannelsWorks[i] ) + isInsideBadChannels = true; - } - if( !isInsideBadChannels) - m_BadChannels.push_back(m_ChannelsWorks[i]); + } + if ( !isInsideBadChannels) + m_BadChannels.push_back(m_ChannelsWorks[i]); } - } - if( m_BadChannels.empty() == false ) - { - itk::OStringStream oss; - oss << "otb::ExtractImageFilter::GenerateOutputInformation : "; - oss << "Channel(s) [ "; - for(unsigned int i=0; i < m_BadChannels.size(); i++) + } + if ( m_BadChannels.empty() == false ) + { + itk::OStringStream oss; + oss << "otb::ExtractImageFilter::GenerateOutputInformation : "; + oss << "Channel(s) [ "; + for (unsigned int i=0; i < m_BadChannels.size(); i++) { oss << m_BadChannels[i] << " "; } - oss << "] not authorized."; - oss << " Each channel index has to be in [1," << nbComponentsPerPixel << "]."; - itkExceptionMacro(<< oss.str().c_str()); - } - nbComponentsPerPixel = m_ChannelsWorks.size(); + oss << "] not authorized."; + oss << " Each channel index has to be in [1," << nbComponentsPerPixel << "]."; + itkExceptionMacro(<< oss.str().c_str()); } + nbComponentsPerPixel = m_ChannelsWorks.size(); + } // initialize the number of channels of the output image outputPtr->SetNumberOfComponentsPerPixel( nbComponentsPerPixel ); @@ -299,42 +299,42 @@ MultiChannelExtractROI<TInputPixelType,TOutputPixelType> // if default behaviour if ( m_ChannelsKind == 0 ) { - // walk the output region, and sample the input image - while( !outIt.IsAtEnd() ) - { - outIt.Set( inIt.Get() ); - ++outIt; - ++inIt; - progress.CompletedPixel(); - } + // walk the output region, and sample the input image + while ( !outIt.IsAtEnd() ) + { + outIt.Set( inIt.Get() ); + ++outIt; + ++inIt; + progress.CompletedPixel(); + } } // Specific behaviour else - { - // for each channel to process - unsigned int channelIn(0); - unsigned int channelOut(0); - unsigned int nbChannels(0); + { + // for each channel to process + unsigned int channelIn(0); + unsigned int channelOut(0); + unsigned int nbChannels(0); - InputImagePixelType pixelInput; - while( !outIt.IsAtEnd() ) - { - OutputImagePixelType pixelOutput; - pixelOutput.Reserve( outputPtr->GetVectorLength() ); - pixelInput = inIt.Get(); - channelOut = 0; - for ( nbChannels = 0; nbChannels < m_ChannelsWorks.size(); nbChannels++) + InputImagePixelType pixelInput; + while ( !outIt.IsAtEnd() ) + { + OutputImagePixelType pixelOutput; + pixelOutput.Reserve( outputPtr->GetVectorLength() ); + pixelInput = inIt.Get(); + channelOut = 0; + for ( nbChannels = 0; nbChannels < m_ChannelsWorks.size(); nbChannels++) { channelIn = m_ChannelsWorks[nbChannels] - 1; pixelOutput[channelOut] = static_cast<OutputValueType>(pixelInput[channelIn]); channelOut++; } - outIt.Set( pixelOutput ); - ++outIt; - ++inIt; - progress.CompletedPixel(); - } + outIt.Set( pixelOutput ); + ++outIt; + ++inIt; + progress.CompletedPixel(); } + } } diff --git a/Code/Common/otbMultiToMonoChannelExtractROI.h b/Code/Common/otbMultiToMonoChannelExtractROI.h index c1be38728e8c2ab660089863522f0d31e71d3767..de5b3d5982a6505059ca7db950e7f00c9ebbd266 100644 --- a/Code/Common/otbMultiToMonoChannelExtractROI.h +++ b/Code/Common/otbMultiToMonoChannelExtractROI.h @@ -39,7 +39,7 @@ namespace otb template <class TInputPixelType, class TOutputPixelType> class ITK_EXPORT MultiToMonoChannelExtractROI: // public ExtractROIBase< itk::VectorImage<TInputPixelType,2> , itk::Image<TOutputPixelType,2> > - public ExtractROIBase< VectorImage<TInputPixelType,2> , Image<TOutputPixelType,2> > + public ExtractROIBase< VectorImage<TInputPixelType,2> , Image<TOutputPixelType,2> > { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbMultiToMonoChannelExtractROI.txx b/Code/Common/otbMultiToMonoChannelExtractROI.txx index 2fd8a86fdd508d78aee2111435dd9210e36a4f4b..12f64bcdb8f541d5987727abaaecd9f2556c5d79 100644 --- a/Code/Common/otbMultiToMonoChannelExtractROI.txx +++ b/Code/Common/otbMultiToMonoChannelExtractROI.txx @@ -29,7 +29,7 @@ namespace otb template<class TInputPixelType, class TOutputPixelType> MultiToMonoChannelExtractROI<TInputPixelType,TOutputPixelType> ::MultiToMonoChannelExtractROI() : ExtractROIBase< VectorImage<TInputPixelType,2> , Image<TOutputPixelType,2> >(), - m_Channel(1) + m_Channel(1) { } @@ -60,17 +60,17 @@ void MultiToMonoChannelExtractROI<TInputPixelType,TOutputPixelType> ::GenerateOutputInformation() { - typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); - // Bounds checking for the channel to process - if ( (m_Channel <= 0) || (m_Channel > inputPtr->GetVectorLength() ) ) - { - itkExceptionMacro(<< "otb::MultiToMonoChannelExtractROI::GenerateOutputInformation " + typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); + // Bounds checking for the channel to process + if ( (m_Channel <= 0) || (m_Channel > inputPtr->GetVectorLength() ) ) + { + itkExceptionMacro(<< "otb::MultiToMonoChannelExtractROI::GenerateOutputInformation " << "The selected channel must in the range [1;"<<inputPtr->GetVectorLength()<<"] " << typeid(itk::ImageBase<InputImageDimension>*).name() ); - } + } - // Calling the superclass method - Superclass::GenerateOutputInformation(); + // Calling the superclass method + Superclass::GenerateOutputInformation(); } @@ -104,15 +104,15 @@ MultiToMonoChannelExtractROI<TInputPixelType,TOutputPixelType> unsigned int channelIn(m_Channel-1); InputImagePixelType pixelInput; - while( !outIt.IsAtEnd() ) + while ( !outIt.IsAtEnd() ) { - OutputImagePixelType pixelOutput; - pixelInput = inIt.Get(); - pixelOutput = static_cast<OutputValueType>(pixelInput[channelIn]); - outIt.Set( pixelOutput ); - ++outIt; - ++inIt; - progress.CompletedPixel(); + OutputImagePixelType pixelOutput; + pixelInput = inIt.Get(); + pixelOutput = static_cast<OutputValueType>(pixelInput[channelIn]); + outIt.Set( pixelOutput ); + ++outIt; + ++inIt; + progress.CompletedPixel(); } } diff --git a/Code/Common/otbObjectList.h b/Code/Common/otbObjectList.h index d35314953b57bc179300fec05b3c48ba3c81dca3..66366d4d0a642b92e4e8fe8c7bd98794df6700e7 100644 --- a/Code/Common/otbObjectList.h +++ b/Code/Common/otbObjectList.h @@ -128,36 +128,41 @@ public: /** typedef of the internal iterator */ typedef typename InternalContainerType::iterator InternalIteratorType; /** Constructor */ - Iterator(){}; + Iterator() {}; /** Constructor with iternal iterator parameter */ - Iterator(InternalIteratorType iter){ + Iterator(InternalIteratorType iter) + { m_Iter=iter; }; /** * Get the current object. * \return The current object pointed by the iterator. */ - ObjectPointerType Get(void){ + ObjectPointerType Get(void) + { return (*m_Iter); }; /** * Increment. */ - Iterator& operator++(){ + Iterator& operator++() + { ++m_Iter; return *this; }; /** * Decrement. */ - Iterator& operator--(){ + Iterator& operator--() + { --m_Iter; return *this; }; /** * Add */ - Iterator operator+(int i){ + Iterator operator+(int i) + { Iterator lIter(m_Iter+i); return lIter; }; @@ -165,20 +170,23 @@ public: /** * Remove */ - Iterator operator-(int i){ + Iterator operator-(int i) + { Iterator lIter(m_Iter-i); return lIter; }; /** * Difference comparison operator. */ - bool operator!=(const Iterator &it){ + bool operator!=(const Iterator &it) + { return (m_Iter != it.m_Iter); }; /** * Equality comparison operator. */ - bool operator==(const Iterator &it){ + bool operator==(const Iterator &it) + { return (m_Iter == it.m_Iter); }; /** @@ -192,7 +200,8 @@ public: /** * Copy operator. */ - Iterator(const Iterator &it){ + Iterator(const Iterator &it) + { m_Iter=it.m_Iter; }; @@ -202,7 +211,7 @@ public: InternalIteratorType & GetIter(void) { return(m_Iter); - } + } private: // Internal iterator. InternalIteratorType m_Iter; @@ -218,55 +227,63 @@ public: /** typedef of the internal iterator */ typedef typename InternalContainerType::const_iterator InternalConstIteratorType; /** Constructor */ - ConstIterator(){}; + ConstIterator() {}; /** Constructor with iternal iterator parameter */ - ConstIterator(InternalConstIteratorType iter) { + ConstIterator(InternalConstIteratorType iter) + { m_Iter=iter; }; /** * Get the current object. * \return The current object pointed by the iterator. */ - ObjectPointerType Get(void) { + ObjectPointerType Get(void) + { return (*m_Iter); }; /** * Increment. */ - ConstIterator& operator++() { + ConstIterator& operator++() + { ++m_Iter; return *this; }; /** * Decrement. */ - ConstIterator& operator--() { + ConstIterator& operator--() + { --m_Iter; return *this; }; /** * Difference comparison operator. */ - bool operator!=(const ConstIterator &it) { + bool operator!=(const ConstIterator &it) + { return (m_Iter != it.m_Iter); }; /** * Equality comparison operator. */ - bool operator==(const ConstIterator &it) { + bool operator==(const ConstIterator &it) + { return (m_Iter == it.m_Iter); }; /** * Instantiation operator. */ - ConstIterator& operator=(const ConstIterator &it) { + ConstIterator& operator=(const ConstIterator &it) + { m_Iter = it.m_Iter; return *this; }; /** * Instantiation operator. */ - ConstIterator& operator=(const Iterator &it) { + ConstIterator& operator=(const Iterator &it) + { m_Iter = it.m_Iter; return *this; }; @@ -280,7 +297,8 @@ public: /** * Copy operator. */ - ConstIterator(const Iterator &it) { + ConstIterator(const Iterator &it) + { m_Iter=it.m_Iter; }; @@ -301,42 +319,48 @@ public: /** typedef of the internal iterator */ typedef typename InternalContainerType::reverse_iterator InternalReverseIteratorType; /** Constructor */ - ReverseIterator(){}; + ReverseIterator() {}; /** Constructor with iternal iterator parameter */ - ReverseIterator(InternalReverseIteratorType iter) { + ReverseIterator(InternalReverseIteratorType iter) + { m_Iter=iter; }; /** * Get the current object. * \return The current object pointed by the iterator. */ - ObjectPointerType Get(void) { + ObjectPointerType Get(void) + { return (*m_Iter); }; /** * Increment. */ - ReverseIterator& operator++() { + ReverseIterator& operator++() + { ++m_Iter; return *this; }; /** * Decrement. */ - ReverseIterator& operator--() { + ReverseIterator& operator--() + { --m_Iter; return *this; }; /** * Difference comparison operator. */ - bool operator!=(const ReverseIterator &it) { + bool operator!=(const ReverseIterator &it) + { return (m_Iter != it.m_Iter); }; /** * Equality comparison operator. */ - bool operator==(const ReverseIterator &it) { + bool operator==(const ReverseIterator &it) + { return (m_Iter == it.m_Iter); }; /** @@ -350,7 +374,8 @@ public: /** * Copy operator. */ - ReverseIterator(const ReverseIterator &it) { + ReverseIterator(const ReverseIterator &it) + { m_Iter=it.m_Iter; }; @@ -371,22 +396,25 @@ public: /** typedef of the internal iterator */ typedef typename InternalContainerType::reverse_iterator InternalReverseConstIteratorType; /** Constructor */ - ReverseConstIterator(){}; + ReverseConstIterator() {}; /** Constructor with iternal iterator parameter */ - ReverseConstIterator(InternalReverseConstIteratorType iter) { + ReverseConstIterator(InternalReverseConstIteratorType iter) + { m_Iter=iter; }; /** * Get the current object. * \return The current object pointed by the iterator. */ - ObjectPointerType Get(void) { + ObjectPointerType Get(void) + { return (*m_Iter); }; /** * Increment. */ - ReverseConstIterator& operator++() { + ReverseConstIterator& operator++() + { ++m_Iter; return *this; }; @@ -401,39 +429,45 @@ public: /** * Difference comparison operator. */ - bool operator!=(const ReverseConstIterator &it) { + bool operator!=(const ReverseConstIterator &it) + { return (m_Iter != it.m_Iter); }; /** * Equality comparison operator. */ - bool operator==(const ReverseConstIterator &it) { + bool operator==(const ReverseConstIterator &it) + { return (m_Iter == it.m_Iter); }; /** * Instantiation operator. */ - ReverseConstIterator& operator=(const ReverseConstIterator &it) { + ReverseConstIterator& operator=(const ReverseConstIterator &it) + { m_Iter = it.m_Iter; return *this; }; /** * Instantiation operator. */ - ReverseConstIterator& operator=(const ReverseIterator &it) { + ReverseConstIterator& operator=(const ReverseIterator &it) + { m_Iter = it.m_Iter; return *this; }; /** * Copy operator. */ - ReverseConstIterator(const ReverseConstIterator &it) { + ReverseConstIterator(const ReverseConstIterator &it) + { m_Iter=it.m_Iter; }; /** * Copy operator. */ - ReverseConstIterator(const ReverseIterator &it) { + ReverseConstIterator(const ReverseIterator &it) + { m_Iter=it.m_Iter; }; @@ -498,7 +532,7 @@ protected: /** Constructor */ ObjectList(); /** Destructor */ - ~ObjectList(){}; + ~ObjectList() {}; /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; diff --git a/Code/Common/otbObjectList.txx b/Code/Common/otbObjectList.txx index b0e585dab2ad74cf80a736457d245555ad74c18c..3d337bcd8c3aa2622daf44e722b0578e973202cd 100644 --- a/Code/Common/otbObjectList.txx +++ b/Code/Common/otbObjectList.txx @@ -23,280 +23,280 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TObject> - ObjectList<TObject> - ::ObjectList() - {} - /** - * Set the minimum capacity of the vector. - * \param size Size of the vector to reserve. - */ - template <class TObject> - void - ObjectList<TObject> - ::Reserve(unsigned int size) - { - m_InternalContainer.reserve(size); - } - /** - * Get the capacity of the vector. - * \return The capacity of the vector. - */ - template <class TObject> - unsigned int - ObjectList<TObject> - ::Capacity(void) const - { - return m_InternalContainer.capacity(); - } - /** - * Get the number of elements in the vector. - * \return The number of elements in the vector. - */ - template <class TObject> - unsigned int - ObjectList<TObject> - ::Size(void) const - { - return m_InternalContainer.size(); - } - /** - * Resize the maximal list capacity. - * \param size The new maximal size of the list. - */ - template <class TObject> - void - ObjectList<TObject> - ::Resize(unsigned int size) - { - m_InternalContainer.resize(size); - } - /** - * Append an element to the list. - * \param element Pointer to the element to append. - */ - template <class TObject> - void - ObjectList<TObject> - ::PushBack(ObjectType* element) - { - m_InternalContainer.push_back(element); - } - /** - * Set the nth element of the list. - * \param index The index where to put the element. - * \param element Pointer to the element to set. - */ - template <class TObject> - void - ObjectList<TObject> - ::SetNthElement(unsigned int index,ObjectPointerType element) +/** + * Constructor + */ +template <class TObject> +ObjectList<TObject> +::ObjectList() +{} +/** + * Set the minimum capacity of the vector. + * \param size Size of the vector to reserve. + */ +template <class TObject> +void +ObjectList<TObject> +::Reserve(unsigned int size) +{ + m_InternalContainer.reserve(size); +} +/** + * Get the capacity of the vector. + * \return The capacity of the vector. + */ +template <class TObject> +unsigned int +ObjectList<TObject> +::Capacity(void) const +{ + return m_InternalContainer.capacity(); +} +/** + * Get the number of elements in the vector. + * \return The number of elements in the vector. + */ +template <class TObject> +unsigned int +ObjectList<TObject> +::Size(void) const +{ + return m_InternalContainer.size(); +} +/** + * Resize the maximal list capacity. + * \param size The new maximal size of the list. + */ +template <class TObject> +void +ObjectList<TObject> +::Resize(unsigned int size) +{ + m_InternalContainer.resize(size); +} +/** + * Append an element to the list. + * \param element Pointer to the element to append. + */ +template <class TObject> +void +ObjectList<TObject> +::PushBack(ObjectType* element) +{ + m_InternalContainer.push_back(element); +} +/** + * Set the nth element of the list. + * \param index The index where to put the element. + * \param element Pointer to the element to set. + */ +template <class TObject> +void +ObjectList<TObject> +::SetNthElement(unsigned int index,ObjectPointerType element) +{ + if ( index >= m_InternalContainer.size() ) { - if( index >= m_InternalContainer.size() ) - { - itkExceptionMacro(<<"Impossible to SetNthElement with the index element "<<index<<"; this element don't exist, the size of the list is "<<m_InternalContainer.size()<<"." ); - } - m_InternalContainer[index]=element; + itkExceptionMacro(<<"Impossible to SetNthElement with the index element "<<index<<"; this element don't exist, the size of the list is "<<m_InternalContainer.size()<<"." ); } - /** - * Get the nth element of the list. - * \param index The index of the object to get. - * \return The pointer to the nth element of the list. - */ - template <class TObject> - typename ObjectList<TObject>::ObjectPointerType - ObjectList<TObject> - ::GetNthElement(unsigned int index) const + m_InternalContainer[index]=element; +} +/** + * Get the nth element of the list. + * \param index The index of the object to get. + * \return The pointer to the nth element of the list. + */ +template <class TObject> +typename ObjectList<TObject>::ObjectPointerType +ObjectList<TObject> +::GetNthElement(unsigned int index) const +{ + if ( index >= m_InternalContainer.size() ) { - if( index >= m_InternalContainer.size() ) - { - itkExceptionMacro(<<"Impossible to GetNthElement with the index element "<<index<<"; this element don't exist, the size of the list is "<<m_InternalContainer.size()<<"." ); - } - return m_InternalContainer[index]; + itkExceptionMacro(<<"Impossible to GetNthElement with the index element "<<index<<"; this element don't exist, the size of the list is "<<m_InternalContainer.size()<<"." ); } + return m_InternalContainer[index]; +} /** * Return the first element of the list. * \return The first element of the list. */ - template <class TObject> - typename ObjectList<TObject>::ObjectPointerType - ObjectList<TObject> - ::Front(void) - { - return m_InternalContainer.front(); - } - /** - * Return the last element of the list. - * \return The last element of the list. - */ - template <class TObject> - typename ObjectList<TObject>::ObjectPointerType - ObjectList<TObject> - ::Back(void) - { - return m_InternalContainer.back(); - } - /** - * Erase the nth element in the list. - * \param index The index of the element to erase. - */ - template <class TObject> - void - ObjectList<TObject> - ::Erase(unsigned int index) - { - if( index >= m_InternalContainer.size() ) - { - itkExceptionMacro(<<"Impossible to erase the index element "<<index<<"; the size of the list is "<<m_InternalContainer.size()<<"." ); - } - m_InternalContainer.erase(m_InternalContainer.begin()+index); - } - /** - * Clear the object list. - */ - template <class TObject> - void - ObjectList<TObject> - ::Clear(void) +template <class TObject> +typename ObjectList<TObject>::ObjectPointerType +ObjectList<TObject> +::Front(void) +{ + return m_InternalContainer.front(); +} +/** + * Return the last element of the list. + * \return The last element of the list. + */ +template <class TObject> +typename ObjectList<TObject>::ObjectPointerType +ObjectList<TObject> +::Back(void) +{ + return m_InternalContainer.back(); +} +/** + * Erase the nth element in the list. + * \param index The index of the element to erase. + */ +template <class TObject> +void +ObjectList<TObject> +::Erase(unsigned int index) +{ + if ( index >= m_InternalContainer.size() ) { - m_InternalContainer.clear(); + itkExceptionMacro(<<"Impossible to erase the index element "<<index<<"; the size of the list is "<<m_InternalContainer.size()<<"." ); } + m_InternalContainer.erase(m_InternalContainer.begin()+index); +} +/** + * Clear the object list. + */ +template <class TObject> +void +ObjectList<TObject> +::Clear(void) +{ + m_InternalContainer.clear(); +} - /** - * Get an Iterator that points to the beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::Iterator - ObjectList<TObject> - ::Begin(void) - { - Iterator iter(m_InternalContainer.begin()); - return iter; - } - /** - * Get a ConstIterator that points to the beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ConstIterator - ObjectList<TObject> - ::Begin(void) const - { - ConstIterator iter(m_InternalContainer.begin()); - return iter; - } - /** - * Get a ReverseIterator that points to the reverse beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ReverseIterator - ObjectList<TObject> - :: ReverseBegin(void) - { - ReverseIterator iter(m_InternalContainer.rbegin()); - return iter; - } - /** - * Get a ReverseConstIterator that points to the reverse beginning of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ReverseConstIterator - ObjectList<TObject> - ::ReverseBegin(void) const - { - ReverseConstIterator iter(m_InternalContainer.rbegin()); - return iter; - } - /** - * Get an Iterator that points past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::Iterator - ObjectList<TObject> - :: End(void) - { - Iterator iter(m_InternalContainer.end()); - return iter; - } - /** - * Get a ConstIterator that points past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ConstIterator - ObjectList<TObject> - ::End(void) const - { - ConstIterator iter(m_InternalContainer.end()); - return iter; - } - /** - * Get a ReverseIterator that points to the reverse past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ReverseIterator - ObjectList<TObject> - ::ReverseEnd(void) - { - ReverseIterator iter(m_InternalContainer.rend()); - return iter; - } - /** - * Get a ReverseConstIterator that points to the reverse past-the-end of the container. - * \return The iterator. - */ - template <class TObject> - typename ObjectList<TObject>::ReverseConstIterator - ObjectList<TObject> - ::ReverseEnd(void) const - { - ReverseConstIterator iter(m_InternalContainer.rend()); - return iter; - } - /** - * Erase elements from begin to last. - * \param begin Iterator pointing on first object to erase. - * \param end Iterator pointing past the last object to erase. - */ - template <class TObject> - void - ObjectList<TObject> - ::Erase(Iterator begin, Iterator end) - { - m_InternalContainer.erase(begin.GetIter(),end.GetIter()); - } - /** - * Erase loc element. - * \param loc Iterator pointing on object to erase. - */ - template <class TObject> - void - ObjectList<TObject> - ::Erase(Iterator loc) - { - m_InternalContainer.erase(loc.GetIter()); - } +/** + * Get an Iterator that points to the beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::Iterator +ObjectList<TObject> +::Begin(void) +{ + Iterator iter(m_InternalContainer.begin()); + return iter; +} +/** + * Get a ConstIterator that points to the beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ConstIterator +ObjectList<TObject> +::Begin(void) const +{ + ConstIterator iter(m_InternalContainer.begin()); + return iter; +} +/** + * Get a ReverseIterator that points to the reverse beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ReverseIterator +ObjectList<TObject> +:: ReverseBegin(void) +{ + ReverseIterator iter(m_InternalContainer.rbegin()); + return iter; +} +/** + * Get a ReverseConstIterator that points to the reverse beginning of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ReverseConstIterator +ObjectList<TObject> +::ReverseBegin(void) const +{ + ReverseConstIterator iter(m_InternalContainer.rbegin()); + return iter; +} +/** + * Get an Iterator that points past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::Iterator +ObjectList<TObject> +:: End(void) +{ + Iterator iter(m_InternalContainer.end()); + return iter; +} +/** + * Get a ConstIterator that points past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ConstIterator +ObjectList<TObject> +::End(void) const +{ + ConstIterator iter(m_InternalContainer.end()); + return iter; +} +/** + * Get a ReverseIterator that points to the reverse past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ReverseIterator +ObjectList<TObject> +::ReverseEnd(void) +{ + ReverseIterator iter(m_InternalContainer.rend()); + return iter; +} +/** + * Get a ReverseConstIterator that points to the reverse past-the-end of the container. + * \return The iterator. + */ +template <class TObject> +typename ObjectList<TObject>::ReverseConstIterator +ObjectList<TObject> +::ReverseEnd(void) const +{ + ReverseConstIterator iter(m_InternalContainer.rend()); + return iter; +} +/** + * Erase elements from begin to last. + * \param begin Iterator pointing on first object to erase. + * \param end Iterator pointing past the last object to erase. + */ +template <class TObject> +void +ObjectList<TObject> +::Erase(Iterator begin, Iterator end) +{ + m_InternalContainer.erase(begin.GetIter(),end.GetIter()); +} +/** + * Erase loc element. + * \param loc Iterator pointing on object to erase. + */ +template <class TObject> +void +ObjectList<TObject> +::Erase(Iterator loc) +{ + m_InternalContainer.erase(loc.GetIter()); +} - /**PrintSelf method */ - template <class TObject> - void - ObjectList<TObject> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "Size: " << m_InternalContainer.size() << std::endl; - } +/**PrintSelf method */ +template <class TObject> +void +ObjectList<TObject> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Size: " << m_InternalContainer.size() << std::endl; +} } // end namespace otb #endif diff --git a/Code/Common/otbObjectListSource.h b/Code/Common/otbObjectListSource.h index b98887140c76492c4fe7b0576ee2a705af6ec547..782b18f5348de9b1a97392c7e4068389165ccf34 100644 --- a/Code/Common/otbObjectListSource.h +++ b/Code/Common/otbObjectListSource.h @@ -38,27 +38,27 @@ namespace otb * * \ingroup ObjectListFilter */ - template <class TOutputList > - class ITK_EXPORT ObjectListSource : public itk::ProcessObject - { - public: - /** Standard class typedefs. */ - typedef ObjectListSource Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +template <class TOutputList > +class ITK_EXPORT ObjectListSource : public itk::ProcessObject +{ +public: + /** Standard class typedefs. */ + typedef ObjectListSource Self; + typedef itk::ProcessObject Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(ObjectListSource, ProcessObject); + /** Run-time type information (and related methods). */ + itkTypeMacro(ObjectListSource, ProcessObject); - /** Some typedefs. */ - typedef TOutputList OutputListType; - typedef typename TOutputList::Pointer OutputListPointer; + /** Some typedefs. */ + typedef TOutputList OutputListType; + typedef typename TOutputList::Pointer OutputListPointer; - typedef itk::DataObject::Pointer DataObjectPointer; + typedef itk::DataObject::Pointer DataObjectPointer; /** Make a DataObject of the correct type to used as the specified * output. Every ProcessObject subclass must be able to create a @@ -73,125 +73,125 @@ namespace otb * SmartPointer to a DataObject. If a subclass of ImageSource has * multiple outputs of different types, then that class must provide * an implementation of MakeOutput(). */ - virtual DataObjectPointer MakeOutput(unsigned int idx); - - /** Graft the specified DataObject onto this ProcessObject's output. - * This method grabs a handle to the specified DataObject's path - * data to use as its output's own path data. It also copies the - * region ivars (RequestedRegion, BufferedRegion, - * LargestPossibleRegion) and meta-data (Spacing, Origin) from the - * specified data object into this filter's output data object. Most - * importantly, however, it leaves the Source ivar untouched so the - * original pipeline routing is intact. This method is used when a - * process object is implemented using a mini-pipeline which is - * defined in its GenerateData() method. The usage is: - * - * \code - * // setup the mini-pipeline to process the input to this filter - * firstFilterInMiniPipeline->SetInput( this->GetInput() ); - * - * // setup the mini-pipeline to calculate the correct regions - * // and write to the appropriate bulk data block - * lastFilterInMiniPipeline->GraftOutput( this->GetOutput() ); - * - * // execute the mini-pipeline - * lastFilterInMiniPipeline->Update(); - * - * // graft the mini-pipeline output back onto this filter's output. - * // this is needed to get the appropriate regions passed back. - * this->GraftOutput( lastFilterInMiniPipeline->GetOutput() ); - * \endcode - * - * For proper pipeline execution, a filter using a mini-pipeline - * must implement the GeneratseInputRequestedRegion(), - * GenerateOutputRequestedRegion(), GenerateOutputInformation() and - * EnlargeOutputRequestedRegion() methods as necessary to reflect - * how the mini-pipeline will execute (in other words, the outer - * filter's pipeline mechanism must be consistent with what the - * mini-pipeline will do). */ - void GraftOutput(itk::DataObject *graft); - - /** Graft the specified data object onto this ProcessObject's idx'th - * output. This is the similar to GraftOutput method except is - * allows you specify which output is affected. The specified index - * must be a valid output number (less than - * ProcessObject::GetNumberOfOutputs()). See the GraftOutput for - * general usage information. */ - void GraftNthOutput(unsigned int idx, itk::DataObject *graft); - - /** Get the output data of this process object. The output of this - * function is not valid until an appropriate Update() method has - * been called, either explicitly or implicitly. Both the filter - * itself and the data object have Update() methods, and both - * methods update the data. Here are three ways to use - * GetOutput() and make sure the data is valid. In these - * examples, \a image is a pointer to some Image object, and the - * particular ProcessObjects involved are filters. The same - * examples apply to non-image (e.g. Mesh) data as well. - * - * \code - * anotherFilter->SetInput( someFilter->GetOutput() ); - * anotherFilter->Update(); - * \endcode - * - * In this situation, \a someFilter and \a anotherFilter are said - * to constitute a \b pipeline. - * - * \code - * image = someFilter->GetOutput(); - * image->Update(); - * \endcode - * - * \code - * someFilter->Update(); - * image = someFilter->GetOutput(); - * \endcode - * (In the above example, the two lines of code can be in - * either order.) - * - * Note that Update() is not called automatically except within a - * pipeline as in the first example. When \b streaming (using a - * StreamingImageFilter) is activated, it may be more efficient to - * use a pipeline than to call Update() once for each filter in - * turn. - * - * For an image, the data generated is for the requested - * Region, which can be set using ImageBase::SetRequestedRegion(). - * By default, the largest possible region is requested. - */ - OutputListType * GetOutput(void); - OutputListType * GetOutput(unsigned int idx); - - - protected: - /** Constructor */ - ObjectListSource(); - /** Destructor */ - virtual ~ObjectListSource() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Ensure that the output lists are cleared before processing */ - virtual void AllocateOutputs(); - - /** ObjectListSource can be implemented as a multithreaded filter. - * Therefore, this implementation provides a ThreadedGenerateData() routine - * which is called for each processing thread. The output image data is - * allocated automatically by the superclass prior to calling - * ThreadedGenerateData(). ThreadedGenerateData can only write to the - * portion of the output image specified by the parameter - * "outputRegionForThread" - * - * \sa ImageToImageFilter::ThreadedGenerateData(), - * ImageToImageFilter::GenerateData() */ - virtual void GenerateData(void); - - - private: - ObjectListSource(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** Graft the specified DataObject onto this ProcessObject's output. + * This method grabs a handle to the specified DataObject's path + * data to use as its output's own path data. It also copies the + * region ivars (RequestedRegion, BufferedRegion, + * LargestPossibleRegion) and meta-data (Spacing, Origin) from the + * specified data object into this filter's output data object. Most + * importantly, however, it leaves the Source ivar untouched so the + * original pipeline routing is intact. This method is used when a + * process object is implemented using a mini-pipeline which is + * defined in its GenerateData() method. The usage is: + * + * \code + * // setup the mini-pipeline to process the input to this filter + * firstFilterInMiniPipeline->SetInput( this->GetInput() ); + * + * // setup the mini-pipeline to calculate the correct regions + * // and write to the appropriate bulk data block + * lastFilterInMiniPipeline->GraftOutput( this->GetOutput() ); + * + * // execute the mini-pipeline + * lastFilterInMiniPipeline->Update(); + * + * // graft the mini-pipeline output back onto this filter's output. + * // this is needed to get the appropriate regions passed back. + * this->GraftOutput( lastFilterInMiniPipeline->GetOutput() ); + * \endcode + * + * For proper pipeline execution, a filter using a mini-pipeline + * must implement the GeneratseInputRequestedRegion(), + * GenerateOutputRequestedRegion(), GenerateOutputInformation() and + * EnlargeOutputRequestedRegion() methods as necessary to reflect + * how the mini-pipeline will execute (in other words, the outer + * filter's pipeline mechanism must be consistent with what the + * mini-pipeline will do). */ + void GraftOutput(itk::DataObject *graft); + + /** Graft the specified data object onto this ProcessObject's idx'th + * output. This is the similar to GraftOutput method except is + * allows you specify which output is affected. The specified index + * must be a valid output number (less than + * ProcessObject::GetNumberOfOutputs()). See the GraftOutput for + * general usage information. */ + void GraftNthOutput(unsigned int idx, itk::DataObject *graft); + + /** Get the output data of this process object. The output of this + * function is not valid until an appropriate Update() method has + * been called, either explicitly or implicitly. Both the filter + * itself and the data object have Update() methods, and both + * methods update the data. Here are three ways to use + * GetOutput() and make sure the data is valid. In these + * examples, \a image is a pointer to some Image object, and the + * particular ProcessObjects involved are filters. The same + * examples apply to non-image (e.g. Mesh) data as well. + * + * \code + * anotherFilter->SetInput( someFilter->GetOutput() ); + * anotherFilter->Update(); + * \endcode + * + * In this situation, \a someFilter and \a anotherFilter are said + * to constitute a \b pipeline. + * + * \code + * image = someFilter->GetOutput(); + * image->Update(); + * \endcode + * + * \code + * someFilter->Update(); + * image = someFilter->GetOutput(); + * \endcode + * (In the above example, the two lines of code can be in + * either order.) + * + * Note that Update() is not called automatically except within a + * pipeline as in the first example. When \b streaming (using a + * StreamingImageFilter) is activated, it may be more efficient to + * use a pipeline than to call Update() once for each filter in + * turn. + * + * For an image, the data generated is for the requested + * Region, which can be set using ImageBase::SetRequestedRegion(). + * By default, the largest possible region is requested. + */ + OutputListType * GetOutput(void); + OutputListType * GetOutput(unsigned int idx); + + +protected: + /** Constructor */ + ObjectListSource(); + /** Destructor */ + virtual ~ObjectListSource() {}; + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /** Ensure that the output lists are cleared before processing */ + virtual void AllocateOutputs(); + + /** ObjectListSource can be implemented as a multithreaded filter. + * Therefore, this implementation provides a ThreadedGenerateData() routine + * which is called for each processing thread. The output image data is + * allocated automatically by the superclass prior to calling + * ThreadedGenerateData(). ThreadedGenerateData can only write to the + * portion of the output image specified by the parameter + * "outputRegionForThread" + * + * \sa ImageToImageFilter::ThreadedGenerateData(), + * ImageToImageFilter::GenerateData() */ + virtual void GenerateData(void); + + +private: + ObjectListSource(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // end namespace otb diff --git a/Code/Common/otbObjectListSource.txx b/Code/Common/otbObjectListSource.txx index 2d1a8436c05bdd4aac6299dca98c4e24b9cdd8e5..43141c5c08d86336dc56140b14b2d74f88680463 100644 --- a/Code/Common/otbObjectListSource.txx +++ b/Code/Common/otbObjectListSource.txx @@ -28,134 +28,134 @@ namespace otb /** * Constructor */ - template <class TOutputList> - ObjectListSource<TOutputList> - ::ObjectListSource() - { +template <class TOutputList> +ObjectListSource<TOutputList> +::ObjectListSource() +{ // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputImage - typename TOutputList::Pointer output - = static_cast<TOutputList*>(this->MakeOutput(0).GetPointer()); - this->Superclass::SetNumberOfRequiredOutputs(1); - this->Superclass::SetNthOutput(0, output.GetPointer()); + typename TOutputList::Pointer output + = static_cast<TOutputList*>(this->MakeOutput(0).GetPointer()); + this->Superclass::SetNumberOfRequiredOutputs(1); + this->Superclass::SetNthOutput(0, output.GetPointer()); - } +} - /** - * - */ - template<class TOutputList> - typename ObjectListSource<TOutputList>::DataObjectPointer - ObjectListSource<TOutputList> - ::MakeOutput(unsigned int) +/** + * + */ +template<class TOutputList> +typename ObjectListSource<TOutputList>::DataObjectPointer +ObjectListSource<TOutputList> +::MakeOutput(unsigned int) +{ + return static_cast<itk::DataObject*>(TOutputList::New().GetPointer()); +} + +/** + * + */ +template <class TOutputList> +typename ObjectListSource<TOutputList>::OutputListType * +ObjectListSource<TOutputList> +::GetOutput() +{ + if (this->GetNumberOfOutputs() < 1) { - return static_cast<itk::DataObject*>(TOutputList::New().GetPointer()); + return 0; } - /** - * - */ - template <class TOutputList> - typename ObjectListSource<TOutputList>::OutputListType * - ObjectListSource<TOutputList> - ::GetOutput() - { - if (this->GetNumberOfOutputs() < 1) - { - return 0; - } + return static_cast<TOutputList*> + (this->Superclass::GetOutput(0)); +} - return static_cast<TOutputList*> - (this->Superclass::GetOutput(0)); - } +/** + * + */ +template <class TOutputList> +typename ObjectListSource<TOutputList>::OutputListType * +ObjectListSource<TOutputList> +::GetOutput(unsigned int idx) +{ + return static_cast<TOutputList*> + (this->Superclass::GetOutput(idx)); +} - /** - * - */ - template <class TOutputList> - typename ObjectListSource<TOutputList>::OutputListType * - ObjectListSource<TOutputList> - ::GetOutput(unsigned int idx) - { - return static_cast<TOutputList*> - (this->Superclass::GetOutput(idx)); - } +/** + * + */ +template<class TOutputList> +void +ObjectListSource<TOutputList> +::GraftOutput(itk::DataObject *graft) +{ + this->GraftNthOutput(0, graft); +} - /** - * - */ - template<class TOutputList> - void - ObjectListSource<TOutputList> - ::GraftOutput(itk::DataObject *graft) +/** + * + */ +template<class TOutputList> +void +ObjectListSource<TOutputList> +::GraftNthOutput(unsigned int idx, itk::DataObject *graft) +{ + if ( idx >= this->GetNumberOfOutputs() ) { - this->GraftNthOutput(0, graft); + itkExceptionMacro(<<"Requested to graft output " << idx << + " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); } - /** - * - */ - template<class TOutputList> - void - ObjectListSource<TOutputList> - ::GraftNthOutput(unsigned int idx, itk::DataObject *graft) + if ( !graft ) { - if ( idx >= this->GetNumberOfOutputs() ) - { - itkExceptionMacro(<<"Requested to graft output " << idx << - " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); - } - - if ( !graft ) - { - itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); - } + itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); + } - itk::DataObject * output = this->GetOutput(idx); + itk::DataObject * output = this->GetOutput(idx); - // Call GraftImage to copy meta-information, regions, and the pixel container - output->Graft( graft ); - } + // Call GraftImage to copy meta-information, regions, and the pixel container + output->Graft( graft ); +} //---------------------------------------------------------------------------- - template <class TOutputList> - void - ObjectListSource<TOutputList> - ::AllocateOutputs() - { - OutputListPointer outputPtr; +template <class TOutputList> +void +ObjectListSource<TOutputList> +::AllocateOutputs() +{ + OutputListPointer outputPtr; // Allocate the output memory - for (unsigned int i=0; i < this->GetNumberOfOutputs(); i++) - { - outputPtr = this->GetOutput(i); - outputPtr->Clear(); - } + for (unsigned int i=0; i < this->GetNumberOfOutputs(); i++) + { + outputPtr = this->GetOutput(i); + outputPtr->Clear(); } +} /** * GenerateData */ - template <class TOutputList> - void - ObjectListSource<TOutputList> - ::GenerateData(void) - { - itkExceptionMacro("subclass should override this method!!!"); - } +template <class TOutputList> +void +ObjectListSource<TOutputList> +::GenerateData(void) +{ + itkExceptionMacro("subclass should override this method!!!"); +} /** * PrintSelf Method */ - template <class TOutputList> - void - ObjectListSource<TOutputList> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template <class TOutputList> +void +ObjectListSource<TOutputList> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} } // end namespace otb #endif diff --git a/Code/Common/otbObjectListToObjectListFilter.h b/Code/Common/otbObjectListToObjectListFilter.h index 1669bfdcc9d205ed04a32d33f00f411b3484c985..35cfe3ffef30cf767583151f782f5440304bab89 100644 --- a/Code/Common/otbObjectListToObjectListFilter.h +++ b/Code/Common/otbObjectListToObjectListFilter.h @@ -37,81 +37,81 @@ namespace otb * * \ingroup ObjectListFilter */ - template <class TInputList, class TOutputList > - class ITK_EXPORT ObjectListToObjectListFilter : public otb::ObjectListSource<TOutputList> - { - public: - /** Standard class typedefs. */ - typedef ObjectListToObjectListFilter Self; - typedef otb::ObjectListSource<TOutputList> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +template <class TInputList, class TOutputList > +class ITK_EXPORT ObjectListToObjectListFilter : public otb::ObjectListSource<TOutputList> +{ +public: + /** Standard class typedefs. */ + typedef ObjectListToObjectListFilter Self; + typedef otb::ObjectListSource<TOutputList> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(ObjectListToObjectListFilter, ObjectListSource); + /** Run-time type information (and related methods). */ + itkTypeMacro(ObjectListToObjectListFilter, ObjectListSource); - /** Some typedefs. */ - typedef TInputList InputListType; - typedef TOutputList OutputListType; - typedef typename TInputList::ConstPointer InputListPointer; - typedef typename TOutputList::Pointer OutputListPointer; - typedef typename TInputList::ConstIterator InputListIterator; - typedef typename InputListType::ObjectType InputObjectType; - typedef typename OutputListType::ObjectType OutputObjectType; + /** Some typedefs. */ + typedef TInputList InputListType; + typedef TOutputList OutputListType; + typedef typename TInputList::ConstPointer InputListPointer; + typedef typename TOutputList::Pointer OutputListPointer; + typedef typename TInputList::ConstIterator InputListIterator; + typedef typename InputListType::ObjectType InputObjectType; + typedef typename OutputListType::ObjectType OutputObjectType; - typedef itk::DataObject::Pointer DataObjectPointer; + typedef itk::DataObject::Pointer DataObjectPointer; - typedef std::vector<OutputListPointer> OutputListForThreadType; + typedef std::vector<OutputListPointer> OutputListForThreadType; - virtual void SetInput( const InputListType *input); - const InputListType * GetInput(void); + virtual void SetInput( const InputListType *input); + const InputListType * GetInput(void); - protected: - /** Constructor */ - ObjectListToObjectListFilter(); - /** Destructor */ - virtual ~ObjectListToObjectListFilter() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + /** Constructor */ + ObjectListToObjectListFilter(); + /** Destructor */ + virtual ~ObjectListToObjectListFilter() {}; + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - virtual void GenerateData(void); + virtual void GenerateData(void); - /** Multi-threading implementation */ + /** Multi-threading implementation */ - virtual void BeforeThreadedGenerateData(); + virtual void BeforeThreadedGenerateData(); - virtual void AfterThreadedGenerateData() {}; + virtual void AfterThreadedGenerateData() {}; - virtual int SplitRequestedRegion(int threadId, int threadCount, unsigned int requestedElements, unsigned int& startIndex, unsigned int& stopIndex); + virtual int SplitRequestedRegion(int threadId, int threadCount, unsigned int requestedElements, unsigned int& startIndex, unsigned int& stopIndex); - /** startIndex and stopIndex represent the indices of the Objects - * to examine in thread threadId */ - virtual void ThreadedGenerateData(unsigned int startIndex, unsigned int stopIndex, int threadId); + /** startIndex and stopIndex represent the indices of the Objects + * to examine in thread threadId */ + virtual void ThreadedGenerateData(unsigned int startIndex, unsigned int stopIndex, int threadId); - /** Static function used as a "callback" by the MultiThreader. The threading - * library will call this routine for each thread, which will delegate the - * control to ThreadedGenerateData(). */ - static ITK_THREAD_RETURN_TYPE ThreaderCallback( void *arg ); + /** Static function used as a "callback" by the MultiThreader. The threading + * library will call this routine for each thread, which will delegate the + * control to ThreadedGenerateData(). */ + static ITK_THREAD_RETURN_TYPE ThreaderCallback( void *arg ); - /** Internal structure used for passing image data into the threading library */ - struct ThreadStruct - { - Pointer Filter; - }; + /** Internal structure used for passing image data into the threading library */ + struct ThreadStruct + { + Pointer Filter; + }; - /** End Multi-threading implementation */ + /** End Multi-threading implementation */ - OutputListForThreadType m_ObjectListPerThread; + OutputListForThreadType m_ObjectListPerThread; - private: - ObjectListToObjectListFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + ObjectListToObjectListFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; } // end namespace otb diff --git a/Code/Common/otbObjectListToObjectListFilter.txx b/Code/Common/otbObjectListToObjectListFilter.txx index 79e8e68fd478f161e79297aeacfce9f5d60e1984..7873b88b0269ba1ab0764b0e3fb849817205fc2a 100644 --- a/Code/Common/otbObjectListToObjectListFilter.txx +++ b/Code/Common/otbObjectListToObjectListFilter.txx @@ -27,148 +27,148 @@ namespace otb /** * Constructor */ - template <class TInputList, class TOutputList> - ObjectListToObjectListFilter<TInputList,TOutputList> - ::ObjectListToObjectListFilter() - { - this->SetNumberOfRequiredInputs( 1 ); - } +template <class TInputList, class TOutputList> +ObjectListToObjectListFilter<TInputList,TOutputList> +::ObjectListToObjectListFilter() +{ + this->SetNumberOfRequiredInputs( 1 ); +} - template <class TInputList, class TOutputList> - void - ObjectListToObjectListFilter<TInputList,TOutputList> - ::SetInput(const InputListType *input) +template <class TInputList, class TOutputList> +void +ObjectListToObjectListFilter<TInputList,TOutputList> +::SetInput(const InputListType *input) +{ +// Process object is not const-correct so the const_cast is required here + this->itk::ProcessObject::SetNthInput(0, + const_cast< InputListType * >( input ) ); +} + +template <class TInputList, class TOutputList> +const typename ObjectListToObjectListFilter<TInputList,TOutputList>::InputListType * +ObjectListToObjectListFilter<TInputList,TOutputList> +::GetInput(void) +{ + if (this->GetNumberOfInputs() < 1) { - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(0, - const_cast< InputListType * >( input ) ); + return 0; } - template <class TInputList, class TOutputList> - const typename ObjectListToObjectListFilter<TInputList,TOutputList>::InputListType * - ObjectListToObjectListFilter<TInputList,TOutputList> - ::GetInput(void) - { - if (this->GetNumberOfInputs() < 1) - { - return 0; - } - - return static_cast<const TInputList * > - (this->itk::ProcessObject::GetInput(0) ); - } + return static_cast<const TInputList * > + (this->itk::ProcessObject::GetInput(0) ); +} - template <class TInputList, class TOutputList> - int - ObjectListToObjectListFilter<TInputList,TOutputList> - ::SplitRequestedRegion(int threadId, int threadCount, unsigned int requestedElements, unsigned int& startIndex, unsigned int& stopIndex ) - { - startIndex = static_cast<unsigned int>( vcl_floor( +template <class TInputList, class TOutputList> +int +ObjectListToObjectListFilter<TInputList,TOutputList> +::SplitRequestedRegion(int threadId, int threadCount, unsigned int requestedElements, unsigned int& startIndex, unsigned int& stopIndex ) +{ + startIndex = static_cast<unsigned int>( vcl_floor( requestedElements*static_cast<double>(threadId)/static_cast<double>(threadCount)+0.5 - )); - stopIndex = static_cast<unsigned int>(vcl_floor( + )); + stopIndex = static_cast<unsigned int>(vcl_floor( requestedElements*static_cast<double>(threadId+1)/static_cast<double>(threadCount)+0.5 - )); - if (stopIndex > requestedElements) - stopIndex = requestedElements; - - //Note: check the itkImageSource.txx for the compuration done there. - // for now, there is no requested region for ObjectListFilter, so we don't - // compute anything here. - return threadCount; - } + )); + if (stopIndex > requestedElements) + stopIndex = requestedElements; + //Note: check the itkImageSource.txx for the compuration done there. + // for now, there is no requested region for ObjectListFilter, so we don't + // compute anything here. + return threadCount; +} - /** - * GenerateData - */ - template <class TInputList, class TOutputList> - void - ObjectListToObjectListFilter<TInputList,TOutputList> - ::GenerateData(void) - { + +/** + * GenerateData + */ +template <class TInputList, class TOutputList> +void +ObjectListToObjectListFilter<TInputList,TOutputList> +::GenerateData(void) +{ // Call a method that can be overridden by a subclass to perform // some calculations prior to splitting the main computations into // separate threads - this->BeforeThreadedGenerateData(); + this->BeforeThreadedGenerateData(); // Set up the multithreaded processing - ThreadStruct str; - str.Filter = this; + ThreadStruct str; + str.Filter = this; // Initializing object per thread - OutputListPointer defaultList; - this->m_ObjectListPerThread = OutputListForThreadType(this->GetNumberOfThreads(),defaultList); + OutputListPointer defaultList; + this->m_ObjectListPerThread = OutputListForThreadType(this->GetNumberOfThreads(),defaultList); // Setting up multithreader - this->GetMultiThreader()->SetNumberOfThreads(this->GetNumberOfThreads()); - this->GetMultiThreader()->SetSingleMethod(this->ThreaderCallback, &str); + this->GetMultiThreader()->SetNumberOfThreads(this->GetNumberOfThreads()); + this->GetMultiThreader()->SetSingleMethod(this->ThreaderCallback, &str); // multithread the execution - this->GetMultiThreader()->SingleMethodExecute(); + this->GetMultiThreader()->SingleMethodExecute(); // Call a method that can be overridden by a subclass to perform // some calculations after all the threads have completed - this->AfterThreadedGenerateData(); + this->AfterThreadedGenerateData(); - } +} - template <class TInputList, class TOutputList> - void - ObjectListToObjectListFilter<TInputList,TOutputList> - ::BeforeThreadedGenerateData(void) - { - this->AllocateOutputs(); - } +template <class TInputList, class TOutputList> +void +ObjectListToObjectListFilter<TInputList,TOutputList> +::BeforeThreadedGenerateData(void) +{ + this->AllocateOutputs(); +} - template <class TInputList, class TOutputList> - void - ObjectListToObjectListFilter<TInputList,TOutputList> - ::ThreadedGenerateData(unsigned int startIndex, unsigned int stopIndex,int threadId) - { +template <class TInputList, class TOutputList> +void +ObjectListToObjectListFilter<TInputList,TOutputList> +::ThreadedGenerateData(unsigned int startIndex, unsigned int stopIndex,int threadId) +{ // The following code is equivalent to: // itkExceptionMacro("subclass should override this method!!!"); // The ExceptionMacro is not used because gcc warns that a // 'noreturn' function does return - itk::OStringStream message; - message << "itk::ERROR: " << this->GetNameOfClass() - << "(" << this << "): " << "Subclass should override this method!!!"; - itk::ExceptionObject e_(__FILE__, __LINE__, message.str().c_str(),ITK_LOCATION); - throw e_; - - } - - template <class TInputList, class TOutputList> - ITK_THREAD_RETURN_TYPE - ObjectListToObjectListFilter<TInputList,TOutputList> - ::ThreaderCallback( void *arg ) - { - ThreadStruct *str; - int threadId, threadCount; - unsigned int total,start, stop; - unsigned int requestedElements; + itk::OStringStream message; + message << "itk::ERROR: " << this->GetNameOfClass() + << "(" << this << "): " << "Subclass should override this method!!!"; + itk::ExceptionObject e_(__FILE__, __LINE__, message.str().c_str(),ITK_LOCATION); + throw e_; + +} + +template <class TInputList, class TOutputList> +ITK_THREAD_RETURN_TYPE +ObjectListToObjectListFilter<TInputList,TOutputList> +::ThreaderCallback( void *arg ) +{ + ThreadStruct *str; + int threadId, threadCount; + unsigned int total,start, stop; + unsigned int requestedElements; - threadId = ((itk::MultiThreader::ThreadInfoStruct *)(arg))->ThreadID; - threadCount = ((itk::MultiThreader::ThreadInfoStruct *)(arg))->NumberOfThreads; - str = (ThreadStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); + threadId = ((itk::MultiThreader::ThreadInfoStruct *)(arg))->ThreadID; + threadCount = ((itk::MultiThreader::ThreadInfoStruct *)(arg))->NumberOfThreads; + str = (ThreadStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); - requestedElements = str->Filter->GetInput()->Size(); - total = str->Filter->SplitRequestedRegion(threadId, threadCount, requestedElements, start, stop); + requestedElements = str->Filter->GetInput()->Size(); + total = str->Filter->SplitRequestedRegion(threadId, threadCount, requestedElements, start, stop); - if (threadId < static_cast<int>(total)) - { + if (threadId < static_cast<int>(total)) + { // For very small list it might occur that start = stop. In this // case the vertex at that index will be processed in the next strip. - if(start!=stop) - { - str->Filter->ThreadedGenerateData(start, stop, threadId); - } + if (start!=stop) + { + str->Filter->ThreadedGenerateData(start, stop, threadId); } + } // else // { // otherwise don't use this thread. Sometimes the threads dont @@ -176,20 +176,20 @@ namespace otb // few threads idle. // } - return ITK_THREAD_RETURN_VALUE; - } + return ITK_THREAD_RETURN_VALUE; +} /** * PrintSelf Method */ - template <class TInputList, class TOutputList> - void - ObjectListToObjectListFilter<TInputList,TOutputList> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } +template <class TInputList, class TOutputList> +void +ObjectListToObjectListFilter<TInputList,TOutputList> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } // end namespace otb diff --git a/Code/Common/otbPathFunction.h b/Code/Common/otbPathFunction.h index 93f3607fe389f05752eb5add9f64e1ac980f16ae..fb95561b1dc578cc2d89ff35c2b6414b82b84d1b 100644 --- a/Code/Common/otbPathFunction.h +++ b/Code/Common/otbPathFunction.h @@ -41,9 +41,9 @@ namespace otb * \ingroup PathFunction */ template <class TInputPath, - class TOutput> +class TOutput> class ITK_EXPORT PathFunction : - public itk::FunctionBase< TInputPath, TOutput > + public itk::FunctionBase< TInputPath, TOutput > { public: @@ -70,7 +70,9 @@ public: /** Get the input path. */ const InputPathType * GetInputPath() const - { return m_Path.GetPointer(); } + { + return m_Path.GetPointer(); + } protected: PathFunction(); diff --git a/Code/Common/otbPathListSource.h b/Code/Common/otbPathListSource.h index 827931f3addc7bff74f898cbe2cc9d9f3c27c42b..078173a72cb8ca6381de5e531023f061089f6943 100644 --- a/Code/Common/otbPathListSource.h +++ b/Code/Common/otbPathListSource.h @@ -37,7 +37,7 @@ namespace otb */ template <class TOutputPath > - class ITK_EXPORT PathListSource : public ObjectListSource<ObjectList<TOutputPath> > +class ITK_EXPORT PathListSource : public ObjectListSource<ObjectList<TOutputPath> > { public: /** Standard class typedefs. */ diff --git a/Code/Common/otbPathListToHistogramGenerator.h b/Code/Common/otbPathListToHistogramGenerator.h index 0a2734cca7842cbc45e43e494afd2ab69429653d..a3539c1e5fe1fde3fce9d9ca86fe8a2b765acc7e 100644 --- a/Code/Common/otbPathListToHistogramGenerator.h +++ b/Code/Common/otbPathListToHistogramGenerator.h @@ -26,7 +26,8 @@ #include "itkVector.h" #include "itkDenseFrequencyContainer.h" -namespace otb { +namespace otb +{ @@ -78,9 +79,9 @@ public: typedef itk::Statistics::ListSampleToHistogramGenerator< - ListSampleType, - MeasurementType, - FrequencyContainerType,1> GeneratorType; + ListSampleType, + MeasurementType, + FrequencyContainerType,1> GeneratorType; typedef typename GeneratorType::Pointer GeneratorPointer; diff --git a/Code/Common/otbPathListToHistogramGenerator.txx b/Code/Common/otbPathListToHistogramGenerator.txx index 4f51d1b8992cc251c87ef14dc7ba0147c243a983..d3782c74c1d672e3a4101f5d14c4c05e4fbbacc4 100644 --- a/Code/Common/otbPathListToHistogramGenerator.txx +++ b/Code/Common/otbPathListToHistogramGenerator.txx @@ -22,7 +22,8 @@ #include "otbPathListToHistogramGenerator.h" -namespace otb { +namespace otb +{ template< class TPath,class TFunction > @@ -59,27 +60,27 @@ PathListToHistogramGenerator< TPath, TFunction > ::Compute() { - PathPointer vertexList; + PathPointer vertexList; - ListSamplePointer ListSample = ListSampleType::New(); - int nbElementPathList = m_PathList->size(); + ListSamplePointer ListSample = ListSampleType::New(); + int nbElementPathList = m_PathList->size(); - ListSampleVectorType ResultFunction; + ListSampleVectorType ResultFunction; - typename TFunction::Pointer function = TFunction::New(); + typename TFunction::Pointer function = TFunction::New(); - for(int noPathList = 0; noPathList < nbElementPathList; noPathList++ ) - { - vertexList = (*m_PathList)[noPathList]; - function->SetInputPath( vertexList ); + for (int noPathList = 0; noPathList < nbElementPathList; noPathList++ ) + { + vertexList = (*m_PathList)[noPathList]; + function->SetInputPath( vertexList ); - ResultFunction[0] = static_cast<MeasurementType>( function->Evaluate() ); - ListSample->PushBack(ResultFunction); + ResultFunction[0] = static_cast<MeasurementType>( function->Evaluate() ); + ListSample->PushBack(ResultFunction); - } + } - m_HistogramGenerator->SetListSample( ListSample ); - m_HistogramGenerator->Update(); + m_HistogramGenerator->SetListSample( ListSample ); + m_HistogramGenerator->Update(); } diff --git a/Code/Common/otbPathListToPathListFilter.h b/Code/Common/otbPathListToPathListFilter.h index f283ae68961070385b91761c3c77f2176c54f31d..57f52f6d4f209b94453e0c0092c3d82399cc87d4 100644 --- a/Code/Common/otbPathListToPathListFilter.h +++ b/Code/Common/otbPathListToPathListFilter.h @@ -28,9 +28,9 @@ namespace otb */ template <class TPath> class ITK_EXPORT PathListToPathListFilter - : public ObjectListToObjectListFilter<ObjectList<TPath>, ObjectList<TPath> > + : public ObjectListToObjectListFilter<ObjectList<TPath>, ObjectList<TPath> > { - public: +public: /** Standard typedefs */ typedef PathListToPathListFilter Self; typedef ObjectListToObjectListFilter<ObjectList<TPath>, ObjectList<TPath> > Superclass; @@ -56,7 +56,7 @@ class ITK_EXPORT PathListToPathListFilter protected: /** Constructor */ - PathListToPathListFilter(){}; + PathListToPathListFilter() {}; /** Destructor */ virtual ~PathListToPathListFilter() {}; diff --git a/Code/Common/otbPersistentFilterStreamingDecorator.h b/Code/Common/otbPersistentFilterStreamingDecorator.h index 0130627a4e07683290d3fe54adae1f97260cfadc..2a2b8c59c08bc764bfe6e26c2b0eaf8f1489d411 100644 --- a/Code/Common/otbPersistentFilterStreamingDecorator.h +++ b/Code/Common/otbPersistentFilterStreamingDecorator.h @@ -40,9 +40,9 @@ namespace otb */ template <class TFilter> class ITK_EXPORT PersistentFilterStreamingDecorator - : public itk::ProcessObject + : public itk::ProcessObject { - public: +public: /** Standard typedefs */ typedef PersistentFilterStreamingDecorator Self; typedef itk::ProcessObject Superclass; @@ -74,12 +74,12 @@ class ITK_EXPORT PersistentFilterStreamingDecorator virtual void Update(void); - protected: +protected: /** Constructor */ PersistentFilterStreamingDecorator(); /** Destructor */ virtual ~PersistentFilterStreamingDecorator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void GenerateData(void); diff --git a/Code/Common/otbPersistentFilterStreamingDecorator.txx b/Code/Common/otbPersistentFilterStreamingDecorator.txx index 1efd984a0b54098e7745f3f7e977c414c44f5037..ca1558e62761086258f9c02b7b651e21e0a77af1 100644 --- a/Code/Common/otbPersistentFilterStreamingDecorator.txx +++ b/Code/Common/otbPersistentFilterStreamingDecorator.txx @@ -46,9 +46,9 @@ PersistentFilterStreamingDecorator<TFilter> ::GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<ImageType*>(this->ProcessObject::GetInput(0)); } diff --git a/Code/Common/otbPersistentImageFilter.h b/Code/Common/otbPersistentImageFilter.h index 92fdb52e3e1788fba32714d65a46089ca00eae7f..7639dfb854b3c8e9fb5c0de69db32f810e330d80 100644 --- a/Code/Common/otbPersistentImageFilter.h +++ b/Code/Common/otbPersistentImageFilter.h @@ -40,9 +40,9 @@ namespace otb */ template <class TInputImage,class TOutputImage> class ITK_EXPORT PersistentImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef PersistentImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -66,14 +66,14 @@ class ITK_EXPORT PersistentImageFilter protected: /** Constructor */ - PersistentImageFilter(){}; + PersistentImageFilter() {}; /** Destructor */ - virtual ~PersistentImageFilter(){}; - /**PrintSelf method */ + virtual ~PersistentImageFilter() {}; + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: PersistentImageFilter(const Self&); //purposely not implemented diff --git a/Code/Common/otbPointSetAndValuesFunction.h b/Code/Common/otbPointSetAndValuesFunction.h index 1c1ad17a6b261d55a58ee036eae1f8b6acebea3d..06978c37aa576a866df5772c53825673cd784e4b 100644 --- a/Code/Common/otbPointSetAndValuesFunction.h +++ b/Code/Common/otbPointSetAndValuesFunction.h @@ -27,86 +27,88 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class PointSetAndValuesFunction - * \brief Base class for function needing a point set and a set of associated value to compute the output. +/** \class PointSetAndValuesFunction + * \brief Base class for function needing a point set and a set of associated value to compute the output. + */ +template <class TPointSet, class TValue, class TCoordRep=double> +class ITK_EXPORT PointSetAndValuesFunction + : public itk::FunctionBase<itk::Point<TCoordRep,::itk::GetPointSetDimension<TPointSet>::PointDimension>,TValue> +{ +public: + /** Standard typedefs */ + typedef PointSetAndValuesFunction Self; + typedef itk::FunctionBase<itk::Point<TCoordRep,::itk::GetPointSetDimension<TPointSet>::PointDimension>,TValue> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** New macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(PointSetAndValuesFunction, FunctionBase); + + typedef TPointSet PointSetType; + typedef typename PointSetType::ConstPointer PointSetConstPointerType; + typedef TValue ValueType; + typedef TCoordRep CoordRepType; + typedef typename PointSetType::PointType PointType; + + typedef itk::Index<PointType::PointDimension> IndexType; + typedef itk::ContinuousIndex<CoordRepType,PointType::PointDimension> ContinuousIndexType; + + typedef itk::VectorContainer<unsigned long,ValueType> ValueVectorType; + typedef typename ValueVectorType::ConstPointer ValueVectorPointerType; + + itkSetObjectMacro(ValueVector,ValueVectorType); + itkGetObjectMacro(ValueVector,ValueVectorType); + + /** + * Set the point set. + * \param the point set + */ + virtual void SetPointSet( const PointSetType * ptr ); + /** + * Get the point set. + * \return the point set */ - template <class TPointSet, class TValue, class TCoordRep=double> - class ITK_EXPORT PointSetAndValuesFunction - : public itk::FunctionBase<itk::Point<TCoordRep,::itk::GetPointSetDimension<TPointSet>::PointDimension>,TValue> - { - public: - /** Standard typedefs */ - typedef PointSetAndValuesFunction Self; - typedef itk::FunctionBase<itk::Point<TCoordRep,::itk::GetPointSetDimension<TPointSet>::PointDimension>,TValue> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** New macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(PointSetAndValuesFunction, FunctionBase); - - typedef TPointSet PointSetType; - typedef typename PointSetType::ConstPointer PointSetConstPointerType; - typedef TValue ValueType; - typedef TCoordRep CoordRepType; - typedef typename PointSetType::PointType PointType; - - typedef itk::Index<PointType::PointDimension> IndexType; - typedef itk::ContinuousIndex<CoordRepType,PointType::PointDimension> ContinuousIndexType; - - typedef itk::VectorContainer<unsigned long,ValueType> ValueVectorType; - typedef typename ValueVectorType::ConstPointer ValueVectorPointerType; - - itkSetObjectMacro(ValueVector,ValueVectorType); - itkGetObjectMacro(ValueVector,ValueVectorType); - - /** - * Set the point set. - * \param the point set - */ - virtual void SetPointSet( const PointSetType * ptr ); - /** - * Get the point set. - * \return the point set - */ - const PointSetType * GetPointSe() const - { return m_PointSet.GetPointer(); } - - /** Evaluate the function at specified Point position. - * Subclasses must provide this method. */ - virtual TValue Evaluate( const PointType& point ) const = 0; - - /** Evaluate the function at specified Index position. - * Subclasses must provide this method. */ - virtual TValue EvaluateAtIndex( const IndexType & index ) const = 0; - - /** Evaluate the function at specified ContinousIndex position. - * Subclasses must provide this method. */ - virtual TValue EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const = 0; - - protected: - /** Constructor */ - PointSetAndValuesFunction() - { - m_PointSet = PointSetType::New(); - m_ValueVector = ValueVectorType::New(); - - } - /** Destructor */ - virtual ~PointSetAndValuesFunction() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - PointSetAndValuesFunction(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** PointSet */ - PointSetConstPointerType m_PointSet; - /** value vector */ - ValueVectorPointerType m_ValueVector; - }; + const PointSetType * GetPointSe() const + { + return m_PointSet.GetPointer(); + } + + /** Evaluate the function at specified Point position. + * Subclasses must provide this method. */ + virtual TValue Evaluate( const PointType& point ) const = 0; + + /** Evaluate the function at specified Index position. + * Subclasses must provide this method. */ + virtual TValue EvaluateAtIndex( const IndexType & index ) const = 0; + + /** Evaluate the function at specified ContinousIndex position. + * Subclasses must provide this method. */ + virtual TValue EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const = 0; + +protected: + /** Constructor */ + PointSetAndValuesFunction() + { + m_PointSet = PointSetType::New(); + m_ValueVector = ValueVectorType::New(); + + } + /** Destructor */ + virtual ~PointSetAndValuesFunction() {}; + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + PointSetAndValuesFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** PointSet */ + PointSetConstPointerType m_PointSet; + /** value vector */ + ValueVectorPointerType m_ValueVector; +}; }// End namespace otb #endif diff --git a/Code/Common/otbPointSetSource.h b/Code/Common/otbPointSetSource.h index abe1c8df5302f2bc88a65fbca2b717fad8da1bfa..6aceeb25655b857ef2656c14e262b6f14f84356a 100644 --- a/Code/Common/otbPointSetSource.h +++ b/Code/Common/otbPointSetSource.h @@ -138,7 +138,7 @@ private: * by the execute method. Set in the GenerateInputRequestedRegion method. */ int m_GenerateDataRegion; int m_GenerateDataNumberOfRegions; - }; +}; } // end namespace otb diff --git a/Code/Common/otbPointSetSource.txx b/Code/Common/otbPointSetSource.txx index 5326964e1aa4ebb05611483ee877a9420ce9e329..a802af3a42758053f8cf0d129b13e5a4d6d82186 100644 --- a/Code/Common/otbPointSetSource.txx +++ b/Code/Common/otbPointSetSource.txx @@ -33,7 +33,7 @@ PointSetSource<TOutputPointSet> // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputPointSet OutputPointSetPointer output - = static_cast<TOutputPointSet*>(this->MakeOutput(0).GetPointer()); + = static_cast<TOutputPointSet*>(this->MakeOutput(0).GetPointer()); this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput( 0, output.GetPointer() ); @@ -62,12 +62,12 @@ PointSetSource<TOutputPointSet> ::GetOutput(void) { if (this->GetNumberOfOutputs() < 1) - { + { return 0; - } + } return static_cast<TOutputPointSet*> - (this->ProcessObject::GetOutput(0)); + (this->ProcessObject::GetOutput(0)); } @@ -80,7 +80,7 @@ PointSetSource<TOutputPointSet> ::GetOutput(unsigned int idx) { return static_cast<TOutputPointSet*> - (this->ProcessObject::GetOutput(idx)); + (this->ProcessObject::GetOutput(idx)); } @@ -130,15 +130,15 @@ PointSetSource<TOutputPointSet> ::GraftNthOutput(unsigned int idx, itk::DataObject *graft) { if ( idx >= this->GetNumberOfOutputs() ) - { + { itkExceptionMacro(<<"Requested to graft output " << idx << - " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); - } + " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); + } if ( !graft ) - { + { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); - } + } itk::DataObject * output = this->GetOutput( idx ); diff --git a/Code/Common/otbPolyLineImageConstIterator.h b/Code/Common/otbPolyLineImageConstIterator.h index f3a82e9d17a0fd3844594c41fbdc03aaf58daf15..b8ea9ea8a3770c1772fb5cf7dda8b69212840c11 100644 --- a/Code/Common/otbPolyLineImageConstIterator.h +++ b/Code/Common/otbPolyLineImageConstIterator.h @@ -40,7 +40,7 @@ namespace otb template <class TImage, class TPath> class ITK_EXPORT PolyLineImageConstIterator { - public: +public: /** Standard typedefs */ typedef PolyLineImageConstIterator Self; @@ -73,25 +73,25 @@ class ITK_EXPORT PolyLineImageConstIterator /** Get the dimension (size) of the index. */ static unsigned int GetImageIteratorDimension() - { + { return TImage::ImageDimension; - } + } /** Get the index. This provides a read only reference to the index. */ const IndexType GetIndex() - { - return m_InternalImageIterator.GetIndex(); - } + { + return m_InternalImageIterator.GetIndex(); + } /** Get the pixel value */ const PixelType & Get(void) const - { + { return m_InternalImageIterator.Get(); - } + } /** Is the iterator at the end of the line? */ bool IsAtEnd() - { + { return (m_InternalVertexIterator == m_Path->GetVertexList()->End()) - && m_InternalImageIterator.IsAtEnd(); - } + && m_InternalImageIterator.IsAtEnd(); + } /** Move an iterator to the beginning of the line. */ void GoToBegin(); /** Walk forward along the line to the next index in the image. */ diff --git a/Code/Common/otbPolyLineImageConstIterator.txx b/Code/Common/otbPolyLineImageConstIterator.txx index 1d6687242d90d5cd0671911809f5275ee4046c4b..8ab8cdcea5aa4a90bc81badbf841e2e3c7a6aa3f 100644 --- a/Code/Common/otbPolyLineImageConstIterator.txx +++ b/Code/Common/otbPolyLineImageConstIterator.txx @@ -29,23 +29,23 @@ namespace otb template <class TImage, class TPath> PolyLineImageConstIterator<TImage, TPath> ::PolyLineImageConstIterator(const ImageType *imagePtr,const PathType * pathPtr) - : m_InternalImageIterator(const_cast<ImageType *>(imagePtr), - imagePtr->GetLargestPossibleRegion().GetIndex(), - imagePtr->GetLargestPossibleRegion().GetIndex()) + : m_InternalImageIterator(const_cast<ImageType *>(imagePtr), + imagePtr->GetLargestPossibleRegion().GetIndex(), + imagePtr->GetLargestPossibleRegion().GetIndex()) { m_Image = imagePtr; m_Path = pathPtr; m_InternalVertexIterator = m_Path->GetVertexList()->Begin(); IndexType source,target; - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { source[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } ++m_InternalVertexIterator; - if(m_InternalVertexIterator!=m_Path->GetVertexList()->End()) + if (m_InternalVertexIterator!=m_Path->GetVertexList()->End()) { - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { target[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } @@ -78,15 +78,15 @@ PolyLineImageConstIterator<TImage, TPath> { m_InternalVertexIterator = m_Path->GetVertexList()->Begin(); IndexType source,target; - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { source[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } ++m_InternalVertexIterator; - if(m_InternalVertexIterator!=m_Path->GetVertexList()->End()) + if (m_InternalVertexIterator!=m_Path->GetVertexList()->End()) { - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { target[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } @@ -103,23 +103,23 @@ void PolyLineImageConstIterator<TImage,TPath> ::operator++() { - // otbMsgDebugMacro(<<this->GetIndex()); +// otbMsgDebugMacro(<<this->GetIndex()); ++m_InternalImageIterator; - if(m_InternalImageIterator.IsAtEnd()) + if (m_InternalImageIterator.IsAtEnd()) { - if(m_InternalVertexIterator!=m_Path->GetVertexList()->End()) + if (m_InternalVertexIterator!=m_Path->GetVertexList()->End()) { IndexType source; - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { source[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } - // otbMsgDebugMacro(<<"Source: "<<source); + // otbMsgDebugMacro(<<"Source: "<<source); ++m_InternalVertexIterator; - if(m_InternalVertexIterator!=m_Path->GetVertexList()->End()) + if (m_InternalVertexIterator!=m_Path->GetVertexList()->End()) { IndexType target; - for(unsigned int i = 0;i<ImageType::ImageDimension;++i) + for (unsigned int i = 0;i<ImageType::ImageDimension;++i) { target[i] = static_cast<unsigned int>(m_InternalVertexIterator.Value()[i]); } diff --git a/Code/Common/otbPolyLineImageIterator.h b/Code/Common/otbPolyLineImageIterator.h index 12abc174e24b5c42181012304cd4744f0e8cd339..99f7a906c06a886db412b77b432d728c05aa3074 100644 --- a/Code/Common/otbPolyLineImageIterator.h +++ b/Code/Common/otbPolyLineImageIterator.h @@ -39,9 +39,9 @@ namespace otb */ template <class TImage, class TPath> class ITK_EXPORT PolyLineImageIterator - : public PolyLineImageConstIterator<TImage,TPath> + : public PolyLineImageConstIterator<TImage,TPath> { - public: +public: /** Standard typedefs */ typedef PolyLineImageIterator Self; typedef PolyLineImageConstIterator<TImage,TPath> Superclass; @@ -75,24 +75,24 @@ class ITK_EXPORT PolyLineImageIterator /** Set the pixel value */ void Set(const PixelType & value) - { - this->m_InternalImageIterator.Set(value); - } + { + this->m_InternalImageIterator.Set(value); + } /** Return a reference to the pixel * This method will provide the fastest access to pixel * data, but it will NOT support ImageAdaptors. */ PixelType & Value(void) - { - return this->m_InternalImageIterator.Value(); - } + { + return this->m_InternalImageIterator.Value(); + } Self &operator=(const Self& it) - { - this->Superclass::operator=(it); - return *this; - }; + { + this->Superclass::operator=(it); + return *this; + }; /** Constructor establishes an iterator to walk along a line */ PolyLineImageIterator(ImageType *imagePtr,PathType * pathPtr) - : Superclass(imagePtr,pathPtr) {}; + : Superclass(imagePtr,pathPtr) {}; /** Default Destructor. */ virtual ~PolyLineImageIterator() {}; }; diff --git a/Code/Common/otbPolyLineParametricPathWithValue.h b/Code/Common/otbPolyLineParametricPathWithValue.h index cff99f3729cfcaead9d6002805d81461393a0dab..379c4a924b78e9a7fd47a8970c7ddd8c19f07d32 100644 --- a/Code/Common/otbPolyLineParametricPathWithValue.h +++ b/Code/Common/otbPolyLineParametricPathWithValue.h @@ -33,9 +33,9 @@ namespace otb */ template < class TValue,unsigned int VDimension=2> class ITK_EXPORT PolyLineParametricPathWithValue - : public itk::PolyLineParametricPath<VDimension> + : public itk::PolyLineParametricPath<VDimension> { - public: +public: /** Standard typedefs */ typedef PolyLineParametricPathWithValue Self; typedef itk::PolyLineParametricPath<VDimension> Superclass; @@ -49,53 +49,53 @@ class ITK_EXPORT PolyLineParametricPathWithValue itkTypeMacro(PolyLineParametricPath, MySuperclass); /** Template parameters typedefs */ - typedef TValue ValueType; - - /** Derived typedefs */ - typedef typename Superclass::VertexType VertexType; - typedef typename Superclass::VertexListType VertexListType; - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - typedef typename VertexListType::ConstIterator VertexListConstIteratorType; - - itkGetMacro(Key,std::string); - - void SetValue(ValueType value) - { - itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); - itk::EncapsulateMetaData<ValueType>(dict,m_Key,value); - } - - ValueType GetValue(void) const - { - ValueType resp(0); - const itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); - if(dict.HasKey(m_Key)) - { - itk::ExposeMetaData<ValueType>(dict,m_Key,resp); - } - else - { - itkGenericExceptionMacro(<<"Key "<<m_Key<<" not found in metadata dictionary !"); - } - return resp; - } - - /** - * Return the path length (perimeter). - * \return The length. - */ - virtual double GetLength() const; + typedef TValue ValueType; + + /** Derived typedefs */ + typedef typename Superclass::VertexType VertexType; + typedef typename Superclass::VertexListType VertexListType; + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + typedef typename VertexListType::ConstIterator VertexListConstIteratorType; + + itkGetMacro(Key,std::string); + + void SetValue(ValueType value) + { + itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); + itk::EncapsulateMetaData<ValueType>(dict,m_Key,value); + } + + ValueType GetValue(void) const + { + ValueType resp(0); + const itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); + if (dict.HasKey(m_Key)) + { + itk::ExposeMetaData<ValueType>(dict,m_Key,resp); + } + else + { + itkGenericExceptionMacro(<<"Key "<<m_Key<<" not found in metadata dictionary !"); + } + return resp; + } + + /** + * Return the path length (perimeter). + * \return The length. + */ + virtual double GetLength() const; protected: /** Constructor */ PolyLineParametricPathWithValue(); /** Destructor */ virtual ~PolyLineParametricPathWithValue() - { } - /**PrintSelf method */ + { } + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: PolyLineParametricPathWithValue(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented std::string m_Key; diff --git a/Code/Common/otbPolyLineParametricPathWithValue.txx b/Code/Common/otbPolyLineParametricPathWithValue.txx index f63b986addf5e70dfda6aab32eea46cba7b6675f..4835b86344e0aa0010f365446c32bb2e5ca5cee6 100644 --- a/Code/Common/otbPolyLineParametricPathWithValue.txx +++ b/Code/Common/otbPolyLineParametricPathWithValue.txx @@ -22,73 +22,73 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template < class TValue,unsigned int VDimension> - PolyLineParametricPathWithValue<TValue,VDimension> - ::PolyLineParametricPathWithValue() - { - itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); - m_Key = "Value"; - itk::EncapsulateMetaData<ValueType>(dict,m_Key,0); - } +/** + * Constructor + */ +template < class TValue,unsigned int VDimension> +PolyLineParametricPathWithValue<TValue,VDimension> +::PolyLineParametricPathWithValue() +{ + itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); + m_Key = "Value"; + itk::EncapsulateMetaData<ValueType>(dict,m_Key,0); +} + +template < class TValue,unsigned int VDimension> +double PolyLineParametricPathWithValue<TValue,VDimension> +::GetLength() const +{ + double length = 0.0; + VertexListConstIteratorType it = this->GetVertexList()->Begin(); - template < class TValue,unsigned int VDimension> - double PolyLineParametricPathWithValue<TValue,VDimension> - ::GetLength() const + if (this->GetVertexList()->Size()>1) { - double length = 0.0; - VertexListConstIteratorType it = this->GetVertexList()->Begin(); - - if(this->GetVertexList()->Size()>1) - { - VertexType pt1 = it.Value();//just init, won't be used like that - VertexType pt2 = it.Value(); + VertexType pt1 = it.Value();//just init, won't be used like that + VertexType pt2 = it.Value(); - it++; - while(it != this->GetVertexList()->End()) + it++; + while (it != this->GetVertexList()->End()) + { + pt1=pt2; + pt2 = it.Value(); + double accum=0.0; + for (unsigned int i=0; i<VDimension; i++) { - pt1=pt2; - pt2 = it.Value(); - double accum=0.0; - for (unsigned int i=0; i<VDimension; i++) - { - accum += (pt1[i]-pt2[i])*(pt1[i]-pt2[i]); - } - length += vcl_sqrt(accum); - it++; + accum += (pt1[i]-pt2[i])*(pt1[i]-pt2[i]); } - - } - else //if there is strictly less than 2 points, length is 0 - { - length = 0.0; + length += vcl_sqrt(accum); + it++; } - return length; } + else //if there is strictly less than 2 points, length is 0 + { + length = 0.0; + } + + return length; +} - /** - * PrintSelf Method - */ - template < class TValue,unsigned int VDimension> - void - PolyLineParametricPathWithValue<TValue,VDimension> - ::PrintSelf(std::ostream& os, itk::Indent indent) const +/** + * PrintSelf Method + */ +template < class TValue,unsigned int VDimension> +void +PolyLineParametricPathWithValue<TValue,VDimension> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + VertexListConstIteratorType it = this->GetVertexList()->Begin(); + while (it != this->GetVertexList()->End()) { - Superclass::PrintSelf(os, indent); - VertexListConstIteratorType it = this->GetVertexList()->Begin(); - while(it != this->GetVertexList()->End()) - { - os << it.Value() << " - "; - it++; - } - os << std::endl; + os << it.Value() << " - "; + it++; } + os << std::endl; +} } // end namespace otb #endif diff --git a/Code/Common/otbPolygon.h b/Code/Common/otbPolygon.h index 6429f47d05c16153af1ac94b3709a9c9f3352706..3c2faa615631bf2020db1694a5cbe8c030440fb2 100644 --- a/Code/Common/otbPolygon.h +++ b/Code/Common/otbPolygon.h @@ -38,9 +38,9 @@ namespace otb */ template<class TValue=double> class ITK_EXPORT Polygon - : public PolyLineParametricPathWithValue<TValue,2> + : public PolyLineParametricPathWithValue<TValue,2> { - public: +public: /** Standard typedefs */ typedef Polygon Self; typedef PolyLineParametricPathWithValue<TValue,2> Superclass; @@ -63,8 +63,8 @@ class ITK_EXPORT Polygon typedef typename RegionType::SizeType SizeType; typedef typename RegionType::IndexType IndexType; - itkSetMacro(Epsilon,double); - itkGetMacro(Epsilon,double); + itkSetMacro(Epsilon,double); + itkGetMacro(Epsilon,double); /** * Check wether point is strictly inside the polygon. @@ -114,37 +114,37 @@ class ITK_EXPORT Polygon * \param a1 Second point of the second segment. * \return True if the two segments are touching without crossing. */ - bool IsTouching(VertexType a1, VertexType a2, VertexType b1, VertexType b2) const; + bool IsTouching(VertexType a1, VertexType a2, VertexType b1, VertexType b2) const; - /** - * Compute the polygon bounding region. - * \return The region. - */ - RegionType GetBoundingRegion(void); + /** + * Compute the polygon bounding region. + * \return The region. + */ + RegionType GetBoundingRegion(void); /** * Return the polygon surface. * \return The surface. */ - double GetSurface() const; + double GetSurface() const; /** * Return the polygon length (perimeter). * \return The length. */ - virtual double GetLength() const; + virtual double GetLength() const; protected: /** Constructor */ Polygon() - { - m_Epsilon = 0.000001; - }; + { + m_Epsilon = 0.000001; + }; /** Destructor */ virtual ~Polygon() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; diff --git a/Code/Common/otbPolygon.txx b/Code/Common/otbPolygon.txx index 0b9c548b66a87296feeb0647e72d2455aef3d8e9..a6e73e9dd913f5f1f372e5f4f4c75881682e8bec 100644 --- a/Code/Common/otbPolygon.txx +++ b/Code/Common/otbPolygon.txx @@ -22,11 +22,11 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Check wether point is strictly inside the polygon. - * \param point The point to check. - * \return True if the point is inside the polygon. - */ +/** + * Check wether point is strictly inside the polygon. + * \param point The point to check. + * \return True if the point is inside the polygon. + */ template<class TValue> bool @@ -40,64 +40,64 @@ Polygon<TValue> double xa = it.Value()[0]; double ya = it.Value()[1]; ++it; - while(it != this->GetVertexList()->End()) - { - double xb = it.Value()[0]; - double yb = it.Value()[1]; - if(vcl_abs(xb-xa)<m_Epsilon) + while (it != this->GetVertexList()->End()) { - if(ya>yb && xa>x && y>=yb && y<ya) + double xb = it.Value()[0]; + double yb = it.Value()[1]; + if (vcl_abs(xb-xa)<m_Epsilon) + { + if (ya>yb && xa>x && y>=yb && y<ya) { ++crossingCount; } - else if (ya<yb && xa>x && y>=ya && y<yb) + else if (ya<yb && xa>x && y>=ya && y<yb) { ++crossingCount; } - } - else if(vcl_abs(yb-ya)>=m_Epsilon) - { - double xcross = xa + (xb - xa)*(y - ya)/(yb-ya); + } + else if (vcl_abs(yb-ya)>=m_Epsilon) + { + double xcross = xa + (xb - xa)*(y - ya)/(yb-ya); - if(ya>yb && xcross>x && y >= yb && y < ya) + if (ya>yb && xcross>x && y >= yb && y < ya) { ++crossingCount; } - else if(ya<yb && xcross>x && y >= ya && y < yb) + else if (ya<yb && xcross>x && y >= ya && y < yb) { ++crossingCount; } - } - xa = xb; - ya = yb; - ++it; } + xa = xb; + ya = yb; + ++it; + } double xb = this->GetVertexList()->Begin().Value()[0]; double yb = this->GetVertexList()->Begin().Value()[1]; - if(vcl_abs(xb-xa)< m_Epsilon) - { - if(ya>yb && xa>x && y>=yb && y<ya) + if (vcl_abs(xb-xa)< m_Epsilon) { - ++crossingCount; - } - else if (ya<yb && xa>x && y>=ya && y<yb) - { - ++crossingCount; - } + if (ya>yb && xa>x && y>=yb && y<ya) + { + ++crossingCount; } - else if(vcl_abs(yb-ya)>=m_Epsilon) + else if (ya<yb && xa>x && y>=ya && y<yb) { - double xcross = xa + (xb - xa)*(y - ya)/(yb-ya); - - if(ya>yb && xcross>x && y >= yb && y < ya) - { - ++crossingCount; + ++crossingCount; + } } - else if(ya<yb && xcross>x && y >= ya && y < yb) + else if (vcl_abs(yb-ya)>=m_Epsilon) { - ++crossingCount; - } + double xcross = xa + (xb - xa)*(y - ya)/(yb-ya); + + if (ya>yb && xcross>x && y >= yb && y < ya) + { + ++crossingCount; } + else if (ya<yb && xcross>x && y >= ya && y < yb) + { + ++crossingCount; + } + } //std::cout<<"Crossing count: "<<crossingCount<<std::endl; return (crossingCount%2 == 1); } @@ -123,69 +123,69 @@ Polygon<TValue> double xbegin = xa; double ybegin = ya; ++it; - while(!resp && it != this->GetVertexList()->End()) - { - xb = it.Value()[0]; - yb = it.Value()[1]; - if(vcl_abs(xb-xa)>=m_Epsilon) + while (!resp && it != this->GetVertexList()->End()) { - double cd = (yb - ya)/(xb - xa); - double oo = (ya - cd * xa); - double xmin = std::min(xa,xb); - double xmax = std::max(xa,xb); - if ((vcl_abs(y - cd * x - oo)<m_Epsilon) - && ( x <= xmax) - && ( x >= xmin)) + xb = it.Value()[0]; + yb = it.Value()[1]; + if (vcl_abs(xb-xa)>=m_Epsilon) + { + double cd = (yb - ya)/(xb - xa); + double oo = (ya - cd * xa); + double xmin = std::min(xa,xb); + double xmax = std::max(xa,xb); + if ((vcl_abs(y - cd * x - oo)<m_Epsilon) + && ( x <= xmax) + && ( x >= xmin)) { //std::cout<<"Case 1: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; resp = true; } - } - else - { - double ymin = std::min(ya,yb); - double ymax = std::max(ya,yb); - if((vcl_abs(x-xa)<m_Epsilon) - &&(y<=ymax) - &&(y>=ymin)) + } + else + { + double ymin = std::min(ya,yb); + double ymax = std::max(ya,yb); + if ((vcl_abs(x-xa)<m_Epsilon) + &&(y<=ymax) + &&(y>=ymin)) { resp = true; //std::cout<<"Case 2: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; } - } - xa = xb; - ya = yb; - ++it; } + xa = xb; + ya = yb; + ++it; + } xb = xbegin; yb = ybegin; - if(vcl_abs(xb-xa)>=m_Epsilon) - { - double cd = (yb - ya)/(xb - xa); - double oo = (ya - cd * xa); - double xmin = std::min(xa,xb); - double xmax = std::max(xa,xb); - - if ((vcl_abs(y - cd * x - oo)<m_Epsilon) - && ( x <= xmax) - && ( x >= xmin)) + if (vcl_abs(xb-xa)>=m_Epsilon) { - resp = true; - //std::cout<<"Case 1: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; - } + double cd = (yb - ya)/(xb - xa); + double oo = (ya - cd * xa); + double xmin = std::min(xa,xb); + double xmax = std::max(xa,xb); + + if ((vcl_abs(y - cd * x - oo)<m_Epsilon) + && ( x <= xmax) + && ( x >= xmin)) + { + resp = true; + //std::cout<<"Case 1: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; } + } else - { - double ymin = std::min(ya,yb); - double ymax = std::max(ya,yb); - if((vcl_abs(x-xa)<=m_Epsilon) - &&(y<=ymax) - &&(y>=ymin)) { - resp = true; - //std::cout<<"Case 2: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; - } + double ymin = std::min(ya,yb); + double ymax = std::max(ya,yb); + if ((vcl_abs(x-xa)<=m_Epsilon) + &&(y<=ymax) + &&(y>=ymin)) + { + resp = true; + //std::cout<<"Case 2: Point is on segment "<<xa<<", "<<ya<<" <-> "<<xb<<", "<<yb<<std::endl; } + } //std::cout<<"Result: "<<resp<<std::endl; return resp; } @@ -207,20 +207,20 @@ Polygon<TValue> VertexType first = current; ++it; while ( it != it_end) + { + //std::cout<<"Testing Is crossing "<<a<<" "<<b<<current<<it.Value()<<" = "<<IsCrossing(a,b,current,it.Value())<<std::endl; + if (IsCrossing(a,b,current,it.Value())) { - //std::cout<<"Testing Is crossing "<<a<<" "<<b<<current<<it.Value()<<" = "<<IsCrossing(a,b,current,it.Value())<<std::endl; - if(IsCrossing(a,b,current,it.Value())) + ++resp; + } + current = it.Value(); + ++it; + } + //std::cout<<"Testing Is crossing "<<a<<" "<<b<<current<<first<<" = "<<IsCrossing(a,b,current,first)<<std::endl; + if (IsCrossing(a,b,current,first)) { ++resp; } - current = it.Value(); - ++it; - } - //std::cout<<"Testing Is crossing "<<a<<" "<<b<<current<<first<<" = "<<IsCrossing(a,b,current,first)<<std::endl; - if(IsCrossing(a,b,current,first)) - { - ++resp; - } return resp; } /** @@ -241,20 +241,20 @@ Polygon<TValue> VertexType first = current; ++it; while ( it != it_end) - { - //std::cout<<"IsTouching "<<a<<" "<<b<<", "<<current<<" "<<it.Value()<<" -> "<<IsTouching(a,b,current,it.Value())<<std::endl; - if (IsTouching(a,b,current,it.Value())) { - ++resp; - } - current = it.Value(); - ++it; - } - //std::cout<<"IsTouching "<<a<<" "<<b<<", "<<current<<" "<<first<<" -> "<<IsTouching(a,b,current,first)<<std::endl; - if(IsTouching(a,b,current,first)) + //std::cout<<"IsTouching "<<a<<" "<<b<<", "<<current<<" "<<it.Value()<<" -> "<<IsTouching(a,b,current,it.Value())<<std::endl; + if (IsTouching(a,b,current,it.Value())) { ++resp; } + current = it.Value(); + ++it; + } + //std::cout<<"IsTouching "<<a<<" "<<b<<", "<<current<<" "<<first<<" -> "<<IsTouching(a,b,current,first)<<std::endl; + if (IsTouching(a,b,current,first)) + { + ++resp; + } return resp; } /** @@ -279,39 +279,39 @@ Polygon<TValue> double xamax = std::max(a1[0],a2[0]); double yamin = std::min(a1[1],a2[1]); double yamax = std::max(a1[1],a2[1]); - if(vcl_abs(a1[0]-a2[0])<m_Epsilon && vcl_abs(b1[0]-b2[0])<m_Epsilon) - { - resp = false; - } - else if(vcl_abs(a1[0]-a2[0])<m_Epsilon) - { - double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); - double oo2 = b1[1] - cd2 * b1[0]; - double ycross = cd2 * a1[0] + oo2; - resp = ( xbmin < a1[0] && xbmax > a1[0] - && yamin < ycross && yamax > ycross); - } - else if(vcl_abs(b1[0]-b2[0])<m_Epsilon) - { - double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); - double oo1 = a1[1] - cd1 * a1[0]; - double ycross = cd1 * b1[0] + oo1; - resp = ( xamin < b1[0] && xamax > b1[0] - && ybmin < ycross && ybmax > ycross); - } - else - { - double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); - double oo1 = a1[1] - cd1 * a1[0]; - double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); - double oo2 = b1[1] - cd2 * b1[0]; - if(cd1 != cd2) + if (vcl_abs(a1[0]-a2[0])<m_Epsilon && vcl_abs(b1[0]-b2[0])<m_Epsilon) + { + resp = false; + } + else if (vcl_abs(a1[0]-a2[0])<m_Epsilon) + { + double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); + double oo2 = b1[1] - cd2 * b1[0]; + double ycross = cd2 * a1[0] + oo2; + resp = ( xbmin < a1[0] && xbmax > a1[0] + && yamin < ycross && yamax > ycross); + } + else if (vcl_abs(b1[0]-b2[0])<m_Epsilon) { - double xcross = (oo2 - oo1) / (cd1 - cd2); - resp = (xamin < xcross && xbmin < xcross - && xamax > xcross && xbmax > xcross); + double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); + double oo1 = a1[1] - cd1 * a1[0]; + double ycross = cd1 * b1[0] + oo1; + resp = ( xamin < b1[0] && xamax > b1[0] + && ybmin < ycross && ybmax > ycross); } + else + { + double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); + double oo1 = a1[1] - cd1 * a1[0]; + double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); + double oo2 = b1[1] - cd2 * b1[0]; + if (cd1 != cd2) + { + double xcross = (oo2 - oo1) / (cd1 - cd2); + resp = (xamin < xcross && xbmin < xcross + && xamax > xcross && xbmax > xcross); } + } return resp; } /** @@ -336,75 +336,75 @@ Polygon<TValue> double xamax = std::max(a1[0],a2[0]); double yamin = std::min(a1[1],a2[1]); double yamax = std::max(a1[1],a2[1]); - if(vcl_abs(a1[0]-a2[0])<m_Epsilon && vcl_abs(b1[0]-b2[0])<m_Epsilon) - { - resp = (vcl_abs(a1[0]-b1[0])<m_Epsilon) - && ((a1[1]<=ybmax && a1[1]>=ybmin) - || (a2[1]<=ybmax && a2[1]>=ybmin) - || (b1[1]<=yamax && b1[1]>=yamin) - || (b2[1]<=yamax && b2[1]>=yamin) ); - } - else if(vcl_abs(a1[0]-a2[0])<m_Epsilon) - { - double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); - double oo2 = b1[1] - cd2 * b1[0]; - - if(vcl_abs(a1[1]-cd2*a1[0]-oo2)<m_Epsilon) + if (vcl_abs(a1[0]-a2[0])<m_Epsilon && vcl_abs(b1[0]-b2[0])<m_Epsilon) { - resp = ( a1[0]>=xbmin && a1[0]<=xbmax); + resp = (vcl_abs(a1[0]-b1[0])<m_Epsilon) + && ((a1[1]<=ybmax && a1[1]>=ybmin) + || (a2[1]<=ybmax && a2[1]>=ybmin) + || (b1[1]<=yamax && b1[1]>=yamin) + || (b2[1]<=yamax && b2[1]>=yamin) ); } - else if(vcl_abs(a2[1]-cd2*a2[0]-oo2)<m_Epsilon) + else if (vcl_abs(a1[0]-a2[0])<m_Epsilon) { - resp = ( a2[0]>=xbmin && a2[0]<=xbmax); - } + double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); + double oo2 = b1[1] - cd2 * b1[0]; + + if (vcl_abs(a1[1]-cd2*a1[0]-oo2)<m_Epsilon) + { + resp = ( a1[0]>=xbmin && a1[0]<=xbmax); } - else if(vcl_abs(b1[0]-b2[0])<m_Epsilon) + else if (vcl_abs(a2[1]-cd2*a2[0]-oo2)<m_Epsilon) { - double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); - double oo1 = a1[1] - cd1 * a1[0]; - - if(vcl_abs(b1[1]-cd1*b1[0]-oo1)<m_Epsilon) - { - resp = ( b1[0]>=xamin && b1[0]<=xamax); + resp = ( a2[0]>=xbmin && a2[0]<=xbmax); + } } - else if(vcl_abs(b2[1]-cd1*b2[0]-oo1)<m_Epsilon) + else if (vcl_abs(b1[0]-b2[0])<m_Epsilon) + { + double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); + double oo1 = a1[1] - cd1 * a1[0]; + + if (vcl_abs(b1[1]-cd1*b1[0]-oo1)<m_Epsilon) { - resp = ( b2[0]>=xamin && b2[0]<=xamax); - } + resp = ( b1[0]>=xamin && b1[0]<=xamax); } - else + else if (vcl_abs(b2[1]-cd1*b2[0]-oo1)<m_Epsilon) { - double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); - double oo1 = a1[1] - cd1 * a1[0]; - double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); - double oo2 = b1[1] - cd2 * b1[0]; - if(vcl_abs(cd1-cd2)<m_Epsilon && vcl_abs(oo1-oo2)<m_Epsilon) - { - resp =((xamin <= xbmax && xamin >= xbmin) - || (xamax <= xbmax && xamax >= xbmin) - || (xbmin <= xamax && xbmin >= xamin) - || (xbmax <= xamax && xbmax >= xamin) ); + resp = ( b2[0]>=xamin && b2[0]<=xamax); + } } - else + else { - if(vcl_abs(a1[1]-cd2*a1[0]-oo2)<m_Epsilon) - { - resp = ( a1[0]>=xbmin && a1[0]<=xbmax); - } - else if(vcl_abs(a2[1]-cd2*a2[0]-oo2)<m_Epsilon) + double cd1 = (a2[1] - a1[1]) / (a2[0] - a1[0]); + double oo1 = a1[1] - cd1 * a1[0]; + double cd2 = (b2[1] - b1[1]) / (b2[0] - b1[0]); + double oo2 = b1[1] - cd2 * b1[0]; + if (vcl_abs(cd1-cd2)<m_Epsilon && vcl_abs(oo1-oo2)<m_Epsilon) + { + resp =((xamin <= xbmax && xamin >= xbmin) + || (xamax <= xbmax && xamax >= xbmin) + || (xbmin <= xamax && xbmin >= xamin) + || (xbmax <= xamax && xbmax >= xamin) ); + } + else + { + if (vcl_abs(a1[1]-cd2*a1[0]-oo2)<m_Epsilon) { - resp = ( a2[0]>=xbmin && a2[0]<=xbmax); + resp = ( a1[0]>=xbmin && a1[0]<=xbmax); } - if(vcl_abs(b1[1]-cd1*b1[0]-oo1)<m_Epsilon) + else if (vcl_abs(a2[1]-cd2*a2[0]-oo2)<m_Epsilon) { - resp = ( b1[0]>=xamin && b1[0]<=xamax); + resp = ( a2[0]>=xbmin && a2[0]<=xbmax); } - else if(vcl_abs(b2[1]-cd1*b2[0]-oo1)<m_Epsilon) + if (vcl_abs(b1[1]-cd1*b1[0]-oo1)<m_Epsilon) + { + resp = ( b1[0]>=xamin && b1[0]<=xamax); + } + else if (vcl_abs(b2[1]-cd1*b2[0]-oo1)<m_Epsilon) { resp = ( b2[0]>=xamin && b2[0]<=xamax); } - } } + } return resp; } @@ -430,44 +430,44 @@ Polygon<TValue> long int x,y; - if(this->GetVertexList()->Size()>0) - { - x = static_cast<long int>(it.Value()[0]); - y = static_cast<long int>(it.Value()[1]); - index[0] = x; - index[1] = y; - - ++it; - while(it != this->GetVertexList()->End()) + if (this->GetVertexList()->Size()>0) { x = static_cast<long int>(it.Value()[0]); y = static_cast<long int>(it.Value()[1]); + index[0] = x; + index[1] = y; - // Index search - if ( x < index[0] ) + ++it; + while (it != this->GetVertexList()->End()) + { + x = static_cast<long int>(it.Value()[0]); + y = static_cast<long int>(it.Value()[1]); + + // Index search + if ( x < index[0] ) { index[0] = x; } - if ( y < index[1] ) + if ( y < index[1] ) { index[1] = y; } - // Max Id search for size computation - if ( x > maxId[0] ) + // Max Id search for size computation + if ( x > maxId[0] ) { maxId[0] = x; } - if ( y > maxId[1] ) + if ( y > maxId[1] ) { maxId[1] = y; } - ++it; - } - - size[0] = maxId[0] - index[0]; - size[1] = maxId[1] - index[1]; + ++it; } + + size[0] = maxId[0] - index[0]; + size[1] = maxId[1] - index[1]; + } region.SetSize(size); region.SetIndex(index); return region; @@ -478,22 +478,22 @@ Polygon<TValue> * Surface computation (for non convex polygons as well) */ template<class TValue> - double - Polygon<TValue> - ::GetSurface() const +double +Polygon<TValue> +::GetSurface() const { double m_Surface; m_Surface = 0.0; VertexListConstIteratorType it = this->GetVertexList()->Begin(); - if(this->GetVertexList()->Size()>2) + if (this->GetVertexList()->Size()>2) { VertexType origin = it.Value(); it++; VertexType pt1 = it.Value(); VertexType pt2 = it.Value(); - while(it != this->GetVertexList()->End()) + while (it != this->GetVertexList()->End()) { pt1=pt2; pt2 = it.Value(); @@ -521,15 +521,15 @@ template<class TValue> /** * Lenght computation (difference with path is in the last addition) */ - template < class TValue> - double Polygon<TValue> - ::GetLength() const +template < class TValue> +double Polygon<TValue> +::GetLength() const { double length = 0.0; VertexListConstIteratorType it = this->GetVertexList()->Begin(); VertexType origin = it.Value(); - if(this->GetVertexList()->Size()>1) + if (this->GetVertexList()->Size()>1) { @@ -537,7 +537,7 @@ template<class TValue> VertexType pt2 = it.Value(); it++; - while(it != this->GetVertexList()->End()) + while (it != this->GetVertexList()->End()) { pt1=pt2; pt2 = it.Value(); diff --git a/Code/Common/otbShiftScaleImageAdaptor.h b/Code/Common/otbShiftScaleImageAdaptor.h index 1e670cde43bd8e1fc6dcd09e90317a5939982cbd..9aad505758f2d7c336a9e3860eda3ec529993f9f 100644 --- a/Code/Common/otbShiftScaleImageAdaptor.h +++ b/Code/Common/otbShiftScaleImageAdaptor.h @@ -27,7 +27,8 @@ namespace otb { -namespace Accessor { +namespace Accessor +{ /** \class ShiftScalePixelAccessor * \brief Give access to the vcl_sqrt() function of a value * @@ -55,27 +56,39 @@ public: typedef TInternalType InternalType; InternalType GetShift() - { return m_Shift; } + { + return m_Shift; + } void SetShift(InternalType value) - { m_Shift = value; } + { + m_Shift = value; + } InternalType GetScale() - { return m_Scale; } + { + return m_Scale; + } void SetScale(InternalType value) - { m_Scale = value; } + { + m_Scale = value; + } inline void Set(TInternalType & output, const TExternalType & input) // {output = (TInternalType)((double) (input));} - {output = (TInternalType)((double) m_Scale*(input+m_Shift));} + { + output = (TInternalType)((double) m_Scale*(input+m_Shift)); + } inline const TExternalType Get(const TInternalType & input) const // {return (TExternalType)((double) (input));} - {return (TExternalType)((double) m_Scale*(input+m_Shift));} + { + return (TExternalType)((double) m_Scale*(input+m_Shift)); + } - private: - InternalType m_Shift; - InternalType m_Scale; +private: + InternalType m_Shift; + InternalType m_Scale; }; @@ -92,22 +105,22 @@ public: template <class TImage, class TOutputPixelType> class ITK_EXPORT ShiftScaleImageAdaptor : public itk::ImageAdaptor<TImage, Accessor::ShiftScalePixelAccessor< - typename TImage::PixelType, - TOutputPixelType > > + typename TImage::PixelType, + TOutputPixelType > > { public: /** Standard class typedefs. */ typedef ShiftScaleImageAdaptor Self; typedef itk::ImageAdaptor<TImage,Accessor::ShiftScalePixelAccessor< - typename TImage::PixelType, - TOutputPixelType > > Superclass; + typename TImage::PixelType, + TOutputPixelType > > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef typename TImage::PixelType InternalType; typedef typename Superclass::IndexType IndexType; typedef typename Accessor::ShiftScalePixelAccessor< - typename TImage::PixelType, - TOutputPixelType > AccessorType; + typename TImage::PixelType, + TOutputPixelType > AccessorType; typedef typename AccessorType::ExternalType PixelType; /** Method for creation through the object factory. */ @@ -126,10 +139,10 @@ public: { itkDebugMacro("setting m_Shift to " << value); if (this->GetPixelAccessor().GetShift() != value) - { + { this->GetPixelAccessor().SetShift(value); this->Modified(); - } + } } typename TImage::PixelType GetScale () @@ -143,10 +156,10 @@ public: { itkDebugMacro("setting m_Scale to " << value); if (this->GetPixelAccessor().GetScale() != value) - { + { this->GetPixelAccessor().SetScale(value); this->Modified(); - } + } } protected: diff --git a/Code/Common/otbSpatialObjectSource.h b/Code/Common/otbSpatialObjectSource.h index 10e87191cc994be688c25919a94eb9dd26e51b24..22587a6e726b9ccd927351820478837207300eab 100644 --- a/Code/Common/otbSpatialObjectSource.h +++ b/Code/Common/otbSpatialObjectSource.h @@ -23,16 +23,16 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * \class SpatialObjectSource - * \brief Base class for filters producing a SpatialObject as output. - * \ingroup DataSources - */ +/** + * \class SpatialObjectSource + * \brief Base class for filters producing a SpatialObject as output. + * \ingroup DataSources + */ template <class TSpatialObject> class ITK_EXPORT SpatialObjectSource - : public itk::ProcessObject + : public itk::ProcessObject { - public: +public: /** Standard typedefs */ typedef SpatialObjectSource Self; typedef itk::ProcessObject Superclass; @@ -59,7 +59,7 @@ class ITK_EXPORT SpatialObjectSource virtual SpatialObjectType * GetOutput(void); - protected: +protected: /** Constructor */ SpatialObjectSource(); /** Destructor */ diff --git a/Code/Common/otbSpatialObjectSource.txx b/Code/Common/otbSpatialObjectSource.txx index 729c6f4da9f030b9ffa3072cfc7f5093e716c4eb..86b63c5ed8cf006130f868561628b4b8559cea57 100644 --- a/Code/Common/otbSpatialObjectSource.txx +++ b/Code/Common/otbSpatialObjectSource.txx @@ -41,10 +41,10 @@ typename SpatialObjectSource<TSpatialObject>::SpatialObjectType * SpatialObjectSource<TSpatialObject> ::GetOutput(void) { - if(this->GetNumberOfOutputs()<1) - { - return 0; - } + if (this->GetNumberOfOutputs()<1) + { + return 0; + } return static_cast<SpatialObjectType *> (this->ProcessObject::GetOutput(0)); } /** diff --git a/Code/Common/otbStandardFilterWatcher.cxx b/Code/Common/otbStandardFilterWatcher.cxx index e72798fd90410b16b579a67fd065fe77d6209713..06842dcb36f6ad400ccae6a40d07569aace5ee52 100644 --- a/Code/Common/otbStandardFilterWatcher.cxx +++ b/Code/Common/otbStandardFilterWatcher.cxx @@ -25,8 +25,8 @@ namespace otb StandardFilterWatcher ::StandardFilterWatcher(itk::ProcessObject* process, - const char *comment) - : FilterWatcherBase(process, comment) + const char *comment) + : FilterWatcherBase(process, comment) { m_StarsCount = 50; } @@ -51,12 +51,12 @@ StandardFilterWatcher ::ShowProgress() { if (m_Process) - { - int progressPercent = static_cast<int>(m_Process->GetProgress()*100); - std::string stars(static_cast<int>(m_Process->GetProgress()*m_StarsCount),'*'); - std::string blanks(static_cast<int>(m_StarsCount - m_Process->GetProgress()*m_StarsCount),' '); - std::cout << "\rProcessing progress:" << progressPercent << "% [" << stars << blanks << "]" << std::flush; - } + { + int progressPercent = static_cast<int>(m_Process->GetProgress()*100); + std::string stars(static_cast<int>(m_Process->GetProgress()*m_StarsCount),'*'); + std::string blanks(static_cast<int>(m_StarsCount - m_Process->GetProgress()*m_StarsCount),' '); + std::cout << "\rProcessing progress:" << progressPercent << "% [" << stars << blanks << "]" << std::flush; + } } void @@ -65,7 +65,7 @@ StandardFilterWatcher { m_TimeProbe.Start(); std::cout << (m_Process.GetPointer() ? m_Process->GetNameOfClass() : "None") - << " \"" << m_Comment << "\" " << std::endl; + << " \"" << m_Comment << "\" " << std::endl; } void @@ -74,8 +74,8 @@ StandardFilterWatcher { m_TimeProbe.Stop(); std::cout << std::endl << "Filter took " - << m_TimeProbe.GetMeanTime() - << " seconds." << std::endl; + << m_TimeProbe.GetMeanTime() + << " seconds." << std::endl; } } // end namespace otb diff --git a/Code/Common/otbStandardFilterWatcher.h b/Code/Common/otbStandardFilterWatcher.h index 7f98bf10ef1ac02a31e82fb4605b8cc7f571d56b..32cf3574278b2cdf5ad99a7836c9631dffb58bc0 100644 --- a/Code/Common/otbStandardFilterWatcher.h +++ b/Code/Common/otbStandardFilterWatcher.h @@ -26,61 +26,67 @@ namespace otb { - /** \class StandardFilterWatcher - * \brief This class shows the percentage progress execution - * of the pipeline filtering process - * - * This class is based on oberservers desgin patter - * Abstract class ProcessObject is the subject - * Event are oberservers - * - * Usage example: - * - * \code - * typedef itk::BinaryThresholdImageFilter<ImageType> FilterType; - * FilterType::Pointer thresholdFilter = FilterType::New(); - * - * StandardFilterWatcher watcher(thresholdFilter, "Threshold"); - * \endcode - * - * \see itk::SimpleFilterWatcher - * \see otb::fltkFilterWatcher - */ - class /*ITK_EXPORT*/ StandardFilterWatcher : public FilterWatcherBase - { - public: - - /** Constructor. Takes a ProcessObject to monitor and an optional - * comment string that is prepended to each event message. */ - StandardFilterWatcher(itk::ProcessObject* process, - const char *comment=""); - - /** Copy constructor */ - StandardFilterWatcher(const StandardFilterWatcher&); - - /** operator= */ - void operator=(const StandardFilterWatcher& ); - - /** Get/Set number of stars */ - void SetStars( int count ) { m_StarsCount = count;} - const int& GetStars() const { return m_StarsCount;} - - protected: - - /** Callback method to show the ProgressEvent */ - virtual void ShowProgress(); - - /** Callback method to show the StartEvent */ - virtual void StartFilter(); - - /** Callback method to show the EndEvent */ - virtual void EndFilter(); - - private: - - /** Stars coutning */ - int m_StarsCount; - }; +/** \class StandardFilterWatcher + * \brief This class shows the percentage progress execution + * of the pipeline filtering process + * + * This class is based on oberservers desgin patter + * Abstract class ProcessObject is the subject + * Event are oberservers + * + * Usage example: + * + * \code + * typedef itk::BinaryThresholdImageFilter<ImageType> FilterType; + * FilterType::Pointer thresholdFilter = FilterType::New(); + * + * StandardFilterWatcher watcher(thresholdFilter, "Threshold"); + * \endcode + * + * \see itk::SimpleFilterWatcher + * \see otb::fltkFilterWatcher + */ +class /*ITK_EXPORT*/ StandardFilterWatcher : public FilterWatcherBase +{ +public: + + /** Constructor. Takes a ProcessObject to monitor and an optional + * comment string that is prepended to each event message. */ + StandardFilterWatcher(itk::ProcessObject* process, + const char *comment=""); + + /** Copy constructor */ + StandardFilterWatcher(const StandardFilterWatcher&); + + /** operator= */ + void operator=(const StandardFilterWatcher& ); + + /** Get/Set number of stars */ + void SetStars( int count ) + { + m_StarsCount = count; + } + const int& GetStars() const + { + return m_StarsCount; + } + +protected: + + /** Callback method to show the ProgressEvent */ + virtual void ShowProgress(); + + /** Callback method to show the StartEvent */ + virtual void StartFilter(); + + /** Callback method to show the EndEvent */ + virtual void EndFilter(); + +private: + + /** Stars coutning */ + int m_StarsCount; +}; } // end namespace otb diff --git a/Code/Common/otbStandardWriterWatcher.cxx b/Code/Common/otbStandardWriterWatcher.cxx index af9058152529ccad113c60269c6ed3fd01c46206..161c037b58d65f1a0f74e71c3e2937da794c293b 100644 --- a/Code/Common/otbStandardWriterWatcher.cxx +++ b/Code/Common/otbStandardWriterWatcher.cxx @@ -25,16 +25,16 @@ namespace otb StandardWriterWatcher ::StandardWriterWatcher(itk::ProcessObject* process, - const char *comment) - : WriterWatcherBase(process, comment) + const char *comment) + : WriterWatcherBase(process, comment) { m_StarsCount = 50; } StandardWriterWatcher ::StandardWriterWatcher(itk::ProcessObject* process,itk::ProcessObject * source, - const char *comment) - : WriterWatcherBase(process,source,comment) + const char *comment) + : WriterWatcherBase(process,source,comment) { m_StarsCount = 50; } @@ -77,40 +77,40 @@ StandardWriterWatcher oss<<"\r"; if (m_SourceProcess) - { - double progress = m_SourceProcess->GetProgress(); - int progressPercent = static_cast<int>(progress*100); - std::string stars(static_cast<int>(progress*m_StarsCount),'*'); - std::string blanks(m_StarsCount - stars.length(),' '); - oss << "Current Tile: "; - if(progressPercent<10) - { - oss<<" "; - } - if(progressPercent<100) { - oss<<" "; - } - oss<<progressPercent << "% [" << stars << blanks << "] "; + double progress = m_SourceProcess->GetProgress(); + int progressPercent = static_cast<int>(progress*100); + std::string stars(static_cast<int>(progress*m_StarsCount),'*'); + std::string blanks(m_StarsCount - stars.length(),' '); + oss << "Current Tile: "; + if (progressPercent<10) + { + oss<<" "; } - - if (m_Process) + if (progressPercent<100) { - double progress = m_Process->GetProgress(); - int progressPercent = static_cast<int>(progress*100); - std::string stars(static_cast<int>(progress*m_StarsCount),'*'); - std::string blanks(m_StarsCount - stars.length(),' '); - oss << "Writing: "; - if(progressPercent<10) - { - oss<<" "; + oss<<" "; + } + oss<<progressPercent << "% [" << stars << blanks << "] "; } - if(progressPercent<100) + + if (m_Process) { - oss<<" "; - } - oss<< progressPercent << "% [" << stars << blanks << "]" << std::flush; + double progress = m_Process->GetProgress(); + int progressPercent = static_cast<int>(progress*100); + std::string stars(static_cast<int>(progress*m_StarsCount),'*'); + std::string blanks(m_StarsCount - stars.length(),' '); + oss << "Writing: "; + if (progressPercent<10) + { + oss<<" "; + } + if (progressPercent<100) + { + oss<<" "; } + oss<< progressPercent << "% [" << stars << blanks << "]" << std::flush; + } std::cout<<oss.str(); } @@ -132,8 +132,8 @@ StandardWriterWatcher { m_TimeProbe.Stop(); std::cout << std::endl << "Writing task took " - << m_TimeProbe.GetMeanTime() - << " seconds." << std::endl; + << m_TimeProbe.GetMeanTime() + << " seconds." << std::endl; } } // end namespace otb diff --git a/Code/Common/otbStandardWriterWatcher.h b/Code/Common/otbStandardWriterWatcher.h index 12e728e00be2e0c1f7ecb6af703034f5fc75645e..e9c491f5f4319b66d37d61e87989861734b39033 100644 --- a/Code/Common/otbStandardWriterWatcher.h +++ b/Code/Common/otbStandardWriterWatcher.h @@ -26,75 +26,81 @@ namespace otb { - /** \class StandardWriterWatcher - * \brief This class shows the percentage progress execution - * of the pipeline filtering process - * - * This class is based on oberservers desgin patter - * Abstract class ProcessObject is the subject - * Event are oberservers - * - * Usage example: - * - * \code - * typedef itk::BinaryThresholdImageWriter<ImageType> WriterType; - * WriterType::Pointer thresholdWriter = WriterType::New(); - * - * StandardWriterWatcher watcher(thresholdWriter, "Threshold"); - * \endcode - * - * \see itk::SimpleWriterWatcher - * \see otb::fltkWriterWatcher - */ - class /*ITK_EXPORT*/ StandardWriterWatcher : public WriterWatcherBase - { - public: - - /** Constructor. Takes a ProcessObject to monitor and an optional - * comment string that is prepended to each event message. */ - StandardWriterWatcher(itk::ProcessObject* process, - const char *comment=""); - StandardWriterWatcher(itk::ProcessObject* process,itk::ProcessObject * source, - const char *comment=""); - - /** Copy constructor */ - StandardWriterWatcher(const StandardWriterWatcher&); - - /** operator= */ - void operator=(const StandardWriterWatcher& ); - - /** Get/Set number of stars */ - void SetStars( int count ) { m_StarsCount = count;} - const int& GetStars() const { return m_StarsCount;} - - protected: - - /** Callback method to show the ProgressEvent */ - virtual void ShowWriterProgress(); - - /** Callback method to show the StartEvent */ - virtual void StartWriter(); - - /** Callback method to show the EndEvent */ - virtual void EndWriter(); - - /** Callback method to show the ProgressEvent */ - virtual void ShowFilterProgress(); - - /** Callback method to show the StartEvent */ - virtual void StartFilter(){}; - - /** Callback method to show the EndEvent */ - virtual void EndFilter(){}; - - /** This is the method invoked by ShowFilterProgress() and ShowWriterProgress() */ - virtual void ShowProgress(); - - private: - - /** Stars coutning */ - int m_StarsCount; - }; +/** \class StandardWriterWatcher + * \brief This class shows the percentage progress execution + * of the pipeline filtering process + * + * This class is based on oberservers desgin patter + * Abstract class ProcessObject is the subject + * Event are oberservers + * + * Usage example: + * + * \code + * typedef itk::BinaryThresholdImageWriter<ImageType> WriterType; + * WriterType::Pointer thresholdWriter = WriterType::New(); + * + * StandardWriterWatcher watcher(thresholdWriter, "Threshold"); + * \endcode + * + * \see itk::SimpleWriterWatcher + * \see otb::fltkWriterWatcher + */ +class /*ITK_EXPORT*/ StandardWriterWatcher : public WriterWatcherBase +{ +public: + + /** Constructor. Takes a ProcessObject to monitor and an optional + * comment string that is prepended to each event message. */ + StandardWriterWatcher(itk::ProcessObject* process, + const char *comment=""); + StandardWriterWatcher(itk::ProcessObject* process,itk::ProcessObject * source, + const char *comment=""); + + /** Copy constructor */ + StandardWriterWatcher(const StandardWriterWatcher&); + + /** operator= */ + void operator=(const StandardWriterWatcher& ); + + /** Get/Set number of stars */ + void SetStars( int count ) + { + m_StarsCount = count; + } + const int& GetStars() const + { + return m_StarsCount; + } + +protected: + + /** Callback method to show the ProgressEvent */ + virtual void ShowWriterProgress(); + + /** Callback method to show the StartEvent */ + virtual void StartWriter(); + + /** Callback method to show the EndEvent */ + virtual void EndWriter(); + + /** Callback method to show the ProgressEvent */ + virtual void ShowFilterProgress(); + + /** Callback method to show the StartEvent */ + virtual void StartFilter() {}; + + /** Callback method to show the EndEvent */ + virtual void EndFilter() {}; + + /** This is the method invoked by ShowFilterProgress() and ShowWriterProgress() */ + virtual void ShowProgress(); + +private: + + /** Stars coutning */ + int m_StarsCount; +}; } // end namespace otb diff --git a/Code/Common/otbStreamingTraits.h b/Code/Common/otbStreamingTraits.h index 78cbcb0fbcfe748fb30e36421d7833cc5a769d7b..0e82db00ec57cdc3dde5998883aacab063c4f0de 100644 --- a/Code/Common/otbStreamingTraits.h +++ b/Code/Common/otbStreamingTraits.h @@ -41,15 +41,15 @@ namespace otb /** * this enum defines the different streaming mode available in OTB. */ - typedef enum - { - SET_NUMBER_OF_STREAM_DIVISIONS = 1, - SET_BUFFER_MEMORY_SIZE = 2, - SET_BUFFER_NUMBER_OF_LINES = 3, - SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS = 4, - SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS = 5, - SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS = 6 - } StreamingMode; +typedef enum +{ + SET_NUMBER_OF_STREAM_DIVISIONS = 1, + SET_BUFFER_MEMORY_SIZE = 2, + SET_BUFFER_NUMBER_OF_LINES = 3, + SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS = 4, + SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS = 5, + SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS = 6 +} StreamingMode; /** \class StreamingTraits * \brief This class is a helper class for terminal streaming filter implementation. @@ -75,7 +75,7 @@ public: ImageType::ImageDimension); typedef itk::ImageRegionSplitter<itkGetStaticConstMacro(ImageDimension)> SplitterType; - // ITK Interpolators + // ITK Interpolators typedef itk::InterpolateImageFunction<TImage,double> InterpolationType; typedef itk::BSplineInterpolateImageFunction<TImage,double> BSplineInterpolationType; typedef itk::LinearInterpolateImageFunction<TImage,double> LinearInterpolationType; @@ -111,12 +111,12 @@ public: * \return The number of streaming divisions. */ static unsigned long CalculateNumberOfStreamDivisions(const TImage * image, - RegionType region, - SplitterType * splitter, - StreamingModeType mode, - unsigned long numberOfStreamDivision, - unsigned long bufferMemorySize, - unsigned long bufferNumberOfLinesDivisions); + RegionType region, + SplitterType * splitter, + StreamingModeType mode, + unsigned long numberOfStreamDivision, + unsigned long bufferMemorySize, + unsigned long bufferNumberOfLinesDivisions); static unsigned int CalculateNeededRadiusForInterpolator(const InterpolationType* interpolator); diff --git a/Code/Common/otbStreamingTraits.txx b/Code/Common/otbStreamingTraits.txx index 34701728324f91a41325daf1ebad34228cc9dabc..bab96cc09e83601435caa95e4a76f9e3cd2e3b01 100644 --- a/Code/Common/otbStreamingTraits.txx +++ b/Code/Common/otbStreamingTraits.txx @@ -31,143 +31,143 @@ namespace otb { - template <class TImage> - unsigned long StreamingTraits<TImage> - ::CalculateNumberOfStreamDivisions(const TImage * image, - RegionType region, - SplitterType * splitter, - StreamingModeType mode, - unsigned long numberOfStreamDivision, - unsigned long bufferMemorySize, - unsigned long bufferNumberOfLinesDivisions) +template <class TImage> +unsigned long StreamingTraits<TImage> +::CalculateNumberOfStreamDivisions(const TImage * image, + RegionType region, + SplitterType * splitter, + StreamingModeType mode, + unsigned long numberOfStreamDivision, + unsigned long bufferMemorySize, + unsigned long bufferNumberOfLinesDivisions) { unsigned long numDivisions(0); - switch(mode) + switch (mode) { - case SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS : // Just like SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS - case SET_NUMBER_OF_STREAM_DIVISIONS : - { - numDivisions = numberOfStreamDivision; - } - break; - case SET_BUFFER_MEMORY_SIZE : + case SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS : // Just like SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS + case SET_NUMBER_OF_STREAM_DIVISIONS : + { + numDivisions = numberOfStreamDivision; + } + break; + case SET_BUFFER_MEMORY_SIZE : + { + const unsigned long bufferMemorySizeOctet = bufferMemorySize/8; + unsigned long numberColumnsOfRegion = region.GetSize()[0]; // X dimension + const unsigned long sizeLine = numberColumnsOfRegion * \ + image->GetNumberOfComponentsPerPixel() * \ + sizeof(PixelType); + unsigned long regionSize = region.GetSize()[1] * sizeLine; + otbMsgDevMacro(<<"image->GetNumberOfComponentsPerPixel() = "<<image->GetNumberOfComponentsPerPixel()); + otbMsgDevMacro(<<"sizeof(PixelType) = "<<sizeof(PixelType)); + otbMsgDevMacro(<<"numberColumnsOfRegion = "<<numberColumnsOfRegion); + otbMsgDevMacro(<<"sizeLine = "<<sizeLine); + otbMsgDevMacro(<<"regionSize = "<<regionSize); + otbMsgDevMacro(<<"BufferMemorySize = "<<bufferMemorySize); + otbMsgDevMacro(<<"bufferMemorySizeOctet = "<<bufferMemorySizeOctet); + + //Active streaming + if ( regionSize > bufferMemorySizeOctet ) { - const unsigned long bufferMemorySizeOctet = bufferMemorySize/8; - unsigned long numberColumnsOfRegion = region.GetSize()[0]; // X dimension - const unsigned long sizeLine = numberColumnsOfRegion * \ - image->GetNumberOfComponentsPerPixel() * \ - sizeof(PixelType); - unsigned long regionSize = region.GetSize()[1] * sizeLine; - otbMsgDevMacro(<<"image->GetNumberOfComponentsPerPixel() = "<<image->GetNumberOfComponentsPerPixel()); - otbMsgDevMacro(<<"sizeof(PixelType) = "<<sizeof(PixelType)); - otbMsgDevMacro(<<"numberColumnsOfRegion = "<<numberColumnsOfRegion); - otbMsgDevMacro(<<"sizeLine = "<<sizeLine); - otbMsgDevMacro(<<"regionSize = "<<regionSize); - otbMsgDevMacro(<<"BufferMemorySize = "<<bufferMemorySize); - otbMsgDevMacro(<<"bufferMemorySizeOctet = "<<bufferMemorySizeOctet); - - //Active streaming - if( regionSize > bufferMemorySizeOctet ) - { - //The regionSize must be at list equal to the sizeLine - if( regionSize < sizeLine ) - { - otbMsgDevMacro(<<"Force buffer size."); - regionSize = sizeLine; - } - //Calculate NumberOfStreamDivisions - numDivisions = static_cast<unsigned long>( - vcl_ceil(static_cast<double>(regionSize)/static_cast<double>(bufferMemorySizeOctet)) - ); - } - else + //The regionSize must be at list equal to the sizeLine + if ( regionSize < sizeLine ) { - //Non streaming - numDivisions = 1; + otbMsgDevMacro(<<"Force buffer size."); + regionSize = sizeLine; } + //Calculate NumberOfStreamDivisions + numDivisions = static_cast<unsigned long>( + vcl_ceil(static_cast<double>(regionSize)/static_cast<double>(bufferMemorySizeOctet)) + ); + } + else + { + //Non streaming + numDivisions = 1; + } + } + break; + case SET_BUFFER_NUMBER_OF_LINES : + { + if ( bufferNumberOfLinesDivisions < 1 ) + { + itkGenericExceptionMacro(<<"Buffer number of lines division must be greater than 0 !"); } - break; - case SET_BUFFER_NUMBER_OF_LINES : + /* Calculate number of split */ + unsigned long numberLinesOfRegion = region.GetSize()[1]; // Y dimension + if ( numberLinesOfRegion > bufferNumberOfLinesDivisions ) { - if( bufferNumberOfLinesDivisions < 1 ) - { - itkGenericExceptionMacro(<<"Buffer number of lines division must be greater than 0 !"); - } - /* Calculate number of split */ - unsigned long numberLinesOfRegion = region.GetSize()[1]; // Y dimension - if( numberLinesOfRegion > bufferNumberOfLinesDivisions ) - { - numDivisions = static_cast<unsigned long>(vcl_ceil(static_cast<double>(numberLinesOfRegion)/static_cast<double>(bufferNumberOfLinesDivisions))); - } - else - { - //Non streaming - numDivisions = 1; - } + numDivisions = static_cast<unsigned long>(vcl_ceil(static_cast<double>(numberLinesOfRegion)/static_cast<double>(bufferNumberOfLinesDivisions))); } - break; - case SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS : // Just like SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS - case SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS : + else { - const unsigned long streamMaxSizeBufferForStreamingBytes = OTB_STREAM_MAX_SIZE_BUFFER_FOR_STREAMING; - const unsigned long streamImageSizeToActivateStreamingBytes = OTB_STREAM_IMAGE_SIZE_TO_ACTIVATE_STREAMING; - //Convert in octet unit - unsigned long streamMaxSizeBufferForStreaming = streamMaxSizeBufferForStreamingBytes/8; - const unsigned long streamImageSizeToActivateStreaming = streamImageSizeToActivateStreamingBytes/8; - - unsigned long numberColumnsOfRegion = region.GetSize()[0]; // X dimension - const unsigned long sizeLine = numberColumnsOfRegion * \ - image->GetNumberOfComponentsPerPixel() * \ - sizeof(PixelType); - const unsigned long regionSize = region.GetSize()[1] * sizeLine; - otbMsgDevMacro(<<"streamImageSizeToActivateStreaming in Bytes = "<<streamImageSizeToActivateStreamingBytes); - otbMsgDevMacro(<<"streamMaxSizeBufferForStreaming in Bytes = "<<streamMaxSizeBufferForStreamingBytes); - otbMsgDevMacro(<<"streamImageSizeToActivateStreaming = "<<streamImageSizeToActivateStreaming); - otbMsgDevMacro(<<"streamMaxSizeBufferForStreaming = "<<streamMaxSizeBufferForStreaming); - otbMsgDevMacro(<<"image->GetNumberOfComponentsPerPixel() = "<<image->GetNumberOfComponentsPerPixel()); - otbMsgDevMacro(<<"sizeof(PixelType) = "<<sizeof(PixelType)); - otbMsgDevMacro(<<"numberColumnsOfRegion = "<<numberColumnsOfRegion); - otbMsgDevMacro(<<"sizeLine = "<<sizeLine); - otbMsgDevMacro(<<"regionSize = "<<regionSize); - - //Active streaming - if( regionSize > streamImageSizeToActivateStreaming ) - { - //On s'assure que la taille du bandeau fait au moins une ligne de l'image si pas TILING - if( (mode != SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS) - && (streamMaxSizeBufferForStreaming < sizeLine) ) - { - otbMsgDevMacro(<<"Force buffer size."); - streamMaxSizeBufferForStreaming = sizeLine; - } - otbMsgDevMacro(<<"Buffer size : "<<streamMaxSizeBufferForStreaming); - //Calculate NumberOfStreamDivisions - numDivisions = static_cast<unsigned long>(vcl_ceil(static_cast<double>(regionSize)/static_cast<double>(streamMaxSizeBufferForStreaming))); - } - else + //Non streaming + numDivisions = 1; + } + } + break; + case SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS : // Just like SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS + case SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS : + { + const unsigned long streamMaxSizeBufferForStreamingBytes = OTB_STREAM_MAX_SIZE_BUFFER_FOR_STREAMING; + const unsigned long streamImageSizeToActivateStreamingBytes = OTB_STREAM_IMAGE_SIZE_TO_ACTIVATE_STREAMING; + //Convert in octet unit + unsigned long streamMaxSizeBufferForStreaming = streamMaxSizeBufferForStreamingBytes/8; + const unsigned long streamImageSizeToActivateStreaming = streamImageSizeToActivateStreamingBytes/8; + + unsigned long numberColumnsOfRegion = region.GetSize()[0]; // X dimension + const unsigned long sizeLine = numberColumnsOfRegion * \ + image->GetNumberOfComponentsPerPixel() * \ + sizeof(PixelType); + const unsigned long regionSize = region.GetSize()[1] * sizeLine; + otbMsgDevMacro(<<"streamImageSizeToActivateStreaming in Bytes = "<<streamImageSizeToActivateStreamingBytes); + otbMsgDevMacro(<<"streamMaxSizeBufferForStreaming in Bytes = "<<streamMaxSizeBufferForStreamingBytes); + otbMsgDevMacro(<<"streamImageSizeToActivateStreaming = "<<streamImageSizeToActivateStreaming); + otbMsgDevMacro(<<"streamMaxSizeBufferForStreaming = "<<streamMaxSizeBufferForStreaming); + otbMsgDevMacro(<<"image->GetNumberOfComponentsPerPixel() = "<<image->GetNumberOfComponentsPerPixel()); + otbMsgDevMacro(<<"sizeof(PixelType) = "<<sizeof(PixelType)); + otbMsgDevMacro(<<"numberColumnsOfRegion = "<<numberColumnsOfRegion); + otbMsgDevMacro(<<"sizeLine = "<<sizeLine); + otbMsgDevMacro(<<"regionSize = "<<regionSize); + + //Active streaming + if ( regionSize > streamImageSizeToActivateStreaming ) + { + //On s'assure que la taille du bandeau fait au moins une ligne de l'image si pas TILING + if ( (mode != SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS) + && (streamMaxSizeBufferForStreaming < sizeLine) ) { - //Non streaming - numDivisions = 1; + otbMsgDevMacro(<<"Force buffer size."); + streamMaxSizeBufferForStreaming = sizeLine; } - + otbMsgDevMacro(<<"Buffer size : "<<streamMaxSizeBufferForStreaming); + //Calculate NumberOfStreamDivisions + numDivisions = static_cast<unsigned long>(vcl_ceil(static_cast<double>(regionSize)/static_cast<double>(streamMaxSizeBufferForStreaming))); } + else + { + //Non streaming + numDivisions = 1; + } + + } + break; + default : + itkGenericExceptionMacro(<<"Method use to calculate number of stream divisions is not set !"); break; - default : - itkGenericExceptionMacro(<<"Method use to calculate number of stream divisions is not set !"); - break; } - if( numDivisions == 0) numDivisions = 1; + if ( numDivisions == 0) numDivisions = 1; otbMsgDevMacro(<<" -> Resume : method : "<<mode<<"\n -> Number of divisions = "<<numDivisions); - // Compute real number of splitter + // Compute real number of splitter unsigned int numDivisionsFromSplitter = splitter->GetNumberOfSplits(region, numDivisions); /** In tiling streaming mode, we keep the number of divisions calculed by splitter */ if ((numDivisionsFromSplitter < numDivisions) - ||(mode==SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS) - ||(mode==SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS) + ||(mode==SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS) + ||(mode==SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS) ) { numDivisions = numDivisionsFromSplitter; @@ -179,7 +179,7 @@ namespace otb template <class TImage> unsigned int StreamingTraits<TImage> - ::CalculateNeededRadiusForInterpolator(const InterpolationType* interpolator) +::CalculateNeededRadiusForInterpolator(const InterpolationType* interpolator) { unsigned int neededRadius = 0; std::string className; @@ -237,16 +237,16 @@ unsigned int StreamingTraits<TImage> neededRadius = dynamic_cast<const BlackmanInterpolationType *>(interpolator)->GetRadius(); } - /*else if (className == "WindowedSincInterpolateImageFunction") + /*else if (className == "WindowedSincInterpolateImageFunction") { itkGenericExceptionMacro(<< "Windowed Sinc Interpolator not supported yet in resample"); otbMsgDevMacro(<<"Windowed Sinc Interpolator not supported yet in resample"); -// dynamic_cast<typename itk::WindowedSincInterpolateImageFunction*>(interpolator); -} + // dynamic_cast<typename itk::WindowedSincInterpolateImageFunction*>(interpolator); + } else { itkGenericExceptionMacro(<< "Interpolator not recognized, please choose another type !"); -} */ + } */ return neededRadius; } @@ -254,31 +254,31 @@ unsigned int StreamingTraits<TImage> template <class TImage> std::string StreamingTraits<TImage> - ::GetMethodUseToCalculateNumberOfStreamDivisions( StreamingModeType mode ) +::GetMethodUseToCalculateNumberOfStreamDivisions( StreamingModeType mode ) { - switch(mode) + switch (mode) { - case SET_NUMBER_OF_STREAM_DIVISIONS: - return "CalculationDivisionEnumType::SET_NUMBER_OF_STREAM_DIVISIONS"; - break; - case SET_BUFFER_MEMORY_SIZE: - return "CalculationDivisionEnumType::SET_BUFFER_MEMORY_SIZE"; - break; - case SET_BUFFER_NUMBER_OF_LINES: - return "CalculationDivisionEnumType::SET_BUFFER_NUMBER_OF_LINES"; - break; - case SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS: - return "CalculationDivisionEnumType::SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS"; - break; - case SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS: - return "CalculationDivisionEnumType::SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS"; - break; - case SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS: - return "CalculationDivisionEnumType::SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS"; - break; - default: - return "unknown"; - break; + case SET_NUMBER_OF_STREAM_DIVISIONS: + return "CalculationDivisionEnumType::SET_NUMBER_OF_STREAM_DIVISIONS"; + break; + case SET_BUFFER_MEMORY_SIZE: + return "CalculationDivisionEnumType::SET_BUFFER_MEMORY_SIZE"; + break; + case SET_BUFFER_NUMBER_OF_LINES: + return "CalculationDivisionEnumType::SET_BUFFER_NUMBER_OF_LINES"; + break; + case SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS: + return "CalculationDivisionEnumType::SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS"; + break; + case SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS: + return "CalculationDivisionEnumType::SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS"; + break; + case SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS: + return "CalculationDivisionEnumType::SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS"; + break; + default: + return "unknown"; + break; } } diff --git a/Code/Common/otbSystem.cxx b/Code/Common/otbSystem.cxx index ee1115d8b854d0005ba5f86d2c5be5c0adbd24c7..18a1095154ef720f59730dcd50e4df1ffc18033e 100644 --- a/Code/Common/otbSystem.cxx +++ b/Code/Common/otbSystem.cxx @@ -26,17 +26,17 @@ /*===================================================================== WIN32 / MSVC++ implementation *====================================================================*/ - #ifndef WIN32CE - # include <io.h> - #else - # include <wce_io.h> - #endif +#ifndef WIN32CE +# include <io.h> +#else +# include <wce_io.h> +#endif #else /*===================================================================== POSIX (Unix) implementation *====================================================================*/ - #include <sys/types.h> - #include <dirent.h> +#include <sys/types.h> +#include <dirent.h> #endif @@ -69,19 +69,19 @@ System::GetRootName( const std::string& filename ) // Create a base filename // i.e Image.ent --> Image - if( fileExt.length() > 0 ) - { + if ( fileExt.length() > 0 ) + { const std::string::size_type it = filename.find_last_of( fileExt ); std::string baseName( filename, 0, it-fileExt.length() ); return( baseName ); - } + } //Default to return same as input when the extension is nothing (Analyze) return( filename ); } bool System::IsAFileName(const std::string& pszPath) { - return( ! IsADirName(pszPath) ); + return( ! IsADirName(pszPath) ); } @@ -108,23 +108,23 @@ System::GetShortFileName( const std::string& filename ) // Set to upper a string std::string System::SetToUpper( const std::string& str ) { - std::string lString(str); - for(unsigned int i=0; i<lString.size(); i++) - { - lString[i]=toupper(lString[i]); - } - return(lString); + std::string lString(str); + for (unsigned int i=0; i<lString.size(); i++) + { + lString[i]=toupper(lString[i]); + } + return(lString); } // Set to lower a string std::string System::SetToLower( const std::string& str ) { - std::string lString(str); - for(unsigned int i=0; i<lString.size(); i++) - { - lString[i]=tolower(lString[i]); - } - return(lString); + std::string lString(str); + for (unsigned int i=0; i<lString.size(); i++) + { + lString[i]=tolower(lString[i]); + } + return(lString); } @@ -137,54 +137,55 @@ std::string System::SetToLower( const std::string& str ) bool System::IsADirName(const std::string& pszPath) { - struct _finddata_t c_file; - long hFile; - bool isADir(false); - std::string pszFileSpec; - std::string path(pszPath); - - if (pszPath.empty() == true) - path = "."; - - pszFileSpec = path + "\\*.*"; - - if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) - { - isADir = true; - _findclose( hFile ); - } - else - { - isADir = false; - } - - return isADir; + struct _finddata_t c_file; + long hFile; + bool isADir(false); + std::string pszFileSpec; + std::string path(pszPath); + + if (pszPath.empty() == true) + path = "."; + + pszFileSpec = path + "\\*.*"; + + if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) + { + isADir = true; + _findclose( hFile ); + } + else + { + isADir = false; + } + + return isADir; } std::vector<std::string> System::Readdir(const std::string& pszPath) { - struct _finddata_t c_file; - long hFile; - std::vector<std::string> listFileFind; - std::string pszFileSpec; - std::string path(pszPath); + struct _finddata_t c_file; + long hFile; + std::vector<std::string> listFileFind; + std::string pszFileSpec; + std::string path(pszPath); - if (pszPath.empty() == true) - path = "."; + if (pszPath.empty() == true) + path = "."; - pszFileSpec = path + "\\*.*"; + pszFileSpec = path + "\\*.*"; - if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) + if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) + { + do { - do - { - listFileFind.push_back(c_file.name); - } while( _findnext( hFile, &c_file ) == 0 ); - - _findclose( hFile ); + listFileFind.push_back(c_file.name); } + while ( _findnext( hFile, &c_file ) == 0 ); + + _findclose( hFile ); + } - return listFileFind; + return listFileFind; } #else @@ -195,24 +196,24 @@ std::vector<std::string> System::Readdir(const std::string& pszPath) bool System::IsADirName(const std::string& pszPath) { - bool isADir(false); - DIR *hDir; - std::string path(pszPath); - - if (pszPath.empty() == true) - path = "."; - - if ( (hDir = opendir(path.c_str())) != NULL ) - { - isADir = true; - closedir( hDir ); - } - else - { - isADir = false; - } - - return isADir; + bool isADir(false); + DIR *hDir; + std::string path(pszPath); + + if (pszPath.empty() == true) + path = "."; + + if ( (hDir = opendir(path.c_str())) != NULL ) + { + isADir = true; + closedir( hDir ); + } + else + { + isADir = false; + } + + return isADir; } /** @@ -233,24 +234,24 @@ bool System::IsADirName(const std::string& pszPath) std::vector<std::string> System::Readdir(const std::string& pszPath) { - DIR *hDir; - std::vector<std::string> listFileFind; - struct dirent *psDirEntry; - std::string path(pszPath); + DIR *hDir; + std::vector<std::string> listFileFind; + struct dirent *psDirEntry; + std::string path(pszPath); - if (pszPath.empty() == true) - path = "."; + if (pszPath.empty() == true) + path = "."; - if ( (hDir = opendir(path.c_str())) != NULL ) + if ( (hDir = opendir(path.c_str())) != NULL ) + { + while ( (psDirEntry = readdir(hDir)) != NULL ) { - while( (psDirEntry = readdir(hDir)) != NULL ) - { - listFileFind.push_back(psDirEntry->d_name); - } - - closedir( hDir ); + listFileFind.push_back(psDirEntry->d_name); } - return listFileFind; + + closedir( hDir ); + } + return listFileFind; } #endif diff --git a/Code/Common/otbSystem.h b/Code/Common/otbSystem.h index 319dac4cb825290c00572bbc22915fe1c0b608a1..aa663689c07e1ee8c91ca48873a2752ab872be9a 100644 --- a/Code/Common/otbSystem.h +++ b/Code/Common/otbSystem.h @@ -26,9 +26,9 @@ #ifdef _WIN - #define OTB_FILE_SEPARATOR '\\' +#define OTB_FILE_SEPARATOR '\\' #else - #define OTB_FILE_SEPARATOR '/' +#define OTB_FILE_SEPARATOR '/' #endif namespace otb diff --git a/Code/Common/otbTestMain.h b/Code/Common/otbTestMain.h index 8e728f326e3c5a64c0eb8fd3ee47db494b1d75dd..530d64baecff5bd619bbff565be1e5855fbbd42b 100644 --- a/Code/Common/otbTestMain.h +++ b/Code/Common/otbTestMain.h @@ -63,7 +63,7 @@ void PrintAvailableTests() std::cout << "Tests available:\n"; std::map<std::string, MainFuncPointer>::iterator j = StringToTestFunctionMap.begin(); int i = 0; - while(j != StringToTestFunctionMap.end()) + while (j != StringToTestFunctionMap.end()) { std::cout << i << ". " << j->first << "\n"; ++i; @@ -96,7 +96,7 @@ int main(int ac, char* av[] ) RegisterTests(); std::string testToRun; - if(ac < 2) + if (ac < 2) { PrintAvailableTests(); std::cout << "To launch a test, enter its number: "; @@ -104,12 +104,12 @@ int main(int ac, char* av[] ) std::cin >> testNum; std::map<std::string, MainFuncPointer>::iterator j = StringToTestFunctionMap.begin(); int i = 0; - while(j != StringToTestFunctionMap.end() && i < testNum) + while (j != StringToTestFunctionMap.end() && i < testNum) { ++i; ++j; } - if(j == StringToTestFunctionMap.end()) + if (j == StringToTestFunctionMap.end()) { std::cerr << testNum << " is not a valid test number\n"; return -1; @@ -142,7 +142,7 @@ int main(int ac, char* av[] ) av += 4; ac -= 4; } - else if(strcmp(av[1], "--compare-n-images") == 0) + else if (strcmp(av[1], "--compare-n-images") == 0) { lFlagRegression = true; lToleranceDiffPixelImage = (double)(::atof(av[2])); @@ -151,7 +151,7 @@ int main(int ac, char* av[] ) baselineFilenamesImage.reserve(nbComparisons); testFilenamesImage.reserve(nbComparisons); // Retrieve all the file names - for(unsigned int i = 0; i<nbComparisons;i++) + for (unsigned int i = 0; i<nbComparisons;i++) { baselineFilenamesImage.push_back(av[4+2*i]); testFilenamesImage.push_back(av[5+2*i]); @@ -176,7 +176,7 @@ int main(int ac, char* av[] ) baselineFilenamesBinary.reserve(nbComparisons); testFilenamesBinary.reserve(nbComparisons); // Retrieve all the file names - for(unsigned int i = 0; i<nbComparisons;i++) + for (unsigned int i = 0; i<nbComparisons;i++) { baselineFilenamesBinary.push_back(av[3+2*i]); testFilenamesBinary.push_back(av[4+2*i]); @@ -193,12 +193,12 @@ int main(int ac, char* av[] ) baselineFilenamesAscii.push_back(av[3]); testFilenamesAscii.push_back(av[4]); - if( ac > 5 ) + if ( ac > 5 ) { if (strcmp(av[5], "--ignore-lines-with") == 0) { unsigned int nbIgnoredLines=(unsigned int)(::atoi(av[6])); - for(unsigned int i=0; i<nbIgnoredLines; i++ ) + for (unsigned int i=0; i<nbIgnoredLines; i++ ) { ignoredLines.push_back(av[7+i]); } @@ -226,7 +226,7 @@ int main(int ac, char* av[] ) baselineFilenamesAscii.reserve(nbComparisons); testFilenamesAscii.reserve(nbComparisons); // Retrieve all the file names - for(unsigned int i = 0; i<nbComparisons;i++) + for (unsigned int i = 0; i<nbComparisons;i++) { baselineFilenamesAscii.push_back(av[4+2*i]); testFilenamesAscii.push_back(av[5+2*i]); @@ -248,7 +248,7 @@ int main(int ac, char* av[] ) testToRun = av[1]; } std::map<std::string, MainFuncPointer>::iterator j = StringToTestFunctionMap.find(testToRun); - if(j != StringToTestFunctionMap.end()) + if (j != StringToTestFunctionMap.end()) { MainFuncPointer f = j->second; int result, multiResult; @@ -262,26 +262,26 @@ int main(int ac, char* av[] ) itkGenericExceptionMacro(<<"Bad function return, no regression test !"); } } - catch( itk::ExceptionObject & e ) + catch ( itk::ExceptionObject & e ) { std::cerr << "otbTestMain '"<<testToRun<<"': ITK Exception thrown:" << std::endl; std::cerr << e.GetFile() << ":" << e.GetLine() << ":"<< std::endl; std::cerr << e.GetDescription() << std::endl; result = EXIT_FAILURE; } - catch( std::bad_alloc & err ) + catch ( std::bad_alloc & err ) { std::cerr << "otbTestMain '"<<testToRun<<"': Exception bad_alloc thrown: "<< std::endl; std::cerr <<(char*)err.what()<< std::endl; result = EXIT_FAILURE; } - catch(const std::exception& e) + catch (const std::exception& e) { std::cerr << "otbTestMain '"<<testToRun<<"': std::exception thrown:"<< std::endl; std::cerr << e.what() << std::endl; result = EXIT_FAILURE; } - catch( ... ) + catch ( ... ) { std::cerr << "otbTestMain '"<<testToRun<<"': Unknown exception thrown !" << std::endl; result = EXIT_FAILURE; @@ -291,7 +291,7 @@ int main(int ac, char* av[] ) { result = 0; std::cout << " -> Test EXIT SUCCESS."<<std::endl; - if( lFlagRegression == false ) + if ( lFlagRegression == false ) { std::cout << "------------- No control baseline tests -------------"<<std::endl; } @@ -301,7 +301,7 @@ int main(int ac, char* av[] ) { std::cout << "------------- Start control baseline tests -------------"<<std::endl; - // Make a list of possible baselines + // Make a list of possible baselines // Non regression test for images if ((baselineFilenamesImage.size()>0) && (testFilenamesImage.size()>0)) @@ -311,9 +311,9 @@ int main(int ac, char* av[] ) std::vector<std::string>::iterator itTestFilenames = testFilenamesImage.begin(); int cpt(1); // For each couple of baseline and test file, do the comparison - for(;(itbaselineFilenames != baselineFilenamesImage.end()) - &&(itTestFilenames != testFilenamesImage.end()); - ++itbaselineFilenames,++itTestFilenames) + for (;(itbaselineFilenames != baselineFilenamesImage.end()) + &&(itTestFilenames != testFilenamesImage.end()); + ++itbaselineFilenames,++itTestFilenames) { std::string baselineFilenameImage = (*itbaselineFilenames); std::string testFilenameImage = (*itTestFilenames); @@ -322,13 +322,13 @@ int main(int ac, char* av[] ) std::map<std::string,int>::reverse_iterator baseline = baselines.rbegin(); multiResult = 1; std::cout<<"Number of baseline images: "<<baselines.size()<<std::endl; - while(baseline!=baselines.rend() && (multiResult!=0)) + while (baseline!=baselines.rend() && (multiResult!=0)) { std::cout<<"Testing non-regression on image: "<<(baseline->first).c_str()<<std::endl; baseline->second = RegressionTestImage(cpt,testFilenameImage.c_str(), - (baseline->first).c_str(), - 0, - lToleranceDiffPixelImage); + (baseline->first).c_str(), + 0, + lToleranceDiffPixelImage); multiResult = baseline->second; ++baseline; @@ -337,10 +337,10 @@ int main(int ac, char* av[] ) { baseline = baselines.rbegin(); baseline->second - = RegressionTestImage(cpt,testFilenameImage.c_str(), - (baseline->first).c_str(), - 1, - lToleranceDiffPixelImage); + = RegressionTestImage(cpt,testFilenameImage.c_str(), + (baseline->first).c_str(), + 1, + lToleranceDiffPixelImage); } cpt++; result += multiResult; @@ -355,9 +355,9 @@ int main(int ac, char* av[] ) std::vector<std::string>::iterator itbaselineFilenames = baselineFilenamesMetaData.begin(); std::vector<std::string>::iterator itTestFilenames = testFilenamesMetaData.begin(); // For each couple of baseline and test file, do the comparison - for(;(itbaselineFilenames != baselineFilenamesMetaData.end()) - &&(itTestFilenames != testFilenamesMetaData.end()); - ++itbaselineFilenames,++itTestFilenames) + for (;(itbaselineFilenames != baselineFilenamesMetaData.end()) + &&(itTestFilenames != testFilenamesMetaData.end()); + ++itbaselineFilenames,++itTestFilenames) { std::string baselineFilenameImage = (*itbaselineFilenames); std::string testFilenameImage = (*itTestFilenames); @@ -366,13 +366,13 @@ int main(int ac, char* av[] ) std::map<std::string,int>::reverse_iterator baseline = baselines.rbegin(); multiResult = 1; std::cout<<"Number of baseline images: "<<baselines.size()<<std::endl; - while(baseline!=baselines.rend() && (multiResult!=0)) + while (baseline!=baselines.rend() && (multiResult!=0)) { std::cout<<"Testing non-regression on image: "<<(baseline->first).c_str()<<std::endl; baseline->second = RegressionTestMetaData(testFilenameImage.c_str(), - (baseline->first).c_str(), - 0, - lToleranceDiffPixelImage); + (baseline->first).c_str(), + 0, + lToleranceDiffPixelImage); multiResult = baseline->second; ++baseline; @@ -381,10 +381,10 @@ int main(int ac, char* av[] ) { baseline = baselines.rbegin(); baseline->second - = RegressionTestMetaData(testFilenameImage.c_str(), - (baseline->first).c_str(), - 1, - lToleranceDiffPixelImage); + = RegressionTestMetaData(testFilenameImage.c_str(), + (baseline->first).c_str(), + 1, + lToleranceDiffPixelImage); } result += multiResult; } @@ -400,20 +400,20 @@ int main(int ac, char* av[] ) std::vector<std::string>::iterator itIgnoredLines = ignoredLines.begin(); // Warning message - if(ignoredLines.size() > 0 ) + if (ignoredLines.size() > 0 ) { - std::cout << "The lines containing the expressions "; - for(;itIgnoredLines!=ignoredLines.end();itIgnoredLines++) - { - std::cout << (*itIgnoredLines) <<" "; - } - std::cout << "are not considered"<< std::endl; + std::cout << "The lines containing the expressions "; + for (;itIgnoredLines!=ignoredLines.end();itIgnoredLines++) + { + std::cout << (*itIgnoredLines) <<" "; + } + std::cout << "are not considered"<< std::endl; } // For each couple of baseline and test file, do the comparison - for(;(itbaselineFilenames != baselineFilenamesAscii.end()) - &&(itTestFilenames != testFilenamesAscii.end()); - ++itbaselineFilenames,++itTestFilenames) + for (;(itbaselineFilenames != baselineFilenamesAscii.end()) + &&(itTestFilenames != testFilenamesAscii.end()); + ++itbaselineFilenames,++itTestFilenames) { std::string baselineFilenameAscii = (*itbaselineFilenames); std::string testFilenameAscii = (*itTestFilenames); @@ -422,14 +422,14 @@ int main(int ac, char* av[] ) std::map<std::string,int>::reverse_iterator baseline = baselines.rbegin(); multiResult = 1; std::cout<<"Number of baseline files: "<<baselines.size()<<std::endl; - while(baseline!=baselines.rend() && (multiResult!=0)) + while (baseline!=baselines.rend() && (multiResult!=0)) { std::cout<<"Testing non-regression on file: "<<(baseline->first).c_str()<<std::endl; baseline->second = RegressionTestAsciiFile(testFilenameAscii.c_str(), - (baseline->first).c_str(), - 0, - lEpsilon, - ignoredLines); + (baseline->first).c_str(), + 0, + lEpsilon, + ignoredLines); multiResult = baseline->second; ++baseline; @@ -438,11 +438,11 @@ int main(int ac, char* av[] ) { baseline = baselines.rbegin(); baseline->second - = RegressionTestAsciiFile(testFilenameAscii.c_str(), - (baseline->first).c_str(), - 1, - lEpsilon, - ignoredLines); + = RegressionTestAsciiFile(testFilenameAscii.c_str(), + (baseline->first).c_str(), + 1, + lEpsilon, + ignoredLines); } result += multiResult; } @@ -454,9 +454,9 @@ int main(int ac, char* av[] ) std::vector<std::string>::iterator itbaselineFilenames = baselineFilenamesBinary.begin(); std::vector<std::string>::iterator itTestFilenames = testFilenamesBinary.begin(); // For each couple of baseline and test file, do the comparison - for(;(itbaselineFilenames != baselineFilenamesBinary.end()) - &&(itTestFilenames != testFilenamesBinary.end()); - ++itbaselineFilenames,++itTestFilenames) + for (;(itbaselineFilenames != baselineFilenamesBinary.end()) + &&(itTestFilenames != testFilenamesBinary.end()); + ++itbaselineFilenames,++itTestFilenames) { std::string baselineFilenameBinary = (*itbaselineFilenames); std::string testFilenameBinary = (*itTestFilenames); @@ -465,12 +465,12 @@ int main(int ac, char* av[] ) std::map<std::string,int>::reverse_iterator baseline = baselines.rbegin(); multiResult = 1; std::cout<<"Number of baseline files: "<<baselines.size()<<std::endl; - while(baseline!=baselines.rend() && (multiResult!=0)) + while (baseline!=baselines.rend() && (multiResult!=0)) { std::cout<<"Testing non-regression on file: "<<(baseline->first).c_str()<<std::endl; baseline->second = RegressionTestBinaryFile(testFilenameBinary.c_str(), - (baseline->first).c_str(), - 0); + (baseline->first).c_str(), + 0); multiResult = baseline->second; ++baseline; @@ -479,35 +479,35 @@ int main(int ac, char* av[] ) { baseline = baselines.rbegin(); baseline->second - = RegressionTestBinaryFile(testFilenameBinary.c_str(), - (baseline->first).c_str(), - 1); + = RegressionTestBinaryFile(testFilenameBinary.c_str(), + (baseline->first).c_str(), + 1); } result += multiResult; } } } - catch( itk::ExceptionObject & e ) + catch ( itk::ExceptionObject & e ) { std::cerr << "otbTestMain 'control baseline test': ITK Exception thrown:" << std::endl; std::cerr << e.GetFile() << ":" << e.GetLine() << ":"<< std::endl; std::cerr << e.GetDescription() << std::endl; return -1; } - catch( std::bad_alloc & err ) + catch ( std::bad_alloc & err ) { std::cerr << "otbTestMain 'control baseline test': Exception bad_alloc thrown: "<< std::endl; std::cerr <<(char*)err.what()<< std::endl; return -1; } - catch(const std::exception& e) + catch (const std::exception& e) { std::cerr << "otbTestMain 'control baseline test': std::exception thrown:"<< std::endl; std::cerr << e.what() << std::endl; return -1; } - catch( ... ) + catch ( ... ) { std::cerr << "otbTestMain 'control baseline test': Unknown exception thrown !" << std::endl; return -1; @@ -562,7 +562,7 @@ bool isNumeric(std::string str) if (isNumber(number)) nbOfNumbers++; if ((!isNumber(number)&&!isPoint(number)&&!isMinusSign(number)) - ||(isMinusSign(number)&&(i!=0))) + ||(isMinusSign(number)&&(i!=0))) result = false; i++; @@ -584,26 +584,30 @@ bool isScientificNumeric(std::string str) // Analyse first character (+, -, 0...9) unsigned int cpt(0); - if( (str[0] != '+') && (str[0] != '-') && (!isNumber(number)) ) return false; - if( (str[0] == '+') || (str[0] == '-') ) { cpt++; signDetected = true; } + if ( (str[0] != '+') && (str[0] != '-') && (!isNumber(number)) ) return false; + if ( (str[0] == '+') || (str[0] == '-') ) + { + cpt++; + signDetected = true; + } - while( cpt < str.size() ) + while ( cpt < str.size() ) { if ( str[cpt] == '.' ) { - // Exit false if two points or if e already detected - if( ( pointDetected == true ) || ( eDetected == true ) ) return false; + // Exit false if two points or if e already detected + if ( ( pointDetected == true ) || ( eDetected == true ) ) return false; pointDetected = true; } else if ( ( str[cpt] == 'e' )||( str[cpt] == 'E' ) ) { - // Exit false if two e - if( eDetected == true ) return false; + // Exit false if two e + if ( eDetected == true ) return false; eDetected = true; } else if ( ( str[cpt] == '-' )||( str[cpt] == '+' ) ) { - // Exit false if already sign with no E detected + // Exit false if already sign with no E detected if ( ( signDetected == true ) && ( eDetected == false ) )return false; signDetected = true; } @@ -624,31 +628,31 @@ bool isHexaPointerAddress(std::string str) bool result(false); unsigned int start(0); //If (0xadresss) - if( (str[0]==40) && - (str[str.size()-1]==41) && - (str[1]==48) && - (str[2]==120) && - (str.size()==11)) + if ( (str[0]==40) && + (str[str.size()-1]==41) && + (str[1]==48) && + (str[2]==120) && + (str.size()==11)) { result = true; start = 3; size = str.size() - 1; } //If 0xadresss - else if( - (str[0]==48) && - (str[1]==120) && - (str.size()==9)) + else if ( + (str[0]==48) && + (str[1]==120) && + (str.size()==9)) { result = true; start = 2; size = str.size(); } // if 01adress - else if( - (str[0]==48) && - (str[1]==49) && - (str.size()==8)) + else if ( + (str[0]==48) && + (str[1]==49) && + (str.size()==8)) { result = true; start = 2; @@ -656,7 +660,7 @@ bool isHexaPointerAddress(std::string str) } unsigned int i(start); - while(result&&(i<size)) + while (result&&(i<size)) { result=result&&isHexaNumber(str[i]); ++i; @@ -670,11 +674,11 @@ std::string VectorToString(otb::ImageBase::VectorType vector) oss.str(""); otb::ImageBase::VectorType::iterator it = vector.begin(); oss<<"["; - while(it!=vector.end()) + while (it!=vector.end()) { oss<<(*it); ++it; - if(it==vector.end()) + if (it==vector.end()) { oss<<"]"; break; @@ -696,7 +700,7 @@ int RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselin std::string diffAsciiFileName(testAsciiFileName); diffAsciiFileName += ".diff.txt"; std::ofstream fluxfilediff; - if( reportErrors ) + if ( reportErrors ) { fluxfilediff.open(diffAsciiFileName.c_str()); } @@ -734,224 +738,224 @@ int RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselin buffstreamRef >> strRef; fluxfilediff << "Line missing in test file: " << numLine - << " : " << strRef - << std::endl; + << " : " << strRef + << std::endl; nbdiff++; } else { - bool foundexpr = false; - if(ignoredLines.size()>0) - { + bool foundexpr = false; + if (ignoredLines.size()>0) + { std::vector<std::string>::iterator itIgnoredLines = ignoredLines.begin(); - for(;(itIgnoredLines != ignoredLines.end()); ++itIgnoredLines) + for (;(itIgnoredLines != ignoredLines.end()); ++itIgnoredLines) { - std::string ignoredLinesAscii = (*itIgnoredLines); - std::string::size_type loc = strfileref.find(ignoredLinesAscii); - if( loc != std::string::npos ) - { - foundexpr = true; - } + std::string ignoredLinesAscii = (*itIgnoredLines); + std::string::size_type loc = strfileref.find(ignoredLinesAscii); + if ( loc != std::string::npos ) + { + foundexpr = true; + } } - } - - if( foundexpr == false ) - { - buffstreamTest << strfiletest; - int nblinediff(0); + } - while (buffstreamRef.peek() != EOF) + if ( foundexpr == false ) { - std::string strRef = ""; - std::string strTest = ""; - - std::string strNumRef = ""; - std::string strCharRef = ""; - std::string strNumTest = ""; - std::string strCharTest = ""; - - buffstreamRef >> strRef; - buffstreamTest >> strTest; - - bool chgt= false; - std::string charTmpRef = ""; - std::string charTmpTest = ""; - unsigned int i=0; - if(!isHexaPointerAddress(strRef)) + buffstreamTest << strfiletest; + int nblinediff(0); + + while (buffstreamRef.peek() != EOF) { - //Analyse if strRef contains scientific value (ex: "-142.124e-012") - if(isScientificNumeric(strRef)) + std::string strRef = ""; + std::string strTest = ""; + + std::string strNumRef = ""; + std::string strCharRef = ""; + std::string strNumTest = ""; + std::string strCharTest = ""; + + buffstreamRef >> strRef; + buffstreamTest >> strTest; + + bool chgt= false; + std::string charTmpRef = ""; + std::string charTmpTest = ""; + unsigned int i=0; + if (!isHexaPointerAddress(strRef)) { - if(!isScientificNumeric(strTest)) + //Analyse if strRef contains scientific value (ex: "-142.124e-012") + if (isScientificNumeric(strRef)) { - if( reportErrors ) + if (!isScientificNumeric(strTest)) { - fluxfilediff << "Diff at line " << numLine << " : compare numeric value with no numeric value ("<<strRef - << strRef << " != " << strTest <<")"<< std::endl; - nblinediff++; - } - nbdiff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine << " : compare numeric value with no numeric value ("<<strRef + << strRef << " != " << strTest <<")"<< std::endl; + nblinediff++; + } + nbdiff++; - } - else if ( (strRef != strTest) && (vcl_abs(atof(strRef.c_str())-atof(strTest.c_str())) > epsilon) ) - { - if( reportErrors ) + } + else if ( (strRef != strTest) && (vcl_abs(atof(strRef.c_str())-atof(strTest.c_str())) > epsilon) ) { - fluxfilediff << "Diff at line " << numLine << " : vcl_abs ( (" - << strRef << ") - (" << strTest - << ") ) > " << epsilon << std::endl; - nblinediff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine << " : vcl_abs ( (" + << strRef << ") - (" << strTest + << ") ) > " << epsilon << std::endl; + nblinediff++; + } + nbdiff++; } - nbdiff++; } - } - else - { - while (i < strRef.size()) + else { - charTmpRef=strRef[i]; - - if(i<strTest.size()) + while (i < strRef.size()) { - charTmpTest=strTest[i]; - } + charTmpRef=strRef[i]; - if (isNumeric(charTmpRef)) - etatCour = ETAT_NUM; - else - etatCour = ETAT_CHAR; + if (i<strTest.size()) + { + charTmpTest=strTest[i]; + } - // "reference" state initialisation. - if (i==0) - etatPrec=etatCour; + if (isNumeric(charTmpRef)) + etatCour = ETAT_NUM; + else + etatCour = ETAT_CHAR; - // Case where there's a number after characteres. - if ((etatCour==ETAT_NUM)&&(etatPrec==ETAT_CHAR)) - { - if ( strCharRef != strCharTest ) + // "reference" state initialisation. + if (i==0) + etatPrec=etatCour; + + // Case where there's a number after characteres. + if ((etatCour==ETAT_NUM)&&(etatPrec==ETAT_CHAR)) { - if( reportErrors ) + if ( strCharRef != strCharTest ) { - fluxfilediff << "Diff at line " << numLine - << " : " << strCharRef - << " != " << strCharTest << std::endl; - nblinediff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine + << " : " << strCharRef + << " != " << strCharTest << std::endl; + nblinediff++; + } + nbdiff++; } - nbdiff++; - } - strCharRef=""; - strCharTest=""; - strNumRef=charTmpRef; - strNumTest=charTmpTest; - chgt=true; - } - // Case where there's a character after numbers. - else if ((etatCour==ETAT_CHAR)&&(etatPrec==ETAT_NUM)) - { - - if ( (strNumRef != strNumTest) && (vcl_abs(atof(strNumRef.c_str())-atof(strNumTest.c_str())) > epsilon) ) + strCharRef=""; + strCharTest=""; + strNumRef=charTmpRef; + strNumTest=charTmpTest; + chgt=true; + } + // Case where there's a character after numbers. + else if ((etatCour==ETAT_CHAR)&&(etatPrec==ETAT_NUM)) { - if( reportErrors ) + + if ( (strNumRef != strNumTest) && (vcl_abs(atof(strNumRef.c_str())-atof(strNumTest.c_str())) > epsilon) ) { - fluxfilediff << "Diff at line " << numLine << " : vcl_abs ( (" - << strNumRef << ") - (" << strNumTest - << ") ) > " << epsilon << std::endl; - nblinediff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine << " : vcl_abs ( (" + << strNumRef << ") - (" << strNumTest + << ") ) > " << epsilon << std::endl; + nblinediff++; + } + nbdiff++; } - nbdiff++; - } - strNumRef=""; - strNumTest=""; - strCharRef=charTmpRef; - strCharTest=charTmpTest; - chgt=true; - } - else if (etatCour==etatPrec) - { - if (etatCour==ETAT_CHAR) - { - strCharRef+=charTmpRef; - strCharTest+=charTmpTest; + strNumRef=""; + strNumTest=""; + strCharRef=charTmpRef; + strCharTest=charTmpTest; + chgt=true; } - else + else if (etatCour==etatPrec) { - strNumRef+=charTmpRef; - strNumTest+=charTmpTest; + if (etatCour==ETAT_CHAR) + { + strCharRef+=charTmpRef; + strCharTest+=charTmpTest; + } + else + { + strNumRef+=charTmpRef; + strNumTest+=charTmpTest; + } } - } - etatPrec = etatCour; - i++; - } + etatPrec = etatCour; + i++; + } - // Simpliest case : string characters or numeric value between 2 separators - if (!chgt) - { - if (isNumeric(strRef)) + // Simpliest case : string characters or numeric value between 2 separators + if (!chgt) { - - if ( ( strRef != strTest) && (vcl_abs(atof(strRef.c_str())-atof(strTest.c_str())) > epsilon)) + if (isNumeric(strRef)) { - if( reportErrors ) + + if ( ( strRef != strTest) && (vcl_abs(atof(strRef.c_str())-atof(strTest.c_str())) > epsilon)) { - fluxfilediff << "Diff at line " << numLine << " : vcl_abs( (" - << strRef << ") - (" << strTest - << ") ) > " << epsilon << std::endl; - nblinediff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine << " : vcl_abs( (" + << strRef << ") - (" << strTest + << ") ) > " << epsilon << std::endl; + nblinediff++; + } + nbdiff++; } - nbdiff++; } - } - else - { - if ( strRef != strTest ) + else { - if( reportErrors ) + if ( strRef != strTest ) { - fluxfilediff << "Diff at line " << numLine - << " : " << strRef - << " != " << strTest << std::endl; - nblinediff++; + if ( reportErrors ) + { + fluxfilediff << "Diff at line " << numLine + << " : " << strRef + << " != " << strTest << std::endl; + nblinediff++; + } + nbdiff++; } - nbdiff++; } } - } - } // else - } // if(!isHexaPointerAddress(strRef)) - else - { - if( reportErrors ) + } // else + } // if(!isHexaPointerAddress(strRef)) + else { - fluxfilediff<<"Pointer address found at line "<<numLine - <<" : "<<strRef - <<" -> comparison skipped."<<std::endl; + if ( reportErrors ) + { + fluxfilediff<<"Pointer address found at line "<<numLine + <<" : "<<strRef + <<" -> comparison skipped."<<std::endl; + } } } - } - numLine++; - //Store alls differences lines - if ( nblinediff!=0 && reportErrors) - { - listStrDiffLineFileRef.push_back(strfileref); - listStrDiffLineFileTest.push_back(strfiletest); - } + numLine++; + //Store alls differences lines + if ( nblinediff!=0 && reportErrors) + { + listStrDiffLineFileRef.push_back(strfileref); + listStrDiffLineFileTest.push_back(strfiletest); + } - } + } } } - while(std::getline(fluxfiletest,strfiletest) != 0) + while (std::getline(fluxfiletest,strfiletest) != 0) { int nblinediff(0); otb::StringStream buffstreamTest; @@ -959,8 +963,8 @@ int RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselin buffstreamTest << strfiletest; buffstreamTest >> strTest; fluxfilediff << "Additional line in test file: " << numLine - << " : " << strTest - << std::endl; + << " : " << strTest + << std::endl; nblinediff++; nbdiff++; if ( nblinediff!=0 && reportErrors) @@ -973,7 +977,7 @@ int RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselin fluxfiletest.close(); fluxfileref.close(); - if( reportErrors ) + if ( reportErrors ) { fluxfilediff.close(); } @@ -990,7 +994,7 @@ int RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselin std::cout << "Tolerance value : "<<epsilon << std::endl; std::cout << "Nb lines differents : "<<listStrDiffLineFileRef.size() << std::endl; - for( unsigned int i = 0; i < listStrDiffLineFileRef.size(); i++) + for ( unsigned int i = 0; i < listStrDiffLineFileRef.size(); i++) { std::cout << " -------------------------------"<<std::endl; std::cout << " Base << "<<listStrDiffLineFileRef[i]<<std::endl; @@ -1005,7 +1009,7 @@ int RegressionTestBinaryFile(const char * testBinaryFileName, const char * basel int nbdiff(0); std::ifstream fluxfiletest(testBinaryFileName,std::ifstream::binary); std::ifstream fluxfileref(baselineBinaryFileName,std::ifstream::binary); - while( !fluxfiletest.eof() && !fluxfileref.eof() ) + while ( !fluxfiletest.eof() && !fluxfileref.eof() ) { if ( fluxfiletest.get() != fluxfileref.get() ) { @@ -1044,7 +1048,7 @@ int RegressionTestImage (int cpt, const char *testImageFilename, const char *bas catch (itk::ExceptionObject& e) { itkGenericExceptionMacro(<< "Exception detected while reading " - << baselineImageFilename << " : " << e.GetDescription()); + << baselineImageFilename << " : " << e.GetDescription()); return 1000; } @@ -1058,7 +1062,7 @@ int RegressionTestImage (int cpt, const char *testImageFilename, const char *bas catch (itk::ExceptionObject& e) { itkGenericExceptionMacro(<< "Exception detected while reading " - << testImageFilename << " : " << e.GetDescription() ); + << testImageFilename << " : " << e.GetDescription() ); return 1000; } @@ -1072,9 +1076,9 @@ int RegressionTestImage (int cpt, const char *testImageFilename, const char *bas { std::cerr << "The size of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has size " << baselineSize << std::endl; + << " has size " << baselineSize << std::endl; std::cerr << "Test image: " << testImageFilename - << " has size " << testSize << std::endl; + << " has size " << testSize << std::endl; return 1; } @@ -1091,11 +1095,11 @@ int RegressionTestImage (int cpt, const char *testImageFilename, const char *bas unsigned long numberOfPixelsWithDifferences = diff->GetNumberOfPixelsWithDifferences(); //Write only one this message - if(reportErrors == 0) + if (reportErrors == 0) { otbGenericMsgDebugMacro(<< "RegressionTestImage DifferenceThreshold: "<<toleranceDiffPixelImage); otbGenericMsgDebugMacro(<< "Status diff->GetTotalDifference: " - << status <<" for "<<numberOfPixelsWithDifferences<<" pixel(s)." ); + << status <<" for "<<numberOfPixelsWithDifferences<<" pixel(s)." ); } // if there are discrepencies, create an diff image if (status.GetSquaredNorm()>0 && reportErrors) @@ -1123,89 +1127,89 @@ int RegressionTestImage (int cpt, const char *testImageFilename, const char *bas std::cout << toleranceDiffPixelImage; std::cout << "</DartMeasurement>" << std::endl; - ::itk::OStringStream diffName; - diffName << testImageFilename << ".diff.png"; - try - { - rescale->SetInput(diff->GetOutput()); - - for(unsigned int i = 1;i<=min(diff->GetOutput()->GetNumberOfComponentsPerPixel(),3U);++i) - { - rescale->SetChannel(i); - } + ::itk::OStringStream diffName; + diffName << testImageFilename << ".diff.png"; + try + { + rescale->SetInput(diff->GetOutput()); - rescale->Update(); - } - catch (...) - { - itkGenericExceptionMacro(<< "Error during rescale of " << diffName.str() ); - } - writer->SetFileName(diffName.str().c_str()); - try - { - writer->Update(); - } - catch (...) + for (unsigned int i = 1;i<=min(diff->GetOutput()->GetNumberOfComponentsPerPixel(),3U);++i) { - itkGenericExceptionMacro(<< "Error during write of " << diffName.str() ); + rescale->SetChannel(i); } + rescale->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<< "Error during rescale of " << diffName.str() ); + } + writer->SetFileName(diffName.str().c_str()); + try + { + writer->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<< "Error during write of " << diffName.str() ); + } + // std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"; - std::cout << "<DartMeasurementFile name=\"DifferenceImage "<<cpt<<"\" type=\"image/png\">"; - std::cout << diffName.str(); - std::cout << "</DartMeasurementFile>" << std::endl; + std::cout << "<DartMeasurementFile name=\"DifferenceImage "<<cpt<<"\" type=\"image/png\">"; + std::cout << diffName.str(); + std::cout << "</DartMeasurementFile>" << std::endl; - ::itk::OStringStream baseName; - baseName << testImageFilename << ".base.png"; - try - { - rescale->SetInput(baselineReader->GetOutput()); - rescale->Update(); - } - catch (...) - { - itkGenericExceptionMacro(<<"Error during rescale of " << baseName.str() ); - } - try - { - writer->SetFileName(baseName.str().c_str()); - writer->Update(); - } - catch (...) - { - itkGenericExceptionMacro(<<"Error during write of " << baseName.str() ); - } + ::itk::OStringStream baseName; + baseName << testImageFilename << ".base.png"; + try + { + rescale->SetInput(baselineReader->GetOutput()); + rescale->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<<"Error during rescale of " << baseName.str() ); + } + try + { + writer->SetFileName(baseName.str().c_str()); + writer->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<<"Error during write of " << baseName.str() ); + } // std::cout << "<DartMeasurementFile name=\"baselineImage\" type=\"image/png\">"; - std::cout << "<DartMeasurementFile name=\"baselineImage "<<cpt<<"\" type=\"image/png\">"; - std::cout << baseName.str(); - std::cout << "</DartMeasurementFile>" << std::endl; + std::cout << "<DartMeasurementFile name=\"baselineImage "<<cpt<<"\" type=\"image/png\">"; + std::cout << baseName.str(); + std::cout << "</DartMeasurementFile>" << std::endl; - ::itk::OStringStream testName; - testName << testImageFilename << ".test.png"; - try - { - rescale->SetInput(testReader->GetOutput()); - rescale->Update(); - } - catch (...) - { - itkGenericExceptionMacro(<< "Error during rescale of " << testName.str()); - } - try - { - writer->SetFileName(testName.str().c_str()); - writer->Update(); - } - catch (...) - { - itkGenericExceptionMacro(<<"Error during write of " << testName.str() ); - } + ::itk::OStringStream testName; + testName << testImageFilename << ".test.png"; + try + { + rescale->SetInput(testReader->GetOutput()); + rescale->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<< "Error during rescale of " << testName.str()); + } + try + { + writer->SetFileName(testName.str().c_str()); + writer->Update(); + } + catch (...) + { + itkGenericExceptionMacro(<<"Error during write of " << testName.str() ); + } // std::cout << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">"; - std::cout << "<DartMeasurementFile name=\"TestImage "<<cpt<<"\" type=\"image/png\">"; - std::cout << testName.str(); - std::cout << "</DartMeasurementFile>" << std::endl; + std::cout << "<DartMeasurementFile name=\"TestImage "<<cpt<<"\" type=\"image/png\">"; + std::cout << testName.str(); + std::cout << "</DartMeasurementFile>" << std::endl; } @@ -1228,10 +1232,10 @@ int RegressionTestMetaData (const char *testImageFilename, const char *baselineI catch (itk::ExceptionObject& e) { itkGenericExceptionMacro(<< "Exception detected while reading " - << baselineImageFilename << " : " << e.GetDescription()); + << baselineImageFilename << " : " << e.GetDescription()); } - // Read the baseline file + // Read the baseline file ReaderType::Pointer testReader = ReaderType::New(); testReader->SetFileName(testImageFilename); try @@ -1241,7 +1245,7 @@ int RegressionTestMetaData (const char *testImageFilename, const char *baselineI catch (itk::ExceptionObject& e) { itkGenericExceptionMacro(<< "Exception detected while reading " - << baselineImageFilename << " : " << e.GetDescription()); + << baselineImageFilename << " : " << e.GetDescription()); } unsigned int errcount = 0; @@ -1255,129 +1259,129 @@ int RegressionTestMetaData (const char *testImageFilename, const char *baselineI { std::cerr << "The size of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has size " << baselineSize << std::endl; + << " has size " << baselineSize << std::endl; std::cerr << "Test image: " << testImageFilename - << " has size " << testSize << std::endl; + << " has size " << testSize << std::endl; errcount++; } ImageType::Pointer blImPtr = baselineReader->GetOutput(); ImageType::Pointer testImPtr = testReader->GetOutput(); // test orgin - if(blImPtr->GetOrigin()!=testImPtr->GetOrigin()) + if (blImPtr->GetOrigin()!=testImPtr->GetOrigin()) { std::cerr << "The origin of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has origin " << blImPtr->GetOrigin() << std::endl; + << " has origin " << blImPtr->GetOrigin() << std::endl; std::cerr << "Test image: " << testImageFilename - << " has origin "<< testImPtr->GetOrigin() << std::endl; + << " has origin "<< testImPtr->GetOrigin() << std::endl; errcount++; } // test spacing - if(blImPtr->GetSpacing()!=testImPtr->GetSpacing()) + if (blImPtr->GetSpacing()!=testImPtr->GetSpacing()) { std::cerr << "The spacing of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has spacing " << blImPtr->GetSpacing() << std::endl; + << " has spacing " << blImPtr->GetSpacing() << std::endl; std::cerr << "Test image: " << testImageFilename - << " has spacing "<< testImPtr->GetSpacing() << std::endl; + << " has spacing "<< testImPtr->GetSpacing() << std::endl; errcount++; } // test projection reference - if(blImPtr->GetProjectionRef().compare(testImPtr->GetProjectionRef())!=0) + if (blImPtr->GetProjectionRef().compare(testImPtr->GetProjectionRef())!=0) { std::cerr << "The projection reference of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has projection reference " << blImPtr->GetProjectionRef() << std::endl; + << " has projection reference " << blImPtr->GetProjectionRef() << std::endl; std::cerr << "Test image: " << testImageFilename - << " has projection reference " << testImPtr->GetProjectionRef() << std::endl; + << " has projection reference " << testImPtr->GetProjectionRef() << std::endl; errcount++; } // test Geographic transform - if(blImPtr->GetGeoTransform()!=testImPtr->GetGeoTransform()) + if (blImPtr->GetGeoTransform()!=testImPtr->GetGeoTransform()) { std::cerr << "The geographic transform of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has geographic transform " << VectorToString(blImPtr->GetGeoTransform()) << std::endl; + << " has geographic transform " << VectorToString(blImPtr->GetGeoTransform()) << std::endl; std::cerr << "Test image: " << testImageFilename - << " has geographic transform " << VectorToString(testImPtr->GetGeoTransform()) << std::endl; + << " has geographic transform " << VectorToString(testImPtr->GetGeoTransform()) << std::endl; errcount++; } // test upper left corner - if(blImPtr->GetUpperLeftCorner()!=testImPtr->GetUpperLeftCorner()) + if (blImPtr->GetUpperLeftCorner()!=testImPtr->GetUpperLeftCorner()) { std::cerr << "The upper left corner of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has upper left corner " << VectorToString(blImPtr->GetUpperLeftCorner()) << std::endl; + << " has upper left corner " << VectorToString(blImPtr->GetUpperLeftCorner()) << std::endl; std::cerr << "Test image: " << testImageFilename - << " has upper left corner " <<VectorToString( testImPtr->GetUpperLeftCorner()) << std::endl; + << " has upper left corner " <<VectorToString( testImPtr->GetUpperLeftCorner()) << std::endl; errcount++; } // test upper right corner - if(blImPtr->GetUpperRightCorner()!=testImPtr->GetUpperRightCorner()) + if (blImPtr->GetUpperRightCorner()!=testImPtr->GetUpperRightCorner()) { std::cerr << "The upper right corner of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has upper right corner " <<VectorToString( blImPtr->GetUpperRightCorner()) << std::endl; + << " has upper right corner " <<VectorToString( blImPtr->GetUpperRightCorner()) << std::endl; std::cerr << "Test image: " << testImageFilename - << " has upper right corner " << VectorToString(testImPtr->GetUpperRightCorner()) << std::endl; + << " has upper right corner " << VectorToString(testImPtr->GetUpperRightCorner()) << std::endl; errcount++; } // test lower left corner - if(blImPtr->GetLowerLeftCorner()!=testImPtr->GetLowerLeftCorner()) + if (blImPtr->GetLowerLeftCorner()!=testImPtr->GetLowerLeftCorner()) { std::cerr << "The lower left corner of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has lower left corner " << VectorToString(blImPtr->GetLowerLeftCorner()) << std::endl; + << " has lower left corner " << VectorToString(blImPtr->GetLowerLeftCorner()) << std::endl; std::cerr << "Test image: " << testImageFilename - << " has lower left corner " << VectorToString(testImPtr->GetLowerLeftCorner()) << std::endl; + << " has lower left corner " << VectorToString(testImPtr->GetLowerLeftCorner()) << std::endl; errcount++; } // test lower right corner - if(blImPtr->GetLowerRightCorner()!=testImPtr->GetLowerRightCorner()) + if (blImPtr->GetLowerRightCorner()!=testImPtr->GetLowerRightCorner()) { std::cerr << "The lower right of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has lower right corner " << VectorToString(blImPtr->GetLowerRightCorner()) << std::endl; + << " has lower right corner " << VectorToString(blImPtr->GetLowerRightCorner()) << std::endl; std::cerr << "Test image: " << testImageFilename - << " has lower right corner " << VectorToString(testImPtr->GetLowerRightCorner()) << std::endl; + << " has lower right corner " << VectorToString(testImPtr->GetLowerRightCorner()) << std::endl; errcount++; } // test gcp projection - if(blImPtr->GetGCPProjection().compare(testImPtr->GetGCPProjection())!=0) + if (blImPtr->GetGCPProjection().compare(testImPtr->GetGCPProjection())!=0) { std::cerr << "The gcp projection of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has gcp projection " << blImPtr->GetGCPProjection() << std::endl; + << " has gcp projection " << blImPtr->GetGCPProjection() << std::endl; std::cerr << "Test image: " << testImageFilename - << " has gcp projection " << testImPtr->GetGCPProjection() << std::endl; + << " has gcp projection " << testImPtr->GetGCPProjection() << std::endl; errcount++; } // test gcp count - if(blImPtr->GetGCPCount()!=testImPtr->GetGCPCount()) + if (blImPtr->GetGCPCount()!=testImPtr->GetGCPCount()) { std::cerr << "The gcp count of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has gcp count " << blImPtr->GetGCPCount() << std::endl; + << " has gcp count " << blImPtr->GetGCPCount() << std::endl; std::cerr << "Test image: " << testImageFilename - << " has gcp count " << testImPtr->GetGCPCount() << std::endl; + << " has gcp count " << testImPtr->GetGCPCount() << std::endl; errcount++; } else { - for(unsigned int i=0;i<blImPtr->GetGCPCount();++i) + for (unsigned int i=0;i<blImPtr->GetGCPCount();++i) { - if((blImPtr->GetGCPId(i).compare(testImPtr->GetGCPId(i))!=0) + if ((blImPtr->GetGCPId(i).compare(testImPtr->GetGCPId(i))!=0) ||(blImPtr->GetGCPInfo(i).compare(testImPtr->GetGCPInfo(i))!=0) ||(blImPtr->GetGCPRow(i)!=testImPtr->GetGCPRow(i)) ||(blImPtr->GetGCPCol(i)!=testImPtr->GetGCPCol(i)) @@ -1387,28 +1391,28 @@ int RegressionTestMetaData (const char *testImageFilename, const char *baselineI { std::cerr << "The GCP number "<<i<<" of the baseline image and Test image do not match!" << std::endl; std::cerr << "baseline image: " << baselineImageFilename - << " has gcp number "<<i<<" (" - <<"id: "<<blImPtr->GetGCPId(i)<<", " - <<"info: "<<blImPtr->GetGCPInfo(i)<<", " - <<"row: "<<blImPtr->GetGCPRow(i)<<", " - <<"col: "<<blImPtr->GetGCPCol(i)<<", " - <<"X: "<<blImPtr->GetGCPX(i)<<", " - <<"Y: "<<blImPtr->GetGCPY(i)<<", " - <<"Z: "<<blImPtr->GetGCPZ(i)<<")"<<std::endl; + << " has gcp number "<<i<<" (" + <<"id: "<<blImPtr->GetGCPId(i)<<", " + <<"info: "<<blImPtr->GetGCPInfo(i)<<", " + <<"row: "<<blImPtr->GetGCPRow(i)<<", " + <<"col: "<<blImPtr->GetGCPCol(i)<<", " + <<"X: "<<blImPtr->GetGCPX(i)<<", " + <<"Y: "<<blImPtr->GetGCPY(i)<<", " + <<"Z: "<<blImPtr->GetGCPZ(i)<<")"<<std::endl; std::cerr << "Test image: " << testImageFilename - << " has gcp number "<<i<<" (" - <<"id: "<<testImPtr->GetGCPId(i)<<", " - <<"info: "<<testImPtr->GetGCPInfo(i)<<", " - <<"row: "<<testImPtr->GetGCPRow(i)<<", " - <<"col: "<<testImPtr->GetGCPCol(i)<<", " - <<"X: "<<testImPtr->GetGCPX(i)<<", " - <<"Y: "<<testImPtr->GetGCPY(i)<<", " - <<"Z: "<<testImPtr->GetGCPZ(i)<<")"<<std::endl; + << " has gcp number "<<i<<" (" + <<"id: "<<testImPtr->GetGCPId(i)<<", " + <<"info: "<<testImPtr->GetGCPInfo(i)<<", " + <<"row: "<<testImPtr->GetGCPRow(i)<<", " + <<"col: "<<testImPtr->GetGCPCol(i)<<", " + <<"X: "<<testImPtr->GetGCPX(i)<<", " + <<"Y: "<<testImPtr->GetGCPY(i)<<", " + <<"Z: "<<testImPtr->GetGCPZ(i)<<")"<<std::endl; errcount++; } } } - if(errcount>0) + if (errcount>0) { std::cout << "<DartMeasurement name=\"MetadataError\" type=\"numeric/int\">"; std::cout << errcount; @@ -1443,15 +1447,15 @@ std::map<std::string,int> RegressionTestbaselines (char *baselineFilename) } while (++x) { - ::itk::OStringStream filename; - filename << originalBaseline << "." << x << suffix; - std::ifstream filestream(filename.str().c_str()); - if (!filestream) - { - break; - } - baselines[filename.str()] = 0; - filestream.close(); + ::itk::OStringStream filename; + filename << originalBaseline << "." << x << suffix; + std::ifstream filestream(filename.str().c_str()); + if (!filestream) + { + break; + } + baselines[filename.str()] = 0; + filestream.close(); } return baselines; } diff --git a/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.h b/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.h index 55996fb3f4089ec702c8cce0d0d2d8aa6fcba0d5..a096dbc23f10b7ffbdcd4545837ae20646989b0e 100644 --- a/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.h +++ b/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.h @@ -23,7 +23,8 @@ #include "itkConstNeighborhoodIterator.h" #include "itkProcessObject.h" -namespace otb { +namespace otb +{ /** \class UnaryFunctorNeighborhoodImageFilter * \brief Implements neighborhood-wise generic operation on image * @@ -35,7 +36,7 @@ namespace otb { */ template <class TInputImage, class TOutputImage, class TFunction > class ITK_EXPORT UnaryFunctorNeighborhoodImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { public: /** Standard class typedefs. */ @@ -75,15 +76,18 @@ public: * SmartPointer.) */ FunctorType& GetFunctor() { - this->Modified(); - return m_Functor; + this->Modified(); + return m_Functor; } /** Get the functor object. The functor is returned by reference. * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - const FunctorType& GetFunctor() const { return m_Functor; }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a diff --git a/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.txx b/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.txx index d42e040e96efae384216b7cba67bb3bfee88d833..0747a31db9c354c114fb4eeba52d3d64c502e14b 100644 --- a/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.txx +++ b/Code/Common/otbUnaryFunctorNeighborhoodImageFilter.txx @@ -53,9 +53,9 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage,TOutputImage,TFunction> typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage::RegionType inputRequestedRegion; @@ -66,12 +66,12 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage,TOutputImage,TFunction> // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -82,12 +82,12 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage,TOutputImage,TFunction> itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << this->GetNameOfClass() - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } /** @@ -104,7 +104,7 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage, TOutputImage, TFunction> // ImageToImageFilter::GetInput(int) always returns a pointer to a // TInputImage so it cannot be used for the second input. InputImagePointer inputPtr - = dynamic_cast<const TInputImage*>(ProcessObjectType::GetInput(0)); + = dynamic_cast<const TInputImage*>(ProcessObjectType::GetInput(0)); OutputImagePointer outputPtr = this->GetOutput(0); RadiusType r; @@ -128,7 +128,7 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage, TOutputImage, TFunction> // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { neighInputIt = itk::ConstNeighborhoodIterator<TInputImage>(r, inputPtr, *fit); outputIt = itk::ImageRegionIterator<TOutputImage>(outputPtr, *fit); @@ -136,15 +136,15 @@ UnaryFunctorNeighborhoodImageFilter<TInputImage, TOutputImage, TFunction> neighInputIt.GoToBegin(); while ( ! outputIt.IsAtEnd() ) - { + { outputIt.Set( m_Functor( neighInputIt) ); ++neighInputIt; ++outputIt; progress.CompletedPixel(); - } } + } } } // end namespace otb diff --git a/Code/Common/otbVectorData.h b/Code/Common/otbVectorData.h index 0769ccc26cda7c8c077ebfa9532af1d9f528e4f3..f10c4bd0dc7254700f7d67d362b0bbdb2483fd0f 100644 --- a/Code/Common/otbVectorData.h +++ b/Code/Common/otbVectorData.h @@ -26,80 +26,80 @@ namespace otb { - /** \class VectorData - * \brief this class represents a hierarchy of vector data. - * - * This class contains an itk::TreeContainer templated with otb::DataNode. - * It represents a tree structure of vector data. These data can be read from - * shapefiles or kml files for instance. - * - * The internal tree can be walked with itk::TreeIteratorBase subclasses. - * - * The three templates indicate - * - the precision of the points coordinates (default double) - * - the number of dimensions of the space (default 2) - * - the precision of the value associated with objects such as line or polygons (default double) - * - * \sa DataNode - * \sa VectorDataFileReader - * \sa VectorDataFileWriter - * - */ - template <class TPrecision = double, unsigned int VDimension =2, class TValuePrecision = double> - class VectorData - : public itk::DataObject - { - public: - /** Standard class typedefs */ - typedef VectorData Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - - - /** Standard macros */ - itkNewMacro(Self); - itkTypeMacro(VectorData,DataObject); - itkStaticConstMacro(Dimension, unsigned int, VDimension); - - /** Template parameters typedef */ - typedef TPrecision PrecisionType; - typedef TValuePrecision ValuePrecisionType; - typedef otb::DataNode<TPrecision,VDimension,TValuePrecision> DataNodeType; - typedef typename DataNodeType::Pointer DataNodePointerType; - typedef itk::TreeContainer<DataNodePointerType> DataTreeType; - typedef typename DataTreeType::Pointer DataTreePointerType; - - itkGetObjectMacro(DataTree,DataTreeType); - itkGetConstObjectMacro(DataTree,DataTreeType); - - virtual void SetProjectionRef(std::string projectionRef); - virtual std::string GetProjectionRef() const; - - /** Clear the vector data */ - virtual bool Clear(); - - /** Return the number of element in the tree */ - virtual int Size() const; - - protected: - /** Constructor */ - VectorData(); - /** Destructor */ - virtual ~VectorData(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - VectorData(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - - /** Data tree */ - DataTreePointerType m_DataTree; - - }; +/** \class VectorData + * \brief this class represents a hierarchy of vector data. + * + * This class contains an itk::TreeContainer templated with otb::DataNode. + * It represents a tree structure of vector data. These data can be read from + * shapefiles or kml files for instance. + * + * The internal tree can be walked with itk::TreeIteratorBase subclasses. + * + * The three templates indicate + * - the precision of the points coordinates (default double) + * - the number of dimensions of the space (default 2) + * - the precision of the value associated with objects such as line or polygons (default double) + * + * \sa DataNode + * \sa VectorDataFileReader + * \sa VectorDataFileWriter + * + */ +template <class TPrecision = double, unsigned int VDimension =2, class TValuePrecision = double> +class VectorData + : public itk::DataObject +{ +public: + /** Standard class typedefs */ + typedef VectorData Self; + typedef itk::DataObject Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + + + /** Standard macros */ + itkNewMacro(Self); + itkTypeMacro(VectorData,DataObject); + itkStaticConstMacro(Dimension, unsigned int, VDimension); + + /** Template parameters typedef */ + typedef TPrecision PrecisionType; + typedef TValuePrecision ValuePrecisionType; + typedef otb::DataNode<TPrecision,VDimension,TValuePrecision> DataNodeType; + typedef typename DataNodeType::Pointer DataNodePointerType; + typedef itk::TreeContainer<DataNodePointerType> DataTreeType; + typedef typename DataTreeType::Pointer DataTreePointerType; + + itkGetObjectMacro(DataTree,DataTreeType); + itkGetConstObjectMacro(DataTree,DataTreeType); + + virtual void SetProjectionRef(std::string projectionRef); + virtual std::string GetProjectionRef() const; + + /** Clear the vector data */ + virtual bool Clear(); + + /** Return the number of element in the tree */ + virtual int Size() const; + +protected: + /** Constructor */ + VectorData(); + /** Destructor */ + virtual ~VectorData() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + VectorData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + + /** Data tree */ + DataTreePointerType m_DataTree; + +}; }// end namespace otb diff --git a/Code/Common/otbVectorData.txx b/Code/Common/otbVectorData.txx index 1f9d9030034eb5fb4c4ad841cb6a5411e6ec76f0..d3c345c6cf3cb1c49a6f2f72c806482b86ce7920 100644 --- a/Code/Common/otbVectorData.txx +++ b/Code/Common/otbVectorData.txx @@ -36,9 +36,9 @@ VectorData<TPrecision,VDimension,TValuePrecision> } template<class TPrecision, unsigned int VDimension, class TValuePrecision> - void - VectorData<TPrecision,VDimension,TValuePrecision> - ::SetProjectionRef(std::string projectionRef) +void +VectorData<TPrecision,VDimension,TValuePrecision> +::SetProjectionRef(std::string projectionRef) { itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); @@ -47,9 +47,9 @@ template<class TPrecision, unsigned int VDimension, class TValuePrecision> } template<class TPrecision, unsigned int VDimension, class TValuePrecision> - std::string - VectorData<TPrecision,VDimension,TValuePrecision> - ::GetProjectionRef() const +std::string +VectorData<TPrecision,VDimension,TValuePrecision> +::GetProjectionRef() const { const itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); @@ -68,9 +68,9 @@ VectorData<TPrecision,VDimension,TValuePrecision> } template <class TPrecision, unsigned int VDimension, class TValuePrecision> - int - VectorData<TPrecision,VDimension,TValuePrecision> - ::Size() const +int +VectorData<TPrecision,VDimension,TValuePrecision> +::Size() const { return m_DataTree->Count(); } @@ -86,18 +86,18 @@ VectorData<TPrecision,VDimension,TValuePrecision> itk::PreOrderTreeIterator<DataTreeType> it(m_DataTree); it.GoToBegin(); - while(!it.IsAtEnd()) - { - itk::PreOrderTreeIterator<DataTreeType> itParent = it; - bool goesOn = true; - while(itParent.HasParent() && goesOn ) + while (!it.IsAtEnd()) { - os<<indent; - goesOn = itParent.GoToParent(); - } - os<<"+"<<it.Get()->GetNodeTypeAsString()<<std::endl; - ++it; + itk::PreOrderTreeIterator<DataTreeType> itParent = it; + bool goesOn = true; + while (itParent.HasParent() && goesOn ) + { + os<<indent; + goesOn = itParent.GoToParent(); } + os<<"+"<<it.Get()->GetNodeTypeAsString()<<std::endl; + ++it; + } } } // end namespace otb diff --git a/Code/Common/otbVectorDataSource.txx b/Code/Common/otbVectorDataSource.txx index 2315eeb7f2a993061cfb6b97412e4c3c110bfab5..05912ef53be3d483ba111f9b89953309fca1acc6 100644 --- a/Code/Common/otbVectorDataSource.txx +++ b/Code/Common/otbVectorDataSource.txx @@ -65,20 +65,20 @@ typename VectorDataSource<TOutputVectorData>::OutputVectorDataType * VectorDataSource<TOutputVectorData> ::GetOutput(void) { - if(this->GetNumberOfOutputs()<1) - { + if (this->GetNumberOfOutputs()<1) + { return 0; - } + } return static_cast<OutputVectorDataType *> (this->ProcessObject::GetOutput(0)); } template <class TOutputVectorData> - typename VectorDataSource<TOutputVectorData>::OutputVectorDataType * - VectorDataSource<TOutputVectorData> - ::GetOutput(unsigned int idx) +typename VectorDataSource<TOutputVectorData>::OutputVectorDataType * +VectorDataSource<TOutputVectorData> +::GetOutput(unsigned int idx) { return static_cast<OutputVectorDataType*> - (this->Superclass::GetOutput(idx)); + (this->Superclass::GetOutput(idx)); } /** diff --git a/Code/Common/otbVectorDataToVectorDataFilter.h b/Code/Common/otbVectorDataToVectorDataFilter.h index 4fd70f8e3f724eef35032fb549f275dbefa28957..2afa64b329ee6e0b0f75f0d7760829b74e7ed6cd 100644 --- a/Code/Common/otbVectorDataToVectorDataFilter.h +++ b/Code/Common/otbVectorDataToVectorDataFilter.h @@ -34,48 +34,48 @@ namespace otb * * \ingroup VectorDataFilter */ - template <class TInputVectorData, class TOutputVectorData > - class ITK_EXPORT VectorDataToVectorDataFilter : public otb::VectorDataSource<TOutputVectorData> - { - public: - /** Standard class typedefs. */ - typedef VectorDataToVectorDataFilter Self; - typedef otb::VectorDataSource<TOutputVectorData> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +template <class TInputVectorData, class TOutputVectorData > +class ITK_EXPORT VectorDataToVectorDataFilter : public otb::VectorDataSource<TOutputVectorData> +{ +public: + /** Standard class typedefs. */ + typedef VectorDataToVectorDataFilter Self; + typedef otb::VectorDataSource<TOutputVectorData> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(VectorDataToVectorDataFilter, VectorDataSource); + /** Run-time type information (and related methods). */ + itkTypeMacro(VectorDataToVectorDataFilter, VectorDataSource); - /** Some typedefs. */ - typedef TInputVectorData InputVectorDataType; - typedef TOutputVectorData OutputVectorDataType; - typedef typename TInputVectorData::ConstPointer InputVectorDataPointer; - typedef typename TOutputVectorData::Pointer OutputVectorDataPointer; + /** Some typedefs. */ + typedef TInputVectorData InputVectorDataType; + typedef TOutputVectorData OutputVectorDataType; + typedef typename TInputVectorData::ConstPointer InputVectorDataPointer; + typedef typename TOutputVectorData::Pointer OutputVectorDataPointer; - typedef itk::DataObject::Pointer DataObjectPointer; + typedef itk::DataObject::Pointer DataObjectPointer; - virtual void SetInput( const InputVectorDataType *input); - const InputVectorDataType * GetInput(void); + virtual void SetInput( const InputVectorDataType *input); + const InputVectorDataType * GetInput(void); - protected: - /** Constructor */ - VectorDataToVectorDataFilter(); - /** Destructor */ - virtual ~VectorDataToVectorDataFilter() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + /** Constructor */ + VectorDataToVectorDataFilter(); + /** Destructor */ + virtual ~VectorDataToVectorDataFilter() {}; + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: - VectorDataToVectorDataFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + VectorDataToVectorDataFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; } // end namespace otb diff --git a/Code/Common/otbVectorDataToVectorDataFilter.txx b/Code/Common/otbVectorDataToVectorDataFilter.txx index 2f25ec475b53dd2cdad63c0aa5c6f0a9759adcb2..10fa96af8a516cba9b454de6cf261b6924ec6fc7 100644 --- a/Code/Common/otbVectorDataToVectorDataFilter.txx +++ b/Code/Common/otbVectorDataToVectorDataFilter.txx @@ -27,49 +27,49 @@ namespace otb /** * Constructor */ - template <class TInputVectorData, class TOutputVectorData> - VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> - ::VectorDataToVectorDataFilter() - { - this->SetNumberOfRequiredInputs( 1 ); - } +template <class TInputVectorData, class TOutputVectorData> +VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> +::VectorDataToVectorDataFilter() +{ + this->SetNumberOfRequiredInputs( 1 ); +} - template <class TInputVectorData, class TOutputVectorData> - void - VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> - ::SetInput(const InputVectorDataType *input) +template <class TInputVectorData, class TOutputVectorData> +void +VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> +::SetInput(const InputVectorDataType *input) +{ +// Process object is not const-correct so the const_cast is required here + this->itk::ProcessObject::SetNthInput(0, + const_cast< InputVectorDataType * >( input ) ); +} + +template <class TInputVectorData, class TOutputVectorData> +const typename VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData>::InputVectorDataType * +VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> +::GetInput(void) +{ + if (this->GetNumberOfInputs() < 1) { - // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(0, - const_cast< InputVectorDataType * >( input ) ); + return 0; } - template <class TInputVectorData, class TOutputVectorData> - const typename VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData>::InputVectorDataType * - VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> - ::GetInput(void) - { - if (this->GetNumberOfInputs() < 1) - { - return 0; - } - - return static_cast<const TInputVectorData * > - (this->itk::ProcessObject::GetInput(0) ); - } + return static_cast<const TInputVectorData * > + (this->itk::ProcessObject::GetInput(0) ); +} /** * PrintSelf Method */ - template <class TInputVectorData, class TOutputVectorData> - void - VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } +template <class TInputVectorData, class TOutputVectorData> +void +VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } // end namespace otb diff --git a/Code/Common/otbVectorImageToASImageAdaptor.h b/Code/Common/otbVectorImageToASImageAdaptor.h index a4990ae1fc5f54625e457ee90997e11bd224bd39..7b0f9104176405d068b3c2645e3e003d1bf7e776 100644 --- a/Code/Common/otbVectorImageToASImageAdaptor.h +++ b/Code/Common/otbVectorImageToASImageAdaptor.h @@ -36,15 +36,15 @@ namespace otb template <class TImage> class ITK_EXPORT VectorImageToASImageAdaptor : public itk::ImageAdaptor<TImage,otb::Accessor::VectorImageToASPixelAccessor< - typename TImage::PixelType::ValueType> > + typename TImage::PixelType::ValueType> > { public: /** Standard class typedefs. */ typedef VectorImageToASImageAdaptor Self; typedef itk::ImageAdaptor<TImage, - otb::Accessor::VectorImageToASPixelAccessor< - typename TImage::PixelType::ValueType - > > Superclass; + otb::Accessor::VectorImageToASPixelAccessor< + typename TImage::PixelType::ValueType + > > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -60,11 +60,11 @@ public: typedef typename Superclass::PixelContainerPointer PixelContainerPointer; typedef typename Superclass::PixelContainerConstPointer PixelContainerConstPointer; - protected: +protected: VectorImageToASImageAdaptor() {} virtual ~VectorImageToASImageAdaptor() {} - private: +private: VectorImageToASImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/Common/otbVectorImageToASPixelAccessor.h b/Code/Common/otbVectorImageToASPixelAccessor.h index 1cb4f2657868284bb76c97ced02988ea95dfaad4..2f85135f6d1812287c02564dbf02199664a30675 100644 --- a/Code/Common/otbVectorImageToASPixelAccessor.h +++ b/Code/Common/otbVectorImageToASPixelAccessor.h @@ -49,8 +49,8 @@ public: /** Standard class typedefs. */ typedef VectorImageToASPixelAccessor Self; - /** External typedef. It defines the external aspect - * that this class will exhibit */ + /** External typedef. It defines the external aspect + * that this class will exhibit */ typedef itk::FixedArray<T,3> ExternalType; /** Internal typedef. It defines the internal real @@ -59,18 +59,18 @@ public: /** Write access to the VectorToRGB component */ inline void Set( InternalType & output, const ExternalType & input ) const - { + { output[0] = input[0]; output[1] = input[1]; output[2] = input[2]; - } + } /** Read access to the VectorToRGB component */ inline ExternalType Get( const InternalType & input ) const - { + { ExternalType rgb(input.GetDataPointer()); return rgb; - } + } private: }; diff --git a/Code/Common/otbWriterWatcherBase.cxx b/Code/Common/otbWriterWatcherBase.cxx index aa4368d626cb0dd33a71884ffce7e7511a0df3e2..924357e69d19654b8b00eb69afcae11aa44e7c36 100644 --- a/Code/Common/otbWriterWatcherBase.cxx +++ b/Code/Common/otbWriterWatcherBase.cxx @@ -33,7 +33,7 @@ WriterWatcherBase WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, - const char *comment) + const char *comment) { // Initialize state m_Process = process; @@ -49,48 +49,48 @@ WriterWatcherBase // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartFilter); + &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndFilter); + &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowFilterProgress); + &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartWriter); + &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndWriter); + &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowWriterProgress); + &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), - m_StartWriterCommand); + m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), - m_EndWriterCommand); + m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), - m_ProgressWriterCommand); + m_ProgressWriterCommand); // Try to get the filter that is wired to m_Process. - if(m_Process->GetInputs()[0]->GetSource()) - { - m_SourceProcess = m_Process->GetInputs()[0]->GetSource(); + if (m_Process->GetInputs()[0]->GetSource()) + { + m_SourceProcess = m_Process->GetInputs()[0]->GetSource(); - // Add the commands as observers - m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), - m_StartFilterCommand); + // Add the commands as observers + m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), + m_StartFilterCommand); - m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), - m_EndFilterCommand); + m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), + m_EndFilterCommand); - m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), - m_ProgressFilterCommand); - } + m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), + m_ProgressFilterCommand); + } } WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, itk::ProcessObject * source, - const char *comment) + const char *comment) { // Initialize state m_Process = process; @@ -106,39 +106,39 @@ WriterWatcherBase // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartFilter); + &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndFilter); + &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowFilterProgress); + &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartWriter); + &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndWriter); + &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowWriterProgress); + &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), - m_StartWriterCommand); + m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), - m_EndWriterCommand); + m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), - m_ProgressWriterCommand); + m_ProgressWriterCommand); m_SourceProcess = source; // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), - m_StartFilterCommand); + m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), - m_EndFilterCommand); + m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), - m_ProgressFilterCommand); + m_ProgressFilterCommand); } @@ -147,35 +147,35 @@ WriterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartWriterCommand) { - m_Process->RemoveObserver(m_StartWriterTag); - } - if (m_EndWriterCommand) - { - m_Process->RemoveObserver(m_EndWriterTag); - } - if (m_ProgressWriterCommand) - { - m_Process->RemoveObserver(m_ProgressWriterTag); - } + if (m_StartWriterCommand) + { + m_Process->RemoveObserver(m_StartWriterTag); } - if (m_SourceProcess) + if (m_EndWriterCommand) { - if (m_StartFilterCommand) - { - m_SourceProcess->RemoveObserver(m_StartFilterTag); - } - if (m_EndFilterCommand) - { - m_SourceProcess->RemoveObserver(m_EndFilterTag); + m_Process->RemoveObserver(m_EndWriterTag); + } + if (m_ProgressWriterCommand) + { + m_Process->RemoveObserver(m_ProgressWriterTag); + } } - if (m_ProgressFilterCommand) + if (m_SourceProcess) { - m_SourceProcess->RemoveObserver(m_ProgressFilterTag); - } + if (m_StartFilterCommand) + { + m_SourceProcess->RemoveObserver(m_StartFilterTag); + } + if (m_EndFilterCommand) + { + m_SourceProcess->RemoveObserver(m_EndFilterTag); + } + if (m_ProgressFilterCommand) + { + m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } + } // Initialize state m_TimeProbe = watch.m_TimeProbe; @@ -192,46 +192,46 @@ WriterWatcherBase // Create a series of commands if (m_Process) - { - m_StartWriterCommand = CommandType::New(); - m_EndWriterCommand = CommandType::New(); - m_ProgressWriterCommand = CommandType::New(); - - // Assign the callbacks - m_StartWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartWriter); - m_EndWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndWriter); - m_ProgressWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowWriterProgress); - - // Add the commands as observers - m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); - m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); - m_ProgressWriterTag - = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); - } + { + m_StartWriterCommand = CommandType::New(); + m_EndWriterCommand = CommandType::New(); + m_ProgressWriterCommand = CommandType::New(); + + // Assign the callbacks + m_StartWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::StartWriter); + m_EndWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::EndWriter); + m_ProgressWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::ShowWriterProgress); + + // Add the commands as observers + m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); + m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); + m_ProgressWriterTag + = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); + } if (m_SourceProcess) - { - m_StartFilterCommand = CommandType::New(); - m_EndFilterCommand = CommandType::New(); - m_ProgressFilterCommand = CommandType::New(); - - // Assign the callbacks - m_StartFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartFilter); - m_EndFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndFilter); - m_ProgressFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowFilterProgress); - - // Add the commands as observers - m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); - m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); - m_ProgressFilterTag - = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); - } + { + m_StartFilterCommand = CommandType::New(); + m_EndFilterCommand = CommandType::New(); + m_ProgressFilterCommand = CommandType::New(); + + // Assign the callbacks + m_StartFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::StartFilter); + m_EndFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::EndFilter); + m_ProgressFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::ShowFilterProgress); + + // Add the commands as observers + m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); + m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); + m_ProgressFilterTag + = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); + } } void @@ -240,35 +240,35 @@ WriterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartWriterCommand) - { - m_Process->RemoveObserver(m_StartWriterTag); - } - if (m_EndWriterCommand) - { - m_Process->RemoveObserver(m_EndWriterTag); - } - if (m_ProgressWriterCommand) { - m_Process->RemoveObserver(m_ProgressWriterTag); - } + if (m_StartWriterCommand) + { + m_Process->RemoveObserver(m_StartWriterTag); } - if (m_SourceProcess) + if (m_EndWriterCommand) { - if (m_StartFilterCommand) - { - m_SourceProcess->RemoveObserver(m_StartFilterTag); - } - if (m_EndFilterCommand) - { - m_SourceProcess->RemoveObserver(m_EndFilterTag); + m_Process->RemoveObserver(m_EndWriterTag); + } + if (m_ProgressWriterCommand) + { + m_Process->RemoveObserver(m_ProgressWriterTag); + } } - if (m_ProgressFilterCommand) + if (m_SourceProcess) { - m_SourceProcess->RemoveObserver(m_ProgressFilterTag); - } + if (m_StartFilterCommand) + { + m_SourceProcess->RemoveObserver(m_StartFilterTag); + } + if (m_EndFilterCommand) + { + m_SourceProcess->RemoveObserver(m_EndFilterTag); + } + if (m_ProgressFilterCommand) + { + m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } + } // Initialize state m_TimeProbe = watch.m_TimeProbe; @@ -285,45 +285,45 @@ WriterWatcherBase // Create a series of commands if (m_Process) - { - m_StartWriterCommand = CommandType::New(); - m_EndWriterCommand = CommandType::New(); - m_ProgressWriterCommand = CommandType::New(); - - // Assign the callbacks - m_StartWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartWriter); - m_EndWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndWriter); - m_ProgressWriterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowWriterProgress); - - // Add the commands as observers - m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); - m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); - m_ProgressWriterTag - = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); - } + { + m_StartWriterCommand = CommandType::New(); + m_EndWriterCommand = CommandType::New(); + m_ProgressWriterCommand = CommandType::New(); + + // Assign the callbacks + m_StartWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::StartWriter); + m_EndWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::EndWriter); + m_ProgressWriterCommand->SetCallbackFunction(this, + &WriterWatcherBase::ShowWriterProgress); + + // Add the commands as observers + m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); + m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); + m_ProgressWriterTag + = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); + } if (m_SourceProcess) - { - m_StartFilterCommand = CommandType::New(); - m_EndFilterCommand = CommandType::New(); - m_ProgressFilterCommand = CommandType::New(); - - // Assign the callbacks - m_StartFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::StartFilter); - m_EndFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::EndFilter); - m_ProgressFilterCommand->SetCallbackFunction(this, - &WriterWatcherBase::ShowFilterProgress); - - // Add the commands as observers - m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); - m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); - m_ProgressFilterTag - = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); - } + { + m_StartFilterCommand = CommandType::New(); + m_EndFilterCommand = CommandType::New(); + m_ProgressFilterCommand = CommandType::New(); + + // Assign the callbacks + m_StartFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::StartFilter); + m_EndFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::EndFilter); + m_ProgressFilterCommand->SetCallbackFunction(this, + &WriterWatcherBase::ShowFilterProgress); + + // Add the commands as observers + m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); + m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); + m_ProgressFilterTag + = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); + } } WriterWatcherBase @@ -331,35 +331,35 @@ WriterWatcherBase { // Remove any observers we have on the old process object if (m_Process) - { - if (m_StartWriterCommand) { - m_Process->RemoveObserver(m_StartWriterTag); - } - if (m_EndWriterCommand) - { - m_Process->RemoveObserver(m_EndWriterTag); - } - if (m_ProgressWriterCommand) - { - m_Process->RemoveObserver(m_ProgressWriterTag); - } + if (m_StartWriterCommand) + { + m_Process->RemoveObserver(m_StartWriterTag); } - if (m_SourceProcess) + if (m_EndWriterCommand) { - if (m_StartFilterCommand) - { - m_SourceProcess->RemoveObserver(m_StartFilterTag); - } - if (m_EndFilterCommand) - { - m_SourceProcess->RemoveObserver(m_EndFilterTag); + m_Process->RemoveObserver(m_EndWriterTag); + } + if (m_ProgressWriterCommand) + { + m_Process->RemoveObserver(m_ProgressWriterTag); + } } - if (m_ProgressFilterCommand) + if (m_SourceProcess) { - m_SourceProcess->RemoveObserver(m_ProgressFilterTag); - } + if (m_StartFilterCommand) + { + m_SourceProcess->RemoveObserver(m_StartFilterTag); } + if (m_EndFilterCommand) + { + m_SourceProcess->RemoveObserver(m_EndFilterTag); + } + if (m_ProgressFilterCommand) + { + m_SourceProcess->RemoveObserver(m_ProgressFilterTag); + } + } } } // end namespace otb diff --git a/Code/Common/otbWriterWatcherBase.h b/Code/Common/otbWriterWatcherBase.h index 6e83683e9d241e041dce87230578dd0d3cfdc7e0..befb2ca66dc277a320ec1ade866d6d2ff4b004a8 100644 --- a/Code/Common/otbWriterWatcherBase.h +++ b/Code/Common/otbWriterWatcherBase.h @@ -28,128 +28,137 @@ namespace otb { - /** \class WriterWatcherBase - * \brief This class is an abstract class - * Provides an interface to progress task mechanic - * - * Implement your callbacks - * \li ShowWriterProgress : callback called for each completed tile - * \li StartWriter : callback called at the begin of tile writing - * \li EndWriter : callback called at the end of tile writing - * \li ShowFilterProgress : callback called for each completed pixel - * \li StartFilter : callback called at the begin of filter execution for a given tile - * \li EndFilter : callback called at the end of filter execution for a given tile - * - */ - class /*ITK_EXPORT*/ WriterWatcherBase - { - public: +/** \class WriterWatcherBase + * \brief This class is an abstract class + * Provides an interface to progress task mechanic + * + * Implement your callbacks + * \li ShowWriterProgress : callback called for each completed tile + * \li StartWriter : callback called at the begin of tile writing + * \li EndWriter : callback called at the end of tile writing + * \li ShowFilterProgress : callback called for each completed pixel + * \li StartFilter : callback called at the begin of filter execution for a given tile + * \li EndFilter : callback called at the end of filter execution for a given tile + * + */ +class /*ITK_EXPORT*/ WriterWatcherBase +{ +public: - /** Constructor. Takes a ProcessObject to monitor and an optional - * comment string that is prepended to each event message. */ - WriterWatcherBase(itk::ProcessObject* process, - const char *comment=""); + /** Constructor. Takes a ProcessObject to monitor and an optional + * comment string that is prepended to each event message. */ + WriterWatcherBase(itk::ProcessObject* process, + const char *comment=""); - /** This other constructor is provided so that the user can set a different processing filter than the one - just before process in the pipeline */ - WriterWatcherBase(itk::ProcessObject* process, itk::ProcessObject * source,const char *comment=""); + /** This other constructor is provided so that the user can set a different processing filter than the one + just before process in the pipeline */ + WriterWatcherBase(itk::ProcessObject* process, itk::ProcessObject * source,const char *comment=""); - /** Default constructor */ - WriterWatcherBase(); + /** Default constructor */ + WriterWatcherBase(); - /** Copy constructor */ - WriterWatcherBase(const WriterWatcherBase&); + /** Copy constructor */ + WriterWatcherBase(const WriterWatcherBase&); - /** operator= */ - void operator=(const WriterWatcherBase& ); + /** operator= */ + void operator=(const WriterWatcherBase& ); - /** Destructor. */ - virtual ~WriterWatcherBase(); + /** Destructor. */ + virtual ~WriterWatcherBase(); - /** Methods to access member data */ - /** Get a pointer to the process object being watched. */ - itk::ProcessObject *GetProcess () {return m_Process.GetPointer();} + /** Methods to access member data */ + /** Get a pointer to the process object being watched. */ + itk::ProcessObject *GetProcess () + { + return m_Process.GetPointer(); + } - /** Get the comment for the watcher. */ - std::string GetComment() {return m_Comment;} + /** Get the comment for the watcher. */ + std::string GetComment() + { + return m_Comment; + } - /** Get a reference to the TimeProbe */ - itk::TimeProbe &GetTimeProbe() {return m_TimeProbe;} + /** Get a reference to the TimeProbe */ + itk::TimeProbe &GetTimeProbe() + { + return m_TimeProbe; + } - protected: +protected: - /** Callback method to show the ProgressEvent from the writer */ - virtual void ShowWriterProgress() = 0; + /** Callback method to show the ProgressEvent from the writer */ + virtual void ShowWriterProgress() = 0; - /** Callback method to show the StartEvent from the writer*/ - virtual void StartWriter() = 0; + /** Callback method to show the StartEvent from the writer*/ + virtual void StartWriter() = 0; - /** Callback method to show the EndEvent from the writer*/ - virtual void EndWriter() = 0; + /** Callback method to show the EndEvent from the writer*/ + virtual void EndWriter() = 0; - /** Callback method to show the ProgressEvent from the filter */ - virtual void ShowFilterProgress() = 0; + /** Callback method to show the ProgressEvent from the filter */ + virtual void ShowFilterProgress() = 0; - /** Callback method to show the StartEvent from the filter*/ - virtual void StartFilter() = 0; + /** Callback method to show the StartEvent from the filter*/ + virtual void StartFilter() = 0; - /** Callback method to show the EndEvent from the filter*/ - virtual void EndFilter() = 0; + /** Callback method to show the EndEvent from the filter*/ + virtual void EndFilter() = 0; - /** Computing time */ - itk::TimeProbe m_TimeProbe; + /** Computing time */ + itk::TimeProbe m_TimeProbe; - /** Associated comment */ - std::string m_Comment; + /** Associated comment */ + std::string m_Comment; - /** Abstract process object */ - itk::ProcessObject::Pointer m_Process; + /** Abstract process object */ + itk::ProcessObject::Pointer m_Process; - /** Second abstract process object representing the source */ - itk::ProcessObject::Pointer m_SourceProcess; + /** Second abstract process object representing the source */ + itk::ProcessObject::Pointer m_SourceProcess; - /** Internal type */ - typedef itk::SimpleMemberCommand<WriterWatcherBase> CommandType; + /** Internal type */ + typedef itk::SimpleMemberCommand<WriterWatcherBase> CommandType; - /** Start writer callback */ - CommandType::Pointer m_StartWriterCommand; + /** Start writer callback */ + CommandType::Pointer m_StartWriterCommand; - /** End writer callback */ - CommandType::Pointer m_EndWriterCommand; + /** End writer callback */ + CommandType::Pointer m_EndWriterCommand; - /** Progress writer callback */ - CommandType::Pointer m_ProgressWriterCommand; + /** Progress writer callback */ + CommandType::Pointer m_ProgressWriterCommand; - /** Start filter callback */ - CommandType::Pointer m_StartFilterCommand; + /** Start filter callback */ + CommandType::Pointer m_StartFilterCommand; - /** End writer callback */ - CommandType::Pointer m_EndFilterCommand; + /** End writer callback */ + CommandType::Pointer m_EndFilterCommand; - /** Progress writer callback */ - CommandType::Pointer m_ProgressFilterCommand; + /** Progress writer callback */ + CommandType::Pointer m_ProgressFilterCommand; - /** Start oberserver */ - unsigned long m_StartWriterTag; + /** Start oberserver */ + unsigned long m_StartWriterTag; - /** End observer */ - unsigned long m_EndWriterTag; + /** End observer */ + unsigned long m_EndWriterTag; - /** Progress observer */ - unsigned long m_ProgressWriterTag; + /** Progress observer */ + unsigned long m_ProgressWriterTag; - /** Start oberserver */ - unsigned long m_StartFilterTag; + /** Start oberserver */ + unsigned long m_StartFilterTag; - /** End observer */ - unsigned long m_EndFilterTag; + /** End observer */ + unsigned long m_EndFilterTag; - /** Progress observer */ - unsigned long m_ProgressFilterTag; + /** Progress observer */ + unsigned long m_ProgressFilterTag; - private: +private: - }; +}; } // end namespace otb diff --git a/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.h b/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.h index db41a50a8b5c6656fc3e49955ae3781dd7879d10..19f9664985fc57e931807be120a3cade63716c5a 100644 --- a/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.h @@ -30,9 +30,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT BSplinesInterpolateDeformationFieldGenerator - : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef BSplinesInterpolateDeformationFieldGenerator Self; typedef PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -62,7 +62,7 @@ protected: BSplinesInterpolateDeformationFieldGenerator() {}; /** Destructor */ virtual ~BSplinesInterpolateDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.txx b/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.txx index 13b65eb92557f143097f81166011fbbb3533e9d6..01d0654f6ae1058e24cc92e9a2c844e31d92e217 100644 --- a/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbBSplinesInterpolateDeformationFieldGenerator.txx @@ -56,25 +56,25 @@ BSplinesInterpolateDeformationFieldGenerator<TPointSet, TDeformationField> PointDataIterator pointDataIterator = this->GetPointSet()->GetPointData()->Begin(); - while( pointIterator != end ) - { - typename PointDataContainer::Element valueAndDeformations = pointDataIterator.Value(); - - if(vcl_abs(valueAndDeformations[0])>=this->GetMetricThreshold()) + while ( pointIterator != end ) { - typename PointSetType::PointType p = pointIterator.Value(); // access the point - sourcePoint[0] = p[0]; - sourcePoint[1] = p[1]; - targetPoint[0] = p[0] - valueAndDeformations[1]; - targetPoint[1] = p[1] - valueAndDeformations[2]; - otbMsgDebugMacro(<<"Adding landmark "<<pointId<<", source point: "<<sourcePoint<<", targetpoint: "<<targetPoint); - sourceLandmarks->InsertElement( pointId, sourcePoint ); - targetLandmarks->InsertElement( pointId, targetPoint ); - ++pointId; - } - ++pointIterator; - ++pointDataIterator; + typename PointDataContainer::Element valueAndDeformations = pointDataIterator.Value(); + + if (vcl_abs(valueAndDeformations[0])>=this->GetMetricThreshold()) + { + typename PointSetType::PointType p = pointIterator.Value(); // access the point + sourcePoint[0] = p[0]; + sourcePoint[1] = p[1]; + targetPoint[0] = p[0] - valueAndDeformations[1]; + targetPoint[1] = p[1] - valueAndDeformations[2]; + otbMsgDebugMacro(<<"Adding landmark "<<pointId<<", source point: "<<sourcePoint<<", targetpoint: "<<targetPoint); + sourceLandmarks->InsertElement( pointId, sourcePoint ); + targetLandmarks->InsertElement( pointId, targetPoint ); + ++pointId; } + ++pointIterator; + ++pointDataIterator; + } typename DeformationFieldSourceType::Pointer deformer = DeformationFieldSourceType::New(); deformer->SetOutputSpacing(this->GetOutputSpacing()); @@ -96,16 +96,16 @@ BSplinesInterpolateDeformationFieldGenerator<TPointSet, TDeformationField> OutputIteratorType outIt(outputPtr,outputPtr->GetRequestedRegion()); int i=0; // Casting otb::Image<itt::Vector<ValueType,2>,2> to otb::VectorImage<ValueType,2> - for(inIt.GoToBegin(),outIt.GoToBegin();(!inIt.IsAtEnd())&&(!outIt.IsAtEnd());++inIt,++outIt,++i) - { - typename ImageType::PixelType inPixel; - inPixel = inIt.Get(); - PixelType outPixel; - outPixel.SetSize(2); - outPixel[0]=-inPixel[0]; - outPixel[1]=-inPixel[1]; - outIt.Set(outPixel); - } + for (inIt.GoToBegin(),outIt.GoToBegin();(!inIt.IsAtEnd())&&(!outIt.IsAtEnd());++inIt,++outIt,++i) + { + typename ImageType::PixelType inPixel; + inPixel = inIt.Get(); + PixelType outPixel; + outPixel.SetSize(2); + outPixel[0]=-inPixel[0]; + outPixel[1]=-inPixel[1]; + outIt.Set(outPixel); + } } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.h b/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.h index ae5bb795f54932eba438b4ec89c9df1e73a8f082..27b326a0c58cc38457cd5a930a4bbaf75b88cdcd 100644 --- a/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.h @@ -40,9 +40,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT BSplinesInterpolateTransformDeformationFieldGenerator - : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef BSplinesInterpolateTransformDeformationFieldGenerator Self; typedef PointSetWithTransformToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -73,7 +73,7 @@ class ITK_EXPORT BSplinesInterpolateTransformDeformationFieldGenerator typedef otb::Image<PointSetDataType,DeformationFieldType::ImageDimension> InternalImageType; typedef itk::PointSet<PointSetDataType,PointSetType::PointDimension> InternalPointSetType; typedef ij::BSplineScatteredDataPointSetToImageFilter<InternalPointSetType,InternalImageType> - SPlineInterpolateFilterType; + SPlineInterpolateFilterType; typedef typename SPlineInterpolateFilterType::Pointer SPlineInterpolateFilterPointerType; /** @@ -99,7 +99,7 @@ protected: BSplinesInterpolateTransformDeformationFieldGenerator(); /** Destructor */ virtual ~BSplinesInterpolateTransformDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.txx b/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.txx index a6ef95fae5f1f794a56d213cc95a8d327133275e..b05e17205f0a98f113b13da36f5537c89d81bdb6 100644 --- a/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbBSplinesInterpolateTransformDeformationFieldGenerator.txx @@ -70,95 +70,95 @@ BSplinesInterpolateTransformDeformationFieldGenerator<TPointSet, TDeformationFie // Initialisation of the splines interpolator typename SPlineInterpolatorListType::Pointer splineIntList = SPlineInterpolatorListType::New(); - for(unsigned int paramIndex = 0;paramIndex<this->GetTransform()->GetNumberOfParameters();++paramIndex) - { - // Create a new interpolator - splineIntList->PushBack(SPlineInterpolateFilterType::New()); - // Create a new point set - typename InternalPointSetType::Pointer tmpPointSet = InternalPointSetType::New(); - tmpPointSet->Initialize(); - unsigned int pointDataCounter = 0; - for(PointSetIteratorType it = this->GetPointSet()->GetPoints()->Begin();it!=this->GetPointSet()->GetPoints()->End();++it) + for (unsigned int paramIndex = 0;paramIndex<this->GetTransform()->GetNumberOfParameters();++paramIndex) { - if(vcl_abs(this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[0])>=this->GetMetricThreshold()) + // Create a new interpolator + splineIntList->PushBack(SPlineInterpolateFilterType::New()); + // Create a new point set + typename InternalPointSetType::Pointer tmpPointSet = InternalPointSetType::New(); + tmpPointSet->Initialize(); + unsigned int pointDataCounter = 0; + for (PointSetIteratorType it = this->GetPointSet()->GetPoints()->Begin();it!=this->GetPointSet()->GetPoints()->End();++it) + { + if (vcl_abs(this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[0])>=this->GetMetricThreshold()) { typename InternalPointSetType::PixelType V(0.0); - if(!IsAngular(paramIndex)) - { - V[0] = this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3]; - V[1] = this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3]; - } - else - { - V[0] = static_cast<ValueType>(vcl_cos(this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3])); - V[1] = static_cast<ValueType>(vcl_sin( this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3])); - } - unsigned long nbPoints = tmpPointSet->GetNumberOfPoints(); - tmpPointSet->SetPoint( nbPoints, it.Value()); - tmpPointSet->SetPointData( nbPoints, V ); + if (!IsAngular(paramIndex)) + { + V[0] = this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3]; + V[1] = this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3]; + } + else + { + V[0] = static_cast<ValueType>(vcl_cos(this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3])); + V[1] = static_cast<ValueType>(vcl_sin( this->GetPointSet()->GetPointData()->GetElement(pointDataCounter)[paramIndex+3])); + } + unsigned long nbPoints = tmpPointSet->GetNumberOfPoints(); + tmpPointSet->SetPoint( nbPoints, it.Value()); + tmpPointSet->SetPointData( nbPoints, V ); } - ++pointDataCounter; - } - - // Set the interpolator parameters - splineIntList->Back()->SetInput(tmpPointSet); - splineIntList->Back()->SetSplineOrder(m_SplineOrder); - typename SPlineInterpolateFilterType::ArrayType ncps; - ncps.Fill(m_NumberOfControlPoints); - splineIntList->Back()->SetNumberOfControlPoints( ncps ); - splineIntList->Back()->SetNumberOfLevels(m_NumberOfLevels); - // splineIntList->Back()->SetGenerateOutputImage(false); - - // Define the parametric domain. - splineIntList->Back()->SetOrigin(this->GetOutput()->GetOrigin()); - splineIntList->Back()->SetSpacing(this->GetOutput()->GetSpacing()); - splineIntList->Back()->SetSize(this->GetOutput()->GetLargestPossibleRegion().GetSize()); - splineIntList->Back()->Update(); + ++pointDataCounter; } + // Set the interpolator parameters + splineIntList->Back()->SetInput(tmpPointSet); + splineIntList->Back()->SetSplineOrder(m_SplineOrder); + typename SPlineInterpolateFilterType::ArrayType ncps; + ncps.Fill(m_NumberOfControlPoints); + splineIntList->Back()->SetNumberOfControlPoints( ncps ); + splineIntList->Back()->SetNumberOfLevels(m_NumberOfLevels); + // splineIntList->Back()->SetGenerateOutputImage(false); + + // Define the parametric domain. + splineIntList->Back()->SetOrigin(this->GetOutput()->GetOrigin()); + splineIntList->Back()->SetSpacing(this->GetOutput()->GetSpacing()); + splineIntList->Back()->SetSize(this->GetOutput()->GetLargestPossibleRegion().GetSize()); + splineIntList->Back()->Update(); + } + // Interpolation typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> IteratorType; IteratorType outIt(outputPtr,outputPtr->GetRequestedRegion()); // main loop - for(outIt.GoToBegin();!outIt.IsAtEnd();++outIt) - { - // Index of the pixel - IndexType index = outIt.GetIndex(); - // parameters vector - ParametersType params(this->GetTransform()->GetNumberOfParameters()); - // we iterate over the number of parameters of the transform - for(unsigned int paramIndex = 0;paramIndex<this->GetTransform()->GetNumberOfParameters();++paramIndex) + for (outIt.GoToBegin();!outIt.IsAtEnd();++outIt) { - typename InternalPointSetType::PointType p; - this->GetOutput()->TransformIndexToPhysicalPoint(index,p); - typename InternalPointSetType::PixelType V(0.0); - // For each parameter we use the associated spline interpolator - if(!IsAngular(paramIndex)) + // Index of the pixel + IndexType index = outIt.GetIndex(); + // parameters vector + ParametersType params(this->GetTransform()->GetNumberOfParameters()); + // we iterate over the number of parameters of the transform + for (unsigned int paramIndex = 0;paramIndex<this->GetTransform()->GetNumberOfParameters();++paramIndex) + { + typename InternalPointSetType::PointType p; + this->GetOutput()->TransformIndexToPhysicalPoint(index,p); + typename InternalPointSetType::PixelType V(0.0); + // For each parameter we use the associated spline interpolator + if (!IsAngular(paramIndex)) { splineIntList->GetNthElement(paramIndex)->EvaluateAtPoint(p,V); params[paramIndex]=V[0]; } - else + else { splineIntList->GetNthElement(paramIndex)->EvaluateAtPoint(p,V); params[paramIndex]=vcl_atan2(V[1],V[0]); } - // We then compute the target point using the transform - this->GetTransform()->SetParameters(params); - PointType sourcePoint,targetPoint; - outputPtr->TransformIndexToPhysicalPoint(index,sourcePoint); - targetPoint = this->GetTransform()->TransformPoint(sourcePoint); - // And the deformation - PixelType pixel; - pixel.SetSize(2); - pixel[0] = static_cast<ValueType>(targetPoint[0]-sourcePoint[0]); - pixel[1] = static_cast<ValueType>(targetPoint[1]-sourcePoint[1]); - outIt.Set(pixel); - } + // We then compute the target point using the transform + this->GetTransform()->SetParameters(params); + PointType sourcePoint,targetPoint; + outputPtr->TransformIndexToPhysicalPoint(index,sourcePoint); + targetPoint = this->GetTransform()->TransformPoint(sourcePoint); + // And the deformation + PixelType pixel; + pixel.SetSize(2); + pixel[0] = static_cast<ValueType>(targetPoint[0]-sourcePoint[0]); + pixel[1] = static_cast<ValueType>(targetPoint[1]-sourcePoint[1]); + outIt.Set(pixel); } + } } template <class TPointSet,class TDeformationField> void diff --git a/Code/DisparityMap/otbDisparityMapEstimationMethod.h b/Code/DisparityMap/otbDisparityMapEstimationMethod.h index 1af61708b6b47532feb4e0eb7461e599b1f3c4c9..0b3043b7c75912514eed9149dfc524d24863de70 100644 --- a/Code/DisparityMap/otbDisparityMapEstimationMethod.h +++ b/Code/DisparityMap/otbDisparityMapEstimationMethod.h @@ -27,30 +27,30 @@ namespace otb { - /** \class DisparityMapEstimationMethod - * \brief This class performs an estimation of the local deformation - * modelled by a given transform between the fixed and the moving image, - * at each point of the given point set. - * - * It uses the ITK registration framework locally for each point and thus - * provides the flexibility of this framework. The parameters of each transform - * are stored in the ouptut point set associated data. Optimizer, metric, - * interpolator and transform fixed parameters have to be set by the user. - * - * This filters returns the pointset enriched with a set of value as PointData, in order of apparition : - * - The final metric value, - * - The column deformation value, - * - The row deformation value, - * - The final estimated parameters of the transform. - * - * This class is derived from the MAECENAS code provided by Jordi Inglada, - * from CNES. - */ +/** \class DisparityMapEstimationMethod + * \brief This class performs an estimation of the local deformation + * modelled by a given transform between the fixed and the moving image, + * at each point of the given point set. + * + * It uses the ITK registration framework locally for each point and thus + * provides the flexibility of this framework. The parameters of each transform + * are stored in the ouptut point set associated data. Optimizer, metric, + * interpolator and transform fixed parameters have to be set by the user. + * + * This filters returns the pointset enriched with a set of value as PointData, in order of apparition : + * - The final metric value, + * - The column deformation value, + * - The row deformation value, + * - The final estimated parameters of the transform. + * + * This class is derived from the MAECENAS code provided by Jordi Inglada, + * from CNES. + */ template <class TFixedImage, class TMovingImage, class TPointSet> class ITK_EXPORT DisparityMapEstimationMethod - : public PointSetSource<TPointSet> + : public PointSetSource<TPointSet> { - public: +public: /** Standard class typedefs. */ typedef DisparityMapEstimationMethod Self; typedef PointSetSource<TPointSet> Superclass; @@ -74,7 +74,7 @@ class ITK_EXPORT DisparityMapEstimationMethod typedef typename MovingImageType::Pointer MovingImagePointerType; typedef typename MovingImageType::PixelType MovingPixelType; - /** Typedef for the input and ouptut point set */ + /** Typedef for the input and ouptut point set */ typedef TPointSet PointSetType; typedef typename PointSetType::Pointer PointSetPointerType; @@ -144,31 +144,31 @@ class ITK_EXPORT DisparityMapEstimationMethod * Get the source pointset. * \return The source pointset. */ - const TPointSet * GetPointSet(void); + const TPointSet * GetPointSet(void); - /** - * Set the fixed image. - * \param image The fixed image. - **/ - void SetFixedImage(const TFixedImage * image); + /** + * Set the fixed image. + * \param image The fixed image. + **/ + void SetFixedImage(const TFixedImage * image); - /** - * Get the fixed image. - * \return The fixed image. - **/ - const TFixedImage * GetFixedImage(void); + /** + * Get the fixed image. + * \return The fixed image. + **/ + const TFixedImage * GetFixedImage(void); - /** - * Set the moving image. - * \param image The mobing image. - **/ - void SetMovingImage(const TMovingImage * image); + /** + * Set the moving image. + * \param image The mobing image. + **/ + void SetMovingImage(const TMovingImage * image); - /** - * Get the fixed image. - * \return The fixed image. - **/ - const TMovingImage * GetMovingImage(void); + /** + * Get the fixed image. + * \return The fixed image. + **/ + const TMovingImage * GetMovingImage(void); protected: @@ -220,7 +220,7 @@ private: * The size of the window */ SizeType m_WinSize; - }; +}; }// end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbDisparityMapEstimationMethod.txx" diff --git a/Code/DisparityMap/otbDisparityMapEstimationMethod.txx b/Code/DisparityMap/otbDisparityMapEstimationMethod.txx index 0e10a744c2b9a2c1b27bb97b521aae6dffde63cb..67d601829aec51c6777421c111acb30232764382 100644 --- a/Code/DisparityMap/otbDisparityMapEstimationMethod.txx +++ b/Code/DisparityMap/otbDisparityMapEstimationMethod.txx @@ -110,10 +110,10 @@ DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> { this->itk::ProcessObject::SetNthInput(2,const_cast<MovingImageType *>(image)); } - /** - * Get the fixed image. - * \return The fixed image. - **/ +/** + * Get the fixed image. + * \return The fixed image. + **/ template < class TFixedImage, class TMovingImage, class TPointSet > const TMovingImage * DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> @@ -155,8 +155,8 @@ DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> otbMsgDevMacro(<<"Starting registration"); /// Iterate through the point set - while(pointIterator!= end) - { + while (pointIterator!= end) + { typename PointSetType::PointType p = pointIterator.Value(); // access the point // Extract the needed sub-images @@ -253,10 +253,10 @@ DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> data[1] = outputPoint[0]-inputPoint[0]; data[2] = outputPoint[1]-inputPoint[1]; - for(unsigned int i = 0;i<finalParameters.GetSize();++i) - { - data[i+3] = finalParameters[i]; - } + for (unsigned int i = 0;i<finalParameters.GetSize();++i) + { + data[i+3] = finalParameters[i]; + } // Set the parameters value in the point set data container. output->SetPoint(dataId,p); @@ -264,16 +264,16 @@ DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> // otbMsgDevMacro(<<"Point "<<dataId<<": "<<finalParameters); ++pointIterator;// advance to next point ++dataId; - } + } } template < class TFixedImage, class TMovingImage, class TPointSet > void DisparityMapEstimationMethod<TFixedImage,TMovingImage,TPointSet> ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "Window size: " << m_WinSize << std::endl; - os << indent << "Exploration size: " << m_ExploSize << std::endl; - } +{ + Superclass::PrintSelf(os, indent); + os << indent << "Window size: " << m_WinSize << std::endl; + os << indent << "Exploration size: " << m_ExploSize << std::endl; +} } #endif diff --git a/Code/DisparityMap/otbMIRegistrationFilter.h b/Code/DisparityMap/otbMIRegistrationFilter.h index 70c159156f4832ee42f031cd671a1a380418c18f..c22e18f75b28b76c50700c4d4e877ee61ed6de56 100644 --- a/Code/DisparityMap/otbMIRegistrationFilter.h +++ b/Code/DisparityMap/otbMIRegistrationFilter.h @@ -22,7 +22,8 @@ #include "itkPDEDeformableRegistrationFilter.h" #include "itkMIRegistrationFunction.h" -namespace otb { +namespace otb +{ /** \class MIRegistrationFilter * \brief Deformably register two images using the PDEs and Mutual Information. @@ -61,14 +62,14 @@ namespace otb { */ template<class TFixedImage, class TMovingImage, class TDeformationField> class ITK_EXPORT MIRegistrationFilter : - public itk::PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, - TDeformationField> + public itk::PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, + TDeformationField> { public: /** Standard class typedefs. */ typedef MIRegistrationFilter Self; typedef itk::PDEDeformableRegistrationFilter< - TFixedImage, TMovingImage,TDeformationField> Superclass; + TFixedImage, TMovingImage,TDeformationField> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -102,7 +103,7 @@ public: /** MIRegistrationFilterFunction type. */ typedef itk::MIRegistrationFunction<FixedImageType,MovingImageType, - DeformationFieldType> MIRegistrationFunctionType; + DeformationFieldType> MIRegistrationFunctionType; typedef typename MIRegistrationFunctionType::RadiusType RadiusType; diff --git a/Code/DisparityMap/otbMIRegistrationFilter.txx b/Code/DisparityMap/otbMIRegistrationFilter.txx index 7a0286966ff01480dd6b2012322927228b342736..03e4a3c243be1d3a2e3664b013e0f6d460ab4ae0 100644 --- a/Code/DisparityMap/otbMIRegistrationFilter.txx +++ b/Code/DisparityMap/otbMIRegistrationFilter.txx @@ -20,7 +20,8 @@ #include "otbMIRegistrationFilter.h" -namespace otb { +namespace otb +{ /* * Default constructor @@ -47,8 +48,8 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); - os << indent << "MI Radius: " << - this->GetMIRadius() << std::endl; + os << indent << "MI Radius: " << + this->GetMIRadius() << std::endl; } @@ -67,21 +68,21 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> // set the gradient selection flag MIRegistrationFunctionType *drfp = dynamic_cast<MIRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to MIRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to MIRegistrationFunction" ); + } /* * Smooth the deformation field */ if ( this->GetSmoothDeformationField() ) - { + { this->SmoothDeformationField(); - } + } } @@ -97,13 +98,13 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> MIRegistrationFunctionType *drfp = dynamic_cast<MIRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to MIRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to MIRegistrationFunction" ); + } return drfp->GetEnergy(); @@ -121,13 +122,13 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> MIRegistrationFunctionType *drfp = dynamic_cast<MIRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to MIRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to MIRegistrationFunction" ); + } return drfp->GetRadius(); @@ -144,13 +145,13 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> MIRegistrationFunctionType *drfp = dynamic_cast<MIRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to MIRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to MIRegistrationFunction" ); + } drfp->SetRadius(radius); @@ -167,21 +168,21 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> // If we smooth the update buffer before applying it, then the are // approximating a viscuous problem as opposed to an elastic problem if ( this->GetSmoothUpdateField() ) - { + { this->SmoothUpdateField(); - } + } this->Superclass::ApplyUpdate(dt); MIRegistrationFunctionType *drfp = dynamic_cast<MIRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to MIRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to MIRegistrationFunction" ); + } // this->SetRMSChange( drfp->GetRMSChange() ); @@ -192,11 +193,11 @@ void MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> ::GenerateInputRequestedRegion() { - // get pointers to the input and output + // get pointers to the input and output typename Superclass::FixedImagePointer fixedPtr = - const_cast< TFixedImage * >( this->GetFixedImage() ); + const_cast< TFixedImage * >( this->GetFixedImage() ); typename Superclass::MovingImagePointer movingPtr = - const_cast< TMovingImage * >( this->GetMovingImage() ); + const_cast< TMovingImage * >( this->GetMovingImage() ); typename TDeformationField::Pointer outputPtr = this->GetOutput(); if ( !fixedPtr || !movingPtr || !outputPtr ) @@ -204,15 +205,15 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> return; } - // get a copy of the input requested region (should equal the output - // requested region) + // get a copy of the input requested region (should equal the output + // requested region) typename TDeformationField::RegionType requestedRegion; requestedRegion = outputPtr->GetRequestedRegion(); - // pad the input requested region by the operator radius + // pad the input requested region by the operator radius requestedRegion.PadByRadius( this->GetMIRadius() ); - // crop the input requested region at the input's largest possible region + // crop the input requested region at the input's largest possible region if ( requestedRegion.Crop(fixedPtr->GetLargestPossibleRegion())) { if ( requestedRegion.Crop(movingPtr->GetLargestPossibleRegion())) @@ -223,13 +224,13 @@ MIRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> } else { - // Couldn't crop the region (requested region is outside the largest - // possible region). Throw an exception. + // Couldn't crop the region (requested region is outside the largest + // possible region). Throw an exception. - // store what we tried to request (prior to trying to crop) + // store what we tried to request (prior to trying to crop) movingPtr->SetRequestedRegion( requestedRegion ); - // build an exception + // build an exception itk::InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region of the moving image."); diff --git a/Code/DisparityMap/otbNCCRegistrationFilter.h b/Code/DisparityMap/otbNCCRegistrationFilter.h index 15399fb4750ce19098bdfa710d1959a281bb8079..0fca41f3de2e32912f037d29e2c3eb23464ddd5c 100644 --- a/Code/DisparityMap/otbNCCRegistrationFilter.h +++ b/Code/DisparityMap/otbNCCRegistrationFilter.h @@ -21,7 +21,8 @@ #include "itkPDEDeformableRegistrationFilter.h" #include "otbNCCRegistrationFunction.h" -namespace otb { +namespace otb +{ /** \class NCCRegistrationFilter * \brief Deformably register two images using the PDEs and NCC. @@ -64,14 +65,14 @@ namespace otb { */ template<class TFixedImage, class TMovingImage, class TDeformationField> class ITK_EXPORT NCCRegistrationFilter : - public itk::PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, - TDeformationField> + public itk::PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, + TDeformationField> { public: /** Standard class typedefs. */ typedef NCCRegistrationFilter Self; typedef itk::PDEDeformableRegistrationFilter< - TFixedImage, TMovingImage,TDeformationField> Superclass; + TFixedImage, TMovingImage,TDeformationField> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -105,7 +106,7 @@ public: /** NCCRegistrationFilterFunction type. */ typedef NCCRegistrationFunction<FixedImageType,MovingImageType, - DeformationFieldType> NCCRegistrationFunctionType; + DeformationFieldType> NCCRegistrationFunctionType; typedef typename NCCRegistrationFunctionType::RadiusType RadiusType; diff --git a/Code/DisparityMap/otbNCCRegistrationFilter.txx b/Code/DisparityMap/otbNCCRegistrationFilter.txx index 48b30a5a688026bed0c01fb5aa1155e19446234b..cca12df31c6571dbdcf2ccd0640629ff93d9709b 100644 --- a/Code/DisparityMap/otbNCCRegistrationFilter.txx +++ b/Code/DisparityMap/otbNCCRegistrationFilter.txx @@ -19,7 +19,8 @@ #define __otbNCCRegistrationFilter_txx #include "otbNCCRegistrationFilter.h" -namespace otb { +namespace otb +{ /* * Default constructor @@ -46,8 +47,8 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); - os << indent << "NCC Radius: " << - this->GetNCCRadius() << std::endl; + os << indent << "NCC Radius: " << + this->GetNCCRadius() << std::endl; } @@ -66,13 +67,13 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> // set the gradient selection flag NCCRegistrationFunctionType *drfp = dynamic_cast<NCCRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to NCCRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to NCCRegistrationFunction" ); + } /* @@ -97,13 +98,13 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> NCCRegistrationFunctionType *drfp = dynamic_cast<NCCRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to NCCRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to NCCRegistrationFunction" ); + } return drfp->GetEnergy(); @@ -121,13 +122,13 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> NCCRegistrationFunctionType *drfp = dynamic_cast<NCCRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to NCCRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to NCCRegistrationFunction" ); + } return drfp->GetRadius(); @@ -144,13 +145,13 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> NCCRegistrationFunctionType *drfp = dynamic_cast<NCCRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to NCCRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to NCCRegistrationFunction" ); + } drfp->SetRadius(radius); @@ -162,11 +163,11 @@ void NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> ::GenerateInputRequestedRegion() { - // get pointers to the input and output + // get pointers to the input and output typename Superclass::FixedImagePointer fixedPtr = - const_cast< TFixedImage * >( this->GetFixedImage() ); + const_cast< TFixedImage * >( this->GetFixedImage() ); typename Superclass::MovingImagePointer movingPtr = - const_cast< TMovingImage * >( this->GetMovingImage() ); + const_cast< TMovingImage * >( this->GetMovingImage() ); typename TDeformationField::Pointer outputPtr = this->GetOutput(); if ( !fixedPtr || !movingPtr || !outputPtr ) @@ -174,15 +175,15 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> return; } - // get a copy of the input requested region (should equal the output - // requested region) + // get a copy of the input requested region (should equal the output + // requested region) typename TDeformationField::RegionType requestedRegion; requestedRegion = outputPtr->GetRequestedRegion(); - // pad the input requested region by the operator radius + // pad the input requested region by the operator radius requestedRegion.PadByRadius( this->GetNCCRadius() ); - // crop the input requested region at the input's largest possible region + // crop the input requested region at the input's largest possible region if ( requestedRegion.Crop(fixedPtr->GetLargestPossibleRegion())) { if ( requestedRegion.Crop(movingPtr->GetLargestPossibleRegion())) @@ -193,13 +194,13 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> } else { - // Couldn't crop the region (requested region is outside the largest - // possible region). Throw an exception. + // Couldn't crop the region (requested region is outside the largest + // possible region). Throw an exception. - // store what we tried to request (prior to trying to crop) + // store what we tried to request (prior to trying to crop) movingPtr->SetRequestedRegion( requestedRegion ); - // build an exception + // build an exception itk::InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region of the moving image."); @@ -235,22 +236,22 @@ NCCRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> { // If we smooth the update buffer before applying it, then the are // approximating a viscuous problem as opposed to an elastic problem -/* if ( this->GetSmoothUpdateField() ) - { - this->SmoothUpdateField(); - } - */ + /* if ( this->GetSmoothUpdateField() ) + { + this->SmoothUpdateField(); + } + */ this->Superclass::ApplyUpdate(dt); NCCRegistrationFunctionType *drfp = dynamic_cast<NCCRegistrationFunctionType *> - (this->GetDifferenceFunction().GetPointer()); + (this->GetDifferenceFunction().GetPointer()); - if( !drfp ) - { - itkExceptionMacro( << - "Could not cast difference function to NCCRegistrationFunction" ); - } + if ( !drfp ) + { + itkExceptionMacro( << + "Could not cast difference function to NCCRegistrationFunction" ); + } // this->SetRMSChange( drfp->GetRMSChange() ); diff --git a/Code/DisparityMap/otbNCCRegistrationFunction.h b/Code/DisparityMap/otbNCCRegistrationFunction.h index 57781582da36186de7a5e1426c54ae88a9593358..c4eb32c0b1ae3c3f2aeb83a855551a8bdcdaa5f1 100644 --- a/Code/DisparityMap/otbNCCRegistrationFunction.h +++ b/Code/DisparityMap/otbNCCRegistrationFunction.h @@ -28,7 +28,8 @@ #include "itkLinearInterpolateImageFunction.h" #include "itkCentralDifferenceImageFunction.h" -namespace otb { +namespace otb +{ /** * \class NCCRegistrationFunction @@ -45,14 +46,14 @@ namespace otb { */ template<class TFixedImage, class TMovingImage, class TDeformationField> class ITK_EXPORT NCCRegistrationFunction : - public itk::PDEDeformableRegistrationFunction< TFixedImage, - TMovingImage, TDeformationField> + public itk::PDEDeformableRegistrationFunction< TFixedImage, + TMovingImage, TDeformationField> { public: /** Standard class typedefs. */ typedef NCCRegistrationFunction Self; typedef itk::PDEDeformableRegistrationFunction< TFixedImage, - TMovingImage, TDeformationField > Superclass; + TMovingImage, TDeformationField > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -61,7 +62,7 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro( NCCRegistrationFunction, - PDEDeformableRegistrationFunction ); + PDEDeformableRegistrationFunction ); /** MovingImage image type. */ typedef typename Superclass::MovingImageType MovingImageType; @@ -77,7 +78,7 @@ public: /** Deformation field type. */ typedef typename Superclass::DeformationFieldType DeformationFieldType; typedef typename Superclass::DeformationFieldTypePointer - DeformationFieldTypePointer; + DeformationFieldTypePointer; /** Inherit some enums from the superclass. */ itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); @@ -96,7 +97,7 @@ public: typedef typename InterpolatorType::Pointer InterpolatorPointer; typedef typename InterpolatorType::PointType PointType; typedef itk::LinearInterpolateImageFunction<MovingImageType,CoordRepType> - DefaultInterpolatorType; + DefaultInterpolatorType; /** Covariant vector type. */ typedef itk::CovariantVector<double,itkGetStaticConstMacro(ImageDimension)> CovariantVectorType; @@ -107,27 +108,35 @@ public: /** Set the moving image interpolator. */ void SetMovingImageInterpolator( InterpolatorType * ptr ) - { m_MovingImageInterpolator = ptr; } + { + m_MovingImageInterpolator = ptr; + } /** Get the moving image interpolator. */ InterpolatorType * GetMovingImageInterpolator(void) - { return m_MovingImageInterpolator; } + { + return m_MovingImageInterpolator; + } /** This class uses a constant timestep of 1. */ virtual TimeStepType ComputeGlobalTimeStep(void * itkNotUsed(GlobalData)) const - { return m_TimeStep; } + { + return m_TimeStep; + } /** Return a pointer to a global data structure that is passed to * this object from the solver at each calculation. */ virtual void *GetGlobalDataPointer() const - { + { GlobalDataStruct *global = new GlobalDataStruct(); return global; - } + } /** Release memory for global data structure. */ virtual void ReleaseGlobalDataPointer( void *GlobalData ) const - { delete (GlobalDataStruct *) GlobalData; } + { + delete (GlobalDataStruct *) GlobalData; + } /** Set the object's state before each iteration. */ virtual void InitializeIteration(); @@ -135,8 +144,8 @@ public: /** This method is called by a finite difference solver image filter at * each pixel that does not lie on a data set boundary */ virtual PixelType ComputeUpdate(const NeighborhoodType &neighborhood, - void *globalData, - const FloatOffsetType &offset = FloatOffsetType(0.0)); + void *globalData, + const FloatOffsetType &offset = FloatOffsetType(0.0)); protected: NCCRegistrationFunction(); @@ -149,9 +158,9 @@ protected: /** A global data type for this class of equation. Used to store * iterators for the fixed image. */ struct GlobalDataStruct - { - FixedImageNeighborhoodIteratorType m_FixedImageIterator; - }; + { + FixedImageNeighborhoodIteratorType m_FixedImageIterator; + }; private: diff --git a/Code/DisparityMap/otbNCCRegistrationFunction.txx b/Code/DisparityMap/otbNCCRegistrationFunction.txx index 20fcd807ce9306a270c8f86de3aedaf6dbf20969..822625d8adf7428787c4cd7ed4cd56ae6632f598 100644 --- a/Code/DisparityMap/otbNCCRegistrationFunction.txx +++ b/Code/DisparityMap/otbNCCRegistrationFunction.txx @@ -25,7 +25,8 @@ #include "itkExceptionObject.h" #include "vnl/vnl_math.h" -namespace otb { +namespace otb +{ /* * Default constructor @@ -37,10 +38,10 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> RadiusType r; unsigned int j; - for( j = 0; j < ImageDimension; j++ ) - { + for ( j = 0; j < ImageDimension; j++ ) + { r[j] = 1; - } + } this->SetRadius(r); m_MetricTotal=0.0; @@ -57,7 +58,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> DefaultInterpolatorType::New(); m_MovingImageInterpolator = static_cast<InterpolatorType*>( - interp.GetPointer() ); + interp.GetPointer() ); } @@ -73,16 +74,16 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> { Superclass::PrintSelf(os, indent); -/* - os << indent << "MovingImageIterpolator: "; - os << m_MovingImageInterpolator.GetPointer() << std::endl; - os << indent << "FixedImageGradientCalculator: "; - os << m_FixedImageGradientCalculator.GetPointer() << std::endl; - os << indent << "DenominatorThreshold: "; - os << m_DenominatorThreshold << std::endl; - os << indent << "IntensityDifferenceThreshold: "; - os << m_IntensityDifferenceThreshold << std::endl; -*/ + /* + os << indent << "MovingImageIterpolator: "; + os << m_MovingImageInterpolator.GetPointer() << std::endl; + os << indent << "FixedImageGradientCalculator: "; + os << m_FixedImageGradientCalculator.GetPointer() << std::endl; + os << indent << "DenominatorThreshold: "; + os << m_DenominatorThreshold << std::endl; + os << indent << "IntensityDifferenceThreshold: "; + os << m_IntensityDifferenceThreshold << std::endl; + */ } @@ -94,10 +95,10 @@ void NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> ::InitializeIteration() { - if( !this->m_MovingImage || !this->m_FixedImage || !m_MovingImageInterpolator ) - { + if ( !this->m_MovingImage || !this->m_FixedImage || !m_MovingImageInterpolator ) + { itkExceptionMacro( << "MovingImage, FixedImage and/or Interpolator not set" ); - } + } // cache fixed image information m_FixedImageSpacing = this->m_FixedImage->GetSpacing(); @@ -111,8 +112,8 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> std::cout << " total metric " << m_MetricTotal << " field size " << - this->GetDeformationField()->GetLargestPossibleRegion().GetSize()<< " image size " << - this->m_FixedImage->GetLargestPossibleRegion().GetSize() << std::endl; + this->GetDeformationField()->GetLargestPossibleRegion().GetSize()<< " image size " << + this->m_FixedImage->GetLargestPossibleRegion().GetSize() << std::endl; m_MetricTotal=0.0; } @@ -143,7 +144,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> itk::NeighborhoodIterator<FixedImageType> - hoodIt( hradius , img, img->GetRequestedRegion()); + hoodIt( hradius , img, img->GetRequestedRegion()); hoodIt.SetLocation(oindex); double sff=0.0; @@ -154,7 +155,8 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> double derivativeF[ImageDimension]; double derivativeM[ImageDimension]; - for (j=0; j<ImageDimension;j++){ + for (j=0; j<ImageDimension;j++) + { derivativeF[j]=0; derivativeM[j]=0; } @@ -162,7 +164,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> unsigned int indct; unsigned int hoodlen=hoodIt.Size(); - for(indct=0; indct<hoodlen-1; indct++) + for (indct=0; indct<hoodlen-1; indct++) { IndexType index=hoodIt.GetIndex(indct); @@ -178,7 +180,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> { - // Get fixed image related information + // Get fixed image related information CovariantVectorType fixedGradient; double fixedGradientSquaredMagnitude = 0; @@ -188,7 +190,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> fixedValue = (double) this->m_FixedImage->GetPixel( index ); fixedGradient = m_FixedImageGradientCalculator->EvaluateAtIndex( index ); - for( j = 0; j < ImageDimension; j++ ) + for ( j = 0; j < ImageDimension; j++ ) { fixedGradientSquaredMagnitude += vnl_math_sqr( fixedGradient[j] ) * m_FixedImageSpacing[j]; } @@ -202,32 +204,32 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> // Edited by OTB developpers DeformationPixelType vec; vec.Fill(0); - if(this->GetDeformationField()->GetBufferedRegion().IsInside(index)) - { - vec = this->GetDeformationField()->GetPixel(index); - } + if (this->GetDeformationField()->GetBufferedRegion().IsInside(index)) + { + vec = this->GetDeformationField()->GetPixel(index); + } // End Edited by OTB developpers - for( j = 0; j < ImageDimension; j++ ) - { + for ( j = 0; j < ImageDimension; j++ ) + { mappedPoint[j] = double( index[j] ) * m_FixedImageSpacing[j] + - m_FixedImageOrigin[j]; + m_FixedImageOrigin[j]; mappedPoint[j] += vec[j]; - } - if( m_MovingImageInterpolator->IsInsideBuffer( mappedPoint ) ) - { + } + if ( m_MovingImageInterpolator->IsInsideBuffer( mappedPoint ) ) + { movingValue = m_MovingImageInterpolator->Evaluate( mappedPoint ); - } + } else - { + { movingValue = 0.0; - } + } sff+=fixedValue*fixedValue; smm+=movingValue*movingValue; sfm+=fixedValue*movingValue; - for(unsigned int dim=0; dim<ImageDimension; dim++) + for (unsigned int dim=0; dim<ImageDimension; dim++) { double differential = fixedGradient[dim]; derivativeF[dim]+= fixedValue * differential; @@ -238,10 +240,10 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> } double updatenorm=0.0; - if( (sff*smm) != 0.0) + if ( (sff*smm) != 0.0) { double factor = 1.0 / vcl_sqrt(sff * smm ); - for(unsigned int i=0; i<ImageDimension; i++) + for (unsigned int i=0; i<ImageDimension; i++) { update[i] = factor * ( derivativeF[i] - (sfm/smm)*derivativeM[i]); updatenorm+=(update[i]*update[i]); @@ -252,7 +254,7 @@ NCCRegistrationFunction<TFixedImage,TMovingImage,TDeformationField> } else { - for(unsigned int i=0; i<ImageDimension; i++) + for (unsigned int i=0; i<ImageDimension; i++) { update[i] = 0.0; } diff --git a/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.h b/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.h index 1b4018d62063d971f2cdae25426a139376ad7982..b49fbfc18a5f711eab6a2dc85d08dc3d0df07252 100644 --- a/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.h @@ -28,9 +28,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT NNearestPointsLinearInterpolateDeformationFieldGenerator - : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef NNearestPointsLinearInterpolateDeformationFieldGenerator Self; typedef PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -63,7 +63,7 @@ protected: NNearestPointsLinearInterpolateDeformationFieldGenerator() {}; /** Destructor */ virtual ~NNearestPointsLinearInterpolateDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.txx b/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.txx index 8a76319ede0d7c145f46a1b03b27909169fad047..e896fd9a0445201e97699259ad936d129b572e46 100644 --- a/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbNNearestPointsLinearInterpolateDeformationFieldGenerator.txx @@ -41,42 +41,42 @@ NNearestPointsLinearInterpolateDeformationFieldGenerator<TPointSet, TDeformation typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> IteratorType; IteratorType it(outputPtr,outputPtr->GetRequestedRegion()); - for(it.GoToBegin();!it.IsAtEnd();++it) - { - IndexType index = it.GetIndex(); - IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),m_NumberOfPoints); - PixelType pixel(2); - double xdeformation, ydeformation,normalization; - xdeformation = 0; - ydeformation = 0; - normalization = 0; - - for(typename IndexVectorType::iterator indexIt=indexVector.begin();indexIt!=indexVector.end();++indexIt) + for (it.GoToBegin();!it.IsAtEnd();++it) { - PointType point; - point[0] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[0]); - point[1] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[1]); - double distance = this->EuclideanDistance(index,point); - if(distance<EPSILON) + IndexType index = it.GetIndex(); + IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),m_NumberOfPoints); + PixelType pixel(2); + double xdeformation, ydeformation,normalization; + xdeformation = 0; + ydeformation = 0; + normalization = 0; + + for (typename IndexVectorType::iterator indexIt=indexVector.begin();indexIt!=indexVector.end();++indexIt) + { + PointType point; + point[0] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[0]); + point[1] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[1]); + double distance = this->EuclideanDistance(index,point); + if (distance<EPSILON) { distance = EPSILON; } - xdeformation += this->GetPointSet()->GetPointData()->GetElement((*indexIt))[1]/distance; - ydeformation += this->GetPointSet()->GetPointData()->GetElement((*indexIt))[2]/distance; - normalization+=1/distance; - } + xdeformation += this->GetPointSet()->GetPointData()->GetElement((*indexIt))[1]/distance; + ydeformation += this->GetPointSet()->GetPointData()->GetElement((*indexIt))[2]/distance; + normalization+=1/distance; + } - if(normalization>0) - { - pixel[0] = static_cast<ValueType>(xdeformation/normalization); - pixel[1] = static_cast<ValueType>(ydeformation/normalization); - } - else - { - pixel=defaultValue; - } - it.Set(pixel); + if (normalization>0) + { + pixel[0] = static_cast<ValueType>(xdeformation/normalization); + pixel[1] = static_cast<ValueType>(ydeformation/normalization); } + else + { + pixel=defaultValue; + } + it.Set(pixel); + } } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.h b/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.h index 169ba3259dbbf47a46ca12c5ae1462e83e8d3406..1f375590cb11fa42c765288b773b998f86b4b137 100644 --- a/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.h @@ -29,9 +29,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT NNearestTransformsLinearInterpolateDeformationFieldGenerator - : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef NNearestTransformsLinearInterpolateDeformationFieldGenerator Self; typedef PointSetWithTransformToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -67,7 +67,7 @@ protected: NNearestTransformsLinearInterpolateDeformationFieldGenerator() {}; /** Destructor */ virtual ~NNearestTransformsLinearInterpolateDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.txx b/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.txx index 9fc80011ec3a6d476b1dc712c11f485e567fd505..684bcd9fd41309fa3ec7877f14646a08520ff628 100644 --- a/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbNNearestTransformsLinearInterpolateDeformationFieldGenerator.txx @@ -41,53 +41,53 @@ NNearestTransformsLinearInterpolateDeformationFieldGenerator<TPointSet, TDeforma typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> IteratorType; IteratorType it(outputPtr,outputPtr->GetRequestedRegion()); - for(it.GoToBegin();!it.IsAtEnd();++it) - { - IndexType index = it.GetIndex(); - IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),m_NumberOfPoints); - PixelType pixel(2); - double xdeformation, ydeformation,normalization; - xdeformation = 0; - ydeformation = 0; - normalization = 0; - - for(typename IndexVectorType::iterator indexIt=indexVector.begin();indexIt!=indexVector.end();++indexIt) + for (it.GoToBegin();!it.IsAtEnd();++it) { - PointType point; - point[0] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[0]); - point[1] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[1]); - double distance = this->EuclideanDistance(index,point); - if(distance<EPSILON) + IndexType index = it.GetIndex(); + IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),m_NumberOfPoints); + PixelType pixel(2); + double xdeformation, ydeformation,normalization; + xdeformation = 0; + ydeformation = 0; + normalization = 0; + + for (typename IndexVectorType::iterator indexIt=indexVector.begin();indexIt!=indexVector.end();++indexIt) + { + PointType point; + point[0] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[0]); + point[1] = static_cast<double>(this->GetPointSet()->GetPoints()->GetElement(*indexIt)[1]); + double distance = this->EuclideanDistance(index,point); + if (distance<EPSILON) { distance = EPSILON; } - ParametersType params(this->GetTransform()->GetNumberOfParameters()); - for(unsigned int i = 0; i<this->GetTransform()->GetNumberOfParameters();++i) + ParametersType params(this->GetTransform()->GetNumberOfParameters()); + for (unsigned int i = 0; i<this->GetTransform()->GetNumberOfParameters();++i) { params[i] = this->GetPointSet()->GetPointData()->GetElement((*indexIt))[i+3]; } - this->GetTransform()->SetParameters(params); - PointType sourcePoint,targetPoint; + this->GetTransform()->SetParameters(params); + PointType sourcePoint,targetPoint; - outputPtr->TransformIndexToPhysicalPoint(it.GetIndex(),sourcePoint); - targetPoint = this->GetTransform()->TransformPoint(sourcePoint); - xdeformation += (targetPoint[0]-sourcePoint[0])/distance; - ydeformation += (targetPoint[1]-sourcePoint[1]) /distance; - normalization+=1/distance; - } + outputPtr->TransformIndexToPhysicalPoint(it.GetIndex(),sourcePoint); + targetPoint = this->GetTransform()->TransformPoint(sourcePoint); + xdeformation += (targetPoint[0]-sourcePoint[0])/distance; + ydeformation += (targetPoint[1]-sourcePoint[1]) /distance; + normalization+=1/distance; + } - if(normalization>0) - { - pixel[0] = static_cast<ValueType>(xdeformation/normalization); - pixel[1] = static_cast<ValueType>(ydeformation/normalization); - } - else - { - pixel=defaultValue; - } - it.Set(pixel); + if (normalization>0) + { + pixel[0] = static_cast<ValueType>(xdeformation/normalization); + pixel[1] = static_cast<ValueType>(ydeformation/normalization); } + else + { + pixel=defaultValue; + } + it.Set(pixel); + } } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.h b/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.h index cea13d5aee8cedf0c02f1cf3eb92bbebe752bfb1..13bb5b3e852deb461d58a8e7e07e6ddd9cc69aa5 100644 --- a/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.h @@ -30,9 +30,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT NearestPointDeformationFieldGenerator - : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef NearestPointDeformationFieldGenerator Self; typedef PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -60,7 +60,7 @@ protected: NearestPointDeformationFieldGenerator() {}; /** Destructor */ virtual ~NearestPointDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.txx b/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.txx index b8ce7a42c74ef3967e33102287b4012bf3b3bfdc..9a588fb7a2b327732346cdfdb8c9cf90b4fcf94f 100644 --- a/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbNearestPointDeformationFieldGenerator.txx @@ -39,21 +39,21 @@ NearestPointDeformationFieldGenerator<TPointSet, TDeformationField> typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> IteratorType; IteratorType it(outputPtr,outputPtr->GetRequestedRegion()); - for(it.GoToBegin();!it.IsAtEnd();++it) + for (it.GoToBegin();!it.IsAtEnd();++it) + { + IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),1); + PixelType p(2); + if (indexVector.size()>=1) { - IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),1); - PixelType p(2); - if(indexVector.size()>=1) - { - p[0] = static_cast<ValueType>(this->GetPointSet()->GetPointData()->GetElement(indexVector[0])[1]); - p[1] = static_cast<ValueType>(this->GetPointSet()->GetPointData()->GetElement(indexVector[0])[2]); - } - else - { - p=defaultValue; - } - it.Set(p); + p[0] = static_cast<ValueType>(this->GetPointSet()->GetPointData()->GetElement(indexVector[0])[1]); + p[1] = static_cast<ValueType>(this->GetPointSet()->GetPointData()->GetElement(indexVector[0])[2]); } + else + { + p=defaultValue; + } + it.Set(p); + } } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.h b/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.h index 0cfaea4d9c72ba49111287348d795dac4586108a..2aa55304ee877822b9bb05744b7e019bf1d72b0f 100644 --- a/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.h @@ -30,9 +30,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT NearestTransformDeformationFieldGenerator - : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> + : public PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> { - public: +public: /** Standard typedefs */ typedef NearestTransformDeformationFieldGenerator Self; typedef PointSetWithTransformToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -63,7 +63,7 @@ protected: NearestTransformDeformationFieldGenerator() {}; /** Destructor */ virtual ~NearestTransformDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(); diff --git a/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.txx b/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.txx index b8e8b3137ced9c23f71131d2575de341e4a45438..8d0082fea520fd02873d626df2d36cbda8387901 100644 --- a/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbNearestTransformDeformationFieldGenerator.txx @@ -39,31 +39,31 @@ NearestTransformDeformationFieldGenerator<TPointSet, TDeformationField> typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> IteratorType; IteratorType it(outputPtr,outputPtr->GetRequestedRegion()); - for(it.GoToBegin();!it.IsAtEnd();++it) + for (it.GoToBegin();!it.IsAtEnd();++it) + { + IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),1); + PixelType pixel(2); + if (indexVector.size()>=1) { - IndexVectorType indexVector = this->GenerateNearestValidPointsPointSet(it.GetIndex(),1); - PixelType pixel(2); - if(indexVector.size()>=1) - { - ParametersType params(this->GetTransform()->GetNumberOfParameters()); - for(unsigned int i = 0; i<this->GetTransform()->GetNumberOfParameters();++i) + ParametersType params(this->GetTransform()->GetNumberOfParameters()); + for (unsigned int i = 0; i<this->GetTransform()->GetNumberOfParameters();++i) { params[i] = this->GetPointSet()->GetPointData()->GetElement(indexVector[0])[i+3]; } - this->GetTransform()->SetParameters(params); - PointType sourcePoint,targetPoint; + this->GetTransform()->SetParameters(params); + PointType sourcePoint,targetPoint; - outputPtr->TransformIndexToPhysicalPoint(it.GetIndex(),sourcePoint); - targetPoint = this->GetTransform()->TransformPoint(sourcePoint); - pixel[0] = static_cast<ValueType>(targetPoint[0]-sourcePoint[0]); - pixel[1] = static_cast<ValueType>(targetPoint[1]-sourcePoint[1]); - } - else - { - pixel=defaultValue; - } - it.Set(pixel); + outputPtr->TransformIndexToPhysicalPoint(it.GetIndex(),sourcePoint); + targetPoint = this->GetTransform()->TransformPoint(sourcePoint); + pixel[0] = static_cast<ValueType>(targetPoint[0]-sourcePoint[0]); + pixel[1] = static_cast<ValueType>(targetPoint[1]-sourcePoint[1]); } + else + { + pixel=defaultValue; + } + it.Set(pixel); + } } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbPointSetBasedResamplingFilter.h b/Code/DisparityMap/otbPointSetBasedResamplingFilter.h index 0110f46e939f14addca29caf8f989a12a8906384..4473573f5e71a1982e04f8c158f284126ae0f9b8 100644 --- a/Code/DisparityMap/otbPointSetBasedResamplingFilter.h +++ b/Code/DisparityMap/otbPointSetBasedResamplingFilter.h @@ -32,9 +32,9 @@ namespace otb template <class TInputImage, class TPointSet, class TOutputImage> class ITK_EXPORT PointSetBasedResamplingFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef PointSetBasedResamplingFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -83,37 +83,37 @@ class ITK_EXPORT PointSetBasedResamplingFilter * Get the pointset containing the disparity. * \return The pointset containing the disparity. */ - const TPointSet * GetPointSet(void); + const TPointSet * GetPointSet(void); - itkSetMacro(MetricThreshold,double); - itkGetMacro(MetricThreshold,double); - itkSetMacro(OutputSize,SizeType); - itkGetConstReferenceMacro(OutputSize,SizeType); - itkSetMacro(OutputSpacing,SpacingType); - itkGetConstReferenceMacro(OutputSpacing,SpacingType); - itkSetMacro(OutputOrigin,PointType); - itkGetConstReferenceMacro(OutputOrigin,PointType); + itkSetMacro(MetricThreshold,double); + itkGetMacro(MetricThreshold,double); + itkSetMacro(OutputSize,SizeType); + itkGetConstReferenceMacro(OutputSize,SizeType); + itkSetMacro(OutputSpacing,SpacingType); + itkGetConstReferenceMacro(OutputSpacing,SpacingType); + itkSetMacro(OutputOrigin,PointType); + itkGetConstReferenceMacro(OutputOrigin,PointType); - /** Set/Get the Transfrom. */ - itkSetObjectMacro(Transform,TransformType); - itkGetObjectMacro(Transform,TransformType); + /** Set/Get the Transfrom. */ + itkSetObjectMacro(Transform,TransformType); + itkGetObjectMacro(Transform,TransformType); - /** Set/Get the Interpolator. */ - itkSetObjectMacro(Interpolator,InterpolatorType); - itkGetObjectMacro(Interpolator,InterpolatorType); + /** Set/Get the Interpolator. */ + itkSetObjectMacro(Interpolator,InterpolatorType); + itkGetObjectMacro(Interpolator,InterpolatorType); protected: /** Constructor */ PointSetBasedResamplingFilter(); /** Destructor */ virtual ~PointSetBasedResamplingFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(void); - /** Generate output information */ + /** Generate output information */ virtual void GenerateOutputInformation(void); /** * \return The parameters of the transform associated with the nearest suitable point in pointset. @@ -137,9 +137,9 @@ private: /** Default value */ OutputPixelType m_DefaultValue; - /** - * The transform used for local registration. - */ + /** + * The transform used for local registration. + */ TransformPointerType m_Transform; /** * The interpolator used for local registration. diff --git a/Code/DisparityMap/otbPointSetBasedResamplingFilter.txx b/Code/DisparityMap/otbPointSetBasedResamplingFilter.txx index 74bd2f937e382a5d33a3cc98d980b3257067c5c0..66d67943d03f27192c498e4be2f1b85be3f3e024 100644 --- a/Code/DisparityMap/otbPointSetBasedResamplingFilter.txx +++ b/Code/DisparityMap/otbPointSetBasedResamplingFilter.txx @@ -92,28 +92,28 @@ PointSetBasedResamplingFilter<TInputImage, TPointSet, TOutputImage> typedef itk::ImageRegionIteratorWithIndex<OutputImageType> IteratorType; IteratorType outputIt(outputPtr,outputPtr->GetRequestedRegion()); - for(outputIt.GoToBegin();!outputIt.IsAtEnd();++outputIt) - { - PointType outputPoint,inputPoint; - IndexType index; - typename TransformType::Pointer inverseTransform; - - index = outputIt.GetIndex(); - m_Transform->SetParameters(this->GetNearestPointTransformParameters(index)); - m_Transform->GetInverse(inverseTransform); - outputPtr->TransformIndexToPhysicalPoint(index,outputPoint); - inputPoint = inverseTransform->TransformPoint(outputPoint); - otbMsgDevMacro(<<"back point: "<<inputPoint<<"(inverse trasform param: "<<inverseTransform->GetParameters()<<")"); - - if(m_Interpolator->IsInsideBuffer(inputPoint)) - { - outputIt.Set(m_Interpolator->Evaluate(inputPoint)); - } - else + for (outputIt.GoToBegin();!outputIt.IsAtEnd();++outputIt) { - outputIt.Set(m_DefaultValue); - } + PointType outputPoint,inputPoint; + IndexType index; + typename TransformType::Pointer inverseTransform; + + index = outputIt.GetIndex(); + m_Transform->SetParameters(this->GetNearestPointTransformParameters(index)); + m_Transform->GetInverse(inverseTransform); + outputPtr->TransformIndexToPhysicalPoint(index,outputPoint); + inputPoint = inverseTransform->TransformPoint(outputPoint); + otbMsgDevMacro(<<"back point: "<<inputPoint<<"(inverse trasform param: "<<inverseTransform->GetParameters()<<")"); + + if (m_Interpolator->IsInsideBuffer(inputPoint)) + { + outputIt.Set(m_Interpolator->Evaluate(inputPoint)); + } + else + { + outputIt.Set(m_DefaultValue); } + } } /** * \return The parameters of the transform associated with the nearest suitable point in pointset. @@ -138,33 +138,33 @@ PointSetBasedResamplingFilter<TInputImage, TPointSet, TOutputImage> PointType indexPoint; outputPtr->TransformIndexToPhysicalPoint(index,indexPoint); - for(;it!=this->GetPointSet()->GetPoints()->End()&&itData!=this->GetPointSet()->GetPointData()->End();++it,++itData) - { - // If the point has a sufficient score - if(vcl_abs(itData.Value()[0])>m_MetricThreshold) + for (;it!=this->GetPointSet()->GetPoints()->End()&&itData!=this->GetPointSet()->GetPointData()->End();++it,++itData) { - ParametersType tmpParameters(m_Transform->GetNumberOfParameters()); - PointType inputPoint, outputPoint; + // If the point has a sufficient score + if (vcl_abs(itData.Value()[0])>m_MetricThreshold) + { + ParametersType tmpParameters(m_Transform->GetNumberOfParameters()); + PointType inputPoint, outputPoint; - for(unsigned int i = 0; i<m_Transform->GetNumberOfParameters();++i) + for (unsigned int i = 0; i<m_Transform->GetNumberOfParameters();++i) { tmpParameters[i]=itData.Value()[i+1]; } - inputPoint[0] = it.Value()[0]; - inputPoint[1] = it.Value()[1]; + inputPoint[0] = it.Value()[0]; + inputPoint[1] = it.Value()[1]; - m_Transform->SetParameters(tmpParameters); - outputPoint = m_Transform->TransformPoint(inputPoint); - // compute the distance to current point - double d = vcl_pow(outputPoint[0]-indexPoint[0],2) + vcl_pow(outputPoint[1]-indexPoint[1],2); + m_Transform->SetParameters(tmpParameters); + outputPoint = m_Transform->TransformPoint(inputPoint); + // compute the distance to current point + double d = vcl_pow(outputPoint[0]-indexPoint[0],2) + vcl_pow(outputPoint[1]-indexPoint[1],2); - if(distance<0||distance>d) + if (distance<0||distance>d) { distance = d; parameters = tmpParameters; } - } } + } return parameters; } diff --git a/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.h b/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.h index ff7459019884c60f1a1966f386660cd10d7bf31d..b245e99038f147a644500feea21739aa9ab1eaac 100644 --- a/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.h @@ -23,35 +23,35 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class DistanceComparisonFunctor - * \brief This functor is used in nearest neighborhood sorting. - * \ingroup DisparityMap - */ - class DistanceComparisonFunctor - { - public: - DistanceComparisonFunctor(){}; - ~DistanceComparisonFunctor(){}; +{ +/** \class DistanceComparisonFunctor + * \brief This functor is used in nearest neighborhood sorting. + * \ingroup DisparityMap + */ +class DistanceComparisonFunctor +{ +public: + DistanceComparisonFunctor() {}; + ~DistanceComparisonFunctor() {}; typedef std::vector<double> DistanceVectorType; void SetDistanceVector(DistanceVectorType &vec) - { - m_DistanceVector = vec; - } + { + m_DistanceVector = vec; + } DistanceVectorType GetDistanceVector(void) - { - return m_DistanceVector; - } + { + return m_DistanceVector; + } inline bool operator()(const unsigned int a1, const unsigned int a2) - { - return m_DistanceVector[a1]<m_DistanceVector[a2]; - } + { + return m_DistanceVector[a1]<m_DistanceVector[a2]; + } - private: +private: DistanceVectorType m_DistanceVector; - }; - } +}; +} /** \class PointSetToDeformationFieldGenerator * \brief Base class for filters generating a deformation field from a point set enriched with deformation and local transform information. * The output of the filters deriving from this base class can be passed to the itk::WarpImageFilter for image resampling. @@ -61,9 +61,9 @@ namespace Functor */ template <class TPointSet, class TDeformationField> class ITK_EXPORT PointSetToDeformationFieldGenerator - : public itk::ImageSource<TDeformationField> + : public itk::ImageSource<TDeformationField> { - public: +public: /** Standard typedefs */ typedef PointSetToDeformationFieldGenerator Self; typedef itk::ImageSource<TDeformationField> Superclass; @@ -101,26 +101,26 @@ class ITK_EXPORT PointSetToDeformationFieldGenerator * Get the pointset containing the disparity. * \return The pointset containing the disparity. */ - const TPointSet * GetPointSet(void); + const TPointSet * GetPointSet(void); - itkSetMacro(MetricThreshold,double); - itkGetMacro(MetricThreshold,double); - itkSetMacro(DefaultValue,ValueType); - itkGetMacro(DefaultValue,ValueType); - itkSetMacro(OutputSize,SizeType); - itkGetConstReferenceMacro(OutputSize,SizeType); - itkSetMacro(OutputSpacing,SpacingType); - itkGetConstReferenceMacro(OutputSpacing,SpacingType); - itkSetMacro(OutputOrigin,PointType); - itkGetConstReferenceMacro(OutputOrigin,PointType); + itkSetMacro(MetricThreshold,double); + itkGetMacro(MetricThreshold,double); + itkSetMacro(DefaultValue,ValueType); + itkGetMacro(DefaultValue,ValueType); + itkSetMacro(OutputSize,SizeType); + itkGetConstReferenceMacro(OutputSize,SizeType); + itkSetMacro(OutputSpacing,SpacingType); + itkGetConstReferenceMacro(OutputSpacing,SpacingType); + itkSetMacro(OutputOrigin,PointType); + itkGetConstReferenceMacro(OutputOrigin,PointType); protected: /** Constructor */ PointSetToDeformationFieldGenerator(); /** Destructor */ virtual ~PointSetToDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Generate output information */ virtual void GenerateOutputInformation(void); diff --git a/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.txx b/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.txx index 134143444e3fb474dcf7b08500d3e7490a1dd561..01de60dfcb7a3b87dffbec96a0c90bc1d4080f80 100644 --- a/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbPointSetToDeformationFieldGenerator.txx @@ -36,7 +36,7 @@ PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> m_OutputSpacing.Fill(1.); m_OutputOrigin.Fill(0.); m_DefaultValue = 0; - // m_NearestPoints = PointSetType::New(); +// m_NearestPoints = PointSetType::New(); } /** * Set the pointset containing the disparity. @@ -100,21 +100,21 @@ PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> typedef typename PointSetType::PointsContainer::ConstIterator PointSetIteratorType; typedef typename PointSetType::PointsContainer PointsContainerType; PointSetIteratorType it = this->GetPointSet()->GetPoints()->Begin(); - for(;it!=this->GetPointSet()->GetPoints()->End();++it) - { - PointType p; - p[0]=it.Value()[0]; - p[1]=it.Value()[1]; - if(vcl_abs(this->GetPointSet()->GetPointData()->GetElement(j)[0])>=m_MetricThreshold) + for (;it!=this->GetPointSet()->GetPoints()->End();++it) { + PointType p; + p[0]=it.Value()[0]; + p[1]=it.Value()[1]; + if (vcl_abs(this->GetPointSet()->GetPointData()->GetElement(j)[0])>=m_MetricThreshold) + { - distanceVector.push_back(EuclideanDistance(index,p)); - sortVector.push_back(i); - indexVector.push_back(j); - ++i; - } - ++j; + distanceVector.push_back(EuclideanDistance(index,p)); + sortVector.push_back(i); + indexVector.push_back(j); + ++i; } + ++j; + } ComparisonFunctorType comp; comp.SetDistanceVector(distanceVector); @@ -123,10 +123,10 @@ PointSetToDeformationFieldGenerator<TPointSet, TDeformationField> // building output vector unsigned int nbElements = (n<indexVector.size() ? n : indexVector.size()); IndexVectorType output; - for(i=0;i<nbElements;i++) - { - output.push_back(indexVector[sortVector[i]]); - } + for (i=0;i<nbElements;i++) + { + output.push_back(indexVector[sortVector[i]]); + } return output; } diff --git a/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.h b/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.h index 26d2034b8a00b72b166533fd0211418abe0c154d..0f1193d1b586c4ab23159d0b727c5f27a365ac3b 100644 --- a/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.h +++ b/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.h @@ -32,9 +32,9 @@ namespace otb */ template <class TPointSet, class TDeformationField> class ITK_EXPORT PointSetWithTransformToDeformationFieldGenerator - : public PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> + : public PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> { - public: +public: /** Standard typedefs */ typedef PointSetWithTransformToDeformationFieldGenerator Self; typedef PointSetToDeformationFieldGenerator<TPointSet,TDeformationField> Superclass; @@ -77,7 +77,7 @@ protected: PointSetWithTransformToDeformationFieldGenerator(); /** Destructor */ virtual ~PointSetWithTransformToDeformationFieldGenerator() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.txx b/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.txx index 8cbf8e624bf05ed78a7ce1f90ea3203a89ef9597..a4437f453090e0c39dc49801170aeb2f230abde9 100644 --- a/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.txx +++ b/Code/DisparityMap/otbPointSetWithTransformToDeformationFieldGenerator.txx @@ -31,7 +31,7 @@ template <class TPointSet, class TDeformationField> PointSetWithTransformToDeformationFieldGenerator<TPointSet, TDeformationField> ::PointSetWithTransformToDeformationFieldGenerator() { - m_Transform = 0; // has to be provided by the user + m_Transform = 0; // has to be provided by the user } /** * PrintSelf Method diff --git a/Code/DisparityMap/otbStreamingWarpImageFilter.h b/Code/DisparityMap/otbStreamingWarpImageFilter.h index 93afac74d099a95d2e649432eef1758f4ce5d5fa..a8889c0ed99af157e304ac91dff82d068f2d11ad 100644 --- a/Code/DisparityMap/otbStreamingWarpImageFilter.h +++ b/Code/DisparityMap/otbStreamingWarpImageFilter.h @@ -45,7 +45,7 @@ namespace otb template <class TInputImage, class TOutputImage, class TDeformationField> class ITK_EXPORT StreamingWarpImageFilter - : public itk::WarpImageFilter< TInputImage, TOutputImage, TDeformationField > + : public itk::WarpImageFilter< TInputImage, TOutputImage, TDeformationField > { public: /** Standard class typedefs. */ @@ -57,7 +57,7 @@ public: /** Method for creation through the object factory. */ itkNewMacro(Self); - /** Run-time type information (and related methods). */ + /** Run-time type information (and related methods). */ itkTypeMacro(StreamingWarpImageFilter, itk::WarpImageFilter); /** template parameters typedef */ diff --git a/Code/DisparityMap/otbStreamingWarpImageFilter.txx b/Code/DisparityMap/otbStreamingWarpImageFilter.txx index 0b4cd45409ef6457fba069f1f348a50cc1b63908..b0811ebec191fc4cebe636f9e22cea34fbcb2cc8 100644 --- a/Code/DisparityMap/otbStreamingWarpImageFilter.txx +++ b/Code/DisparityMap/otbStreamingWarpImageFilter.txx @@ -49,10 +49,10 @@ StreamingWarpImageFilter<TInputImage,TOutputImage,TDeformationField> DeformationFieldType * deformationPtr = const_cast<DeformationFieldType*>(this->GetDeformationField()); // Check if the input and the deformation field exist - if(!inputPtr || !deformationPtr) - { - return; - } + if (!inputPtr || !deformationPtr) + { + return; + } // Compute the security margin radius typename InputImageType::SizeType radius; @@ -62,10 +62,10 @@ StreamingWarpImageFilter<TInputImage,TOutputImage,TDeformationField> unsigned int interpolatorRadius = StreamingTraits<typename Superclass::InputImageType>::CalculateNeededRadiusForInterpolator(this->GetInterpolator()); // Compute the margin due to the maximum deformation value and interpolator radius - for(unsigned int i = 0; i<InputImageType::ImageDimension;++i) - { - radius[i]= interpolatorRadius + static_cast<unsigned int>(vcl_ceil(m_MaximumDeformation[i]/vcl_abs(spacing[i]))); - } + for (unsigned int i = 0; i<InputImageType::ImageDimension;++i) + { + radius[i]= interpolatorRadius + static_cast<unsigned int>(vcl_ceil(m_MaximumDeformation[i]/vcl_abs(spacing[i]))); + } otbMsgDevMacro(<<"WarpImageFilter: MaximumDeformation: "<<m_MaximumDeformation<<", interpolator radius: "<<interpolatorRadius<<", total radius: "<<radius); @@ -79,12 +79,12 @@ StreamingWarpImageFilter<TInputImage,TOutputImage,TDeformationField> // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -97,7 +97,7 @@ StreamingWarpImageFilter<TInputImage,TOutputImage,TDeformationField> e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } template<class TInputImage, class TOutputImage, class TDeformationField> diff --git a/Code/FeatureExtraction/otbAddCarvingPathFilter.txx b/Code/FeatureExtraction/otbAddCarvingPathFilter.txx index 3ec07255a40fc9fbb3f894aed00078c29dc4dc90..a522d65a9dc68ddfd5da3543e1923f5050e1a8f4 100644 --- a/Code/FeatureExtraction/otbAddCarvingPathFilter.txx +++ b/Code/FeatureExtraction/otbAddCarvingPathFilter.txx @@ -69,7 +69,7 @@ AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> InputIteratorType inputIterator(inputImage, inputImage->GetLargestPossibleRegion()); OutputIteratorType outputIterator(outputImage, - outputImage->GetLargestPossibleRegion()); + outputImage->GetLargestPossibleRegion()); unsigned int dir0; unsigned int dir1; @@ -104,7 +104,7 @@ AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> //go to the end of the path pathIterator = vertexList->Begin(); - while(pathIterator != vertexList->End()) + while (pathIterator != vertexList->End()) { ++pathIterator; } @@ -115,21 +115,21 @@ AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> while (!outputIterator.IsAtEndOfSlice()) { bool flag = false; - while(!outputIterator.IsAtEndOfLine()) + while (!outputIterator.IsAtEndOfLine()) { index = outputIterator.GetIndex(); - if(index[dir1] != line) + if (index[dir1] != line) { line = index[dir1]; typename InputImageType::PointType tmpIndex; inputImage->TransformContinuousIndexToPhysicalPoint(pathIterator.Value(),tmpIndex); inputImage->TransformPhysicalPointToIndex(tmpIndex,indexToAdd); - if(pathIterator != vertexList->Begin()) + if (pathIterator != vertexList->Begin()) { --pathIterator; } - if(index[dir1] != indexToAdd[dir1]) + if (index[dir1] != indexToAdd[dir1]) { itkExceptionMacro(<< "Error : " << index[dir1] << " , " << indexToAdd[dir1]); } @@ -154,7 +154,7 @@ AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> } - if((outputIterator.GetIndex())[dir0] != (inputIterator.GetIndex())[dir0]+1) + if ((outputIterator.GetIndex())[dir0] != (inputIterator.GetIndex())[dir0]+1) { itkExceptionMacro(<< "Error 2: "<< (outputIterator.GetIndex())[dir0] << " , " << (inputIterator.GetIndex())[dir0]); } @@ -184,9 +184,9 @@ AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> template <class TInputImage, class TInputPath,class TOutputImage> - void - AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> - ::GenerateOutputInformation() +void +AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> +::GenerateOutputInformation() { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); @@ -212,11 +212,11 @@ template <class TInputImage, class TInputPath,class TOutputImage> // we need to compute the output spacing, the output image size, and the // output image start index const typename TInputImage::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename TInputImage::SizeType& inputSize - = inputPtr->GetLargestPossibleRegion().GetSize(); + = inputPtr->GetLargestPossibleRegion().GetSize(); const typename TInputImage::IndexType& inputStartIndex - = inputPtr->GetLargestPossibleRegion().GetIndex(); + = inputPtr->GetLargestPossibleRegion().GetIndex(); typename TOutputImage::SpacingType outputSpacing; typename TOutputImage::SizeType outputSize; @@ -242,15 +242,15 @@ template <class TInputImage, class TInputPath,class TOutputImage> } template <class TInputImage, class TInputPath,class TOutputImage> - void - AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> - ::GenerateInputRequestedRegion() +void +AddCarvingPathFilter<TInputImage,TInputPath,TOutputImage> +::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output InputImagePointer inputPtr = - const_cast< InputImageType * >( this->GetInput() ); + const_cast< InputImageType * >( this->GetInput() ); if ( !inputPtr ) { itkExceptionMacro( << "Input has not been set." ); diff --git a/Code/FeatureExtraction/otbAssociativeSymmetricalSumImageFilter.h b/Code/FeatureExtraction/otbAssociativeSymmetricalSumImageFilter.h index 5695fde9d4ab72e46e48b6e14b40591c045cbd07..0ad1fb5ede7f5cd24b351fe8e0c70821027d4149 100644 --- a/Code/FeatureExtraction/otbAssociativeSymmetricalSumImageFilter.h +++ b/Code/FeatureExtraction/otbAssociativeSymmetricalSumImageFilter.h @@ -39,9 +39,9 @@ namespace otb namespace Functor { - /** \class AssociativeSymmetricalSum - * \brief Functor used with the AssociativeSymmetricalSumImageFilter. - */ +/** \class AssociativeSymmetricalSum + * \brief Functor used with the AssociativeSymmetricalSumImageFilter. + */ template< class TInput1, class TInput2, class TOutput> class ITK_EXPORT AssociativeSymmetricalSum { @@ -64,21 +64,21 @@ public: template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT AssociativeSymmetricalSumImageFilter : - public -itk::BinaryFunctorImageFilter<TInputImage1,TInputImage2,TOutputImage, - Functor::AssociativeSymmetricalSum< - typename TInputImage1::PixelType, - typename TInputImage2::PixelType, - typename TOutputImage::PixelType> > + public + itk::BinaryFunctorImageFilter<TInputImage1,TInputImage2,TOutputImage, + Functor::AssociativeSymmetricalSum< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef AssociativeSymmetricalSumImageFilter Self; typedef itk::BinaryFunctorImageFilter<TInputImage1,TInputImage2,TOutputImage, - Functor::AssociativeSymmetricalSum< - typename TInputImage1::PixelType, - typename TInputImage1::PixelType, - typename TOutputImage::PixelType> + Functor::AssociativeSymmetricalSum< + typename TInputImage1::PixelType, + typename TInputImage1::PixelType, + typename TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/FeatureExtraction/otbAssymmetricFusionOfLineDetectorImageFilter.h b/Code/FeatureExtraction/otbAssymmetricFusionOfLineDetectorImageFilter.h index 4a22622cf29785b81f4a62fcde55266b69e0ecbf..0863e581cf9605c28088ffe73be9db073f9a6c93 100644 --- a/Code/FeatureExtraction/otbAssymmetricFusionOfLineDetectorImageFilter.h +++ b/Code/FeatureExtraction/otbAssymmetricFusionOfLineDetectorImageFilter.h @@ -39,19 +39,19 @@ namespace otb */ template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage, - class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > +class TOutputImage, +class TOutputImageDirection = TOutputImage, +class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > class ITK_EXPORT AssymmetricFusionOfLineDetectorImageFilter : - public LineDetectorImageFilterBase< TInputImage, TOutputImage, TOutputImageDirection, TInterpolator > + public LineDetectorImageFilterBase< TInputImage, TOutputImage, TOutputImageDirection, TInterpolator > { public: itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); typedef AssymmetricFusionOfLineDetectorImageFilter Self; diff --git a/Code/FeatureExtraction/otbBreakAngularPathListFilter.h b/Code/FeatureExtraction/otbBreakAngularPathListFilter.h index c7ce394dceaec3aa61cd2c628ef6844168a648d2..09b1be4abcabe4c64adea2d45e983983e786fa12 100644 --- a/Code/FeatureExtraction/otbBreakAngularPathListFilter.h +++ b/Code/FeatureExtraction/otbBreakAngularPathListFilter.h @@ -31,9 +31,9 @@ namespace otb */ template <class TPath> class ITK_EXPORT BreakAngularPathListFilter - : public PathListToPathListFilter<TPath> + : public PathListToPathListFilter<TPath> { - public: +public: /** Standard typedefs */ typedef BreakAngularPathListFilter Self; typedef PathListToPathListFilter<TPath> Superclass; diff --git a/Code/FeatureExtraction/otbBreakAngularPathListFilter.txx b/Code/FeatureExtraction/otbBreakAngularPathListFilter.txx index 86b5da580ea3f5d934be419cbabff834779aa5e8..3bc13d54d715ca99bca00cbecff2f42a17266483 100644 --- a/Code/FeatureExtraction/otbBreakAngularPathListFilter.txx +++ b/Code/FeatureExtraction/otbBreakAngularPathListFilter.txx @@ -38,56 +38,56 @@ void BreakAngularPathListFilter<TPath> ::BreakAngularPath(const MaxAngleType maxAngle, const PathPointerType inputPath, PathListPointerType outputPathList) { - typename PathType::VertexListType::ConstPointer vertexList = inputPath->GetVertexList(); - typename PathType::VertexListType::ConstIterator pathIt = vertexList->Begin(); - - typename PathType::VertexType pixel1, pixel2, pixel3; - - // Initialisation - PathPointerType newPath = PathType::New(); - newPath->Initialize(); - - double alpha1(0.), alpha2(0.); - - while ( pathIt != vertexList->End() ) + typename PathType::VertexListType::ConstPointer vertexList = inputPath->GetVertexList(); + typename PathType::VertexListType::ConstIterator pathIt = vertexList->Begin(); + + typename PathType::VertexType pixel1, pixel2, pixel3; + + // Initialisation + PathPointerType newPath = PathType::New(); + newPath->Initialize(); + + double alpha1(0.), alpha2(0.); + + while ( pathIt != vertexList->End() ) + { + // Add Pixel 1 + newPath->AddVertex(pathIt.Value()); + pixel1=pathIt.Value(); + ++pathIt; + if (pathIt != vertexList->End()) + { + pixel2=pathIt.Value(); + ++pathIt; + if (pathIt != vertexList->End()) + { + pixel3=pathIt.Value(); + + alpha1 = vcl_atan2((pixel1[1]-pixel2[1]),(pixel1[0]-pixel2[0])); + alpha2 = vcl_atan2((pixel2[1]-pixel3[1]),(pixel2[0]-pixel3[0])); + alpha1 = (alpha1 >= 0)?alpha1:(alpha1+2.*M_PI); + alpha2 = (alpha2 >= 0)?alpha2:(alpha2+2.*M_PI); + if (vcl_abs(alpha1-alpha2) > static_cast<double>(maxAngle) ) { - // Add Pixel 1 - newPath->AddVertex(pathIt.Value()); - pixel1=pathIt.Value(); - ++pathIt; - if (pathIt != vertexList->End()) - { - pixel2=pathIt.Value(); - ++pathIt; - if (pathIt != vertexList->End()) - { - pixel3=pathIt.Value(); - - alpha1 = vcl_atan2((pixel1[1]-pixel2[1]),(pixel1[0]-pixel2[0])); - alpha2 = vcl_atan2((pixel2[1]-pixel3[1]),(pixel2[0]-pixel3[0])); - alpha1 = (alpha1 >= 0)?alpha1:(alpha1+2.*M_PI); - alpha2 = (alpha2 >= 0)?alpha2:(alpha2+2.*M_PI); - if (vcl_abs(alpha1-alpha2) > static_cast<double>(maxAngle) ) - { - // Add Pixel 2 - newPath->AddVertex(pixel2); - //Create new PathType in the out path list - outputPathList->PushBack(newPath); - // Reinit - newPath = PathType::New(); - - } - --pathIt; // Return previous pixel - } - else - { - // Add last Pixel (Pixel 2) - newPath->AddVertex(pixel2); - } - } + // Add Pixel 2 + newPath->AddVertex(pixel2); + //Create new PathType in the out path list + outputPathList->PushBack(newPath); + // Reinit + newPath = PathType::New(); + } - //Create new PathType in the out list - outputPathList->PushBack(newPath); + --pathIt; // Return previous pixel + } + else + { + // Add last Pixel (Pixel 2) + newPath->AddVertex(pixel2); + } + } + } + //Create new PathType in the out list + outputPathList->PushBack(newPath); } @@ -96,18 +96,18 @@ void BreakAngularPathListFilter<TPath> ::GenerateData() { - const PathListType * inputPathList = this->GetInput(); - PathListType * outputPathList = this->GetOutput(); - - typename PathListType::ConstIterator listIt = inputPathList->Begin(); - outputPathList->Clear(); - - PathListPointerType newTempPathList = PathListType::New(); - while( listIt != inputPathList->End()) - { - (void)BreakAngularPath(m_MaxAngle, listIt.Get(), outputPathList); - ++listIt; - } + const PathListType * inputPathList = this->GetInput(); + PathListType * outputPathList = this->GetOutput(); + + typename PathListType::ConstIterator listIt = inputPathList->Begin(); + outputPathList->Clear(); + + PathListPointerType newTempPathList = PathListType::New(); + while ( listIt != inputPathList->End()) + { + (void)BreakAngularPath(m_MaxAngle, listIt.Get(), outputPathList); + ++listIt; + } } /** diff --git a/Code/FeatureExtraction/otbCloudDetectionFilter.h b/Code/FeatureExtraction/otbCloudDetectionFilter.h index 7d7427c79456ce754231bf95dce4f80466771c6d..35a322c06edf2d56f7163e803f28a33021dfd430 100644 --- a/Code/FeatureExtraction/otbCloudDetectionFilter.h +++ b/Code/FeatureExtraction/otbCloudDetectionFilter.h @@ -28,15 +28,15 @@ namespace otb * \brief Apply a threshold. * \brief Apply a color reversal. */ -template <class TInputImage, class TOutputImage, class TFunction = Functor::SpectralAngleFunctor< - ITK_TYPENAME TInputImage::PixelType, ITK_TYPENAME TOutputImage::PixelType> > +template <class TInputImage, class TOutputImage, class TFunction = Functor::SpectralAngleFunctor< +ITK_TYPENAME TInputImage::PixelType, ITK_TYPENAME TOutputImage::PixelType> > class ITK_EXPORT CloudDetectionFilter : public itk::UnaryFunctorImageFilter< TInputImage, TOutputImage, TFunction > { public: /** Standard class typedefs. */ typedef CloudDetectionFilter Self; - typedef typename itk::UnaryFunctorImageFilter < TInputImage, TOutputImage, TFunction > - Superclass; + typedef typename itk::UnaryFunctorImageFilter < TInputImage, TOutputImage, TFunction > + Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -65,7 +65,7 @@ public: protected: CloudDetectionFilter(); - virtual ~CloudDetectionFilter(){}; + virtual ~CloudDetectionFilter() {}; virtual void BeforeThreadedGenerateData(); diff --git a/Code/FeatureExtraction/otbCloudDetectionFunctor.h b/Code/FeatureExtraction/otbCloudDetectionFunctor.h index edb58028a6b60adf31717a2b9e3a80034dbf4693..5a71d53b4a4e5f982ca0f06e759fda69a9d929c3 100644 --- a/Code/FeatureExtraction/otbCloudDetectionFunctor.h +++ b/Code/FeatureExtraction/otbCloudDetectionFunctor.h @@ -23,99 +23,121 @@ namespace otb { - /** \class CloudDetectionFunctor - * \brief This functor first computes the spectral angle according to a reference pixel. - * \brief Then multiplies the result by a gaussian coefficient - * \brief Binarise the image with a threshold - * \brief And reverse the pixel values. - */ +/** \class CloudDetectionFunctor + * \brief This functor first computes the spectral angle according to a reference pixel. + * \brief Then multiplies the result by a gaussian coefficient + * \brief Binarise the image with a threshold + * \brief And reverse the pixel values. + */ namespace Functor { template<class TInput,class TOutputValue> class CloudDetectionFunctor { - public: +public: typedef SpectralAngleFunctor<TInput, TOutputValue> SpectralAngleFunctorType; CloudDetectionFunctor() - { - m_ReferencePixel.SetSize(4); - m_ReferencePixel.Fill(1); - m_RefNorm = 2.0; - m_Variance = 1.0; - m_Denom = 1.0; - m_Coef = 1.0; - -maxigauss = 0; -maxi = 0; -minigauss = 100000; -mini = 100000; - - }; - - ~CloudDetectionFunctor(){}; + { + m_ReferencePixel.SetSize(4); + m_ReferencePixel.Fill(1); + m_RefNorm = 2.0; + m_Variance = 1.0; + m_Denom = 1.0; + m_Coef = 1.0; + + maxigauss = 0; + maxi = 0; + minigauss = 100000; + mini = 100000; + + }; + + ~CloudDetectionFunctor() {}; inline TOutputValue operator()(const TInput& inPix) - { + { - TOutputValue lOut; - double lRes = 0.0; - double lCurPixNorm = 0.0; - double lGaussianCoef = 1.0; + TOutputValue lOut; + double lRes = 0.0; + double lCurPixNorm = 0.0; + double lGaussianCoef = 1.0; - for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) - { - lCurPixNorm += inPix[i]*inPix[i]; - } - lCurPixNorm = vcl_sqrt(static_cast<double>(lCurPixNorm)); - lGaussianCoef = m_Coef * vcl_exp(- vcl_pow(((lCurPixNorm-m_RefNorm)/m_RefNorm),2) / m_Denom ) ; - lRes = lGaussianCoef * (M_PI-m_SpectralAngleFunctor(inPix)); + for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) + { + lCurPixNorm += inPix[i]*inPix[i]; + } + lCurPixNorm = vcl_sqrt(static_cast<double>(lCurPixNorm)); + lGaussianCoef = m_Coef * vcl_exp(- vcl_pow(((lCurPixNorm-m_RefNorm)/m_RefNorm),2) / m_Denom ) ; + lRes = lGaussianCoef * (M_PI-m_SpectralAngleFunctor(inPix)); -if (lGaussianCoef > maxigauss){ maxigauss=lGaussianCoef; std::cout <<"maxigauss" << maxigauss << std::endl;} -if (lRes > maxi){ maxi=lRes; std::cout <<"maxi"<< maxi << std::endl;} + if (lGaussianCoef > maxigauss) + { + maxigauss=lGaussianCoef; + std::cout <<"maxigauss" << maxigauss << std::endl; + } + if (lRes > maxi) + { + maxi=lRes; + std::cout <<"maxi"<< maxi << std::endl; + } -if (lGaussianCoef < minigauss){ minigauss=lGaussianCoef; std::cout <<"minigauss"<< minigauss << std::endl;} -if (lRes < mini){ mini=lRes; std::cout <<"mini"<< mini << std::endl;} + if (lGaussianCoef < minigauss) + { + minigauss=lGaussianCoef; + std::cout <<"minigauss"<< minigauss << std::endl; + } + if (lRes < mini) + { + mini=lRes; + std::cout <<"mini"<< mini << std::endl; + } // lRes = ( (-1)*(lRes/M_PI) ) +1 ; - lOut = static_cast<TOutputValue>(lRes); - return lOut; + lOut = static_cast<TOutputValue>(lRes); + return lOut; - } + } void SetReferencePixel( TInput ref ) - { - m_ReferencePixel = ref; - m_SpectralAngleFunctor.SetReferencePixel(ref); - m_RefNorm = 0.0; - for(unsigned int i = 0; i<ref.Size(); i++) + { + m_ReferencePixel = ref; + m_SpectralAngleFunctor.SetReferencePixel(ref); + m_RefNorm = 0.0; + for (unsigned int i = 0; i<ref.Size(); i++) { m_RefNorm += ref[i]*ref[i]; } - m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); - }; + m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); + }; void SetVariance(double variance) - { - m_Variance = variance; - m_Denom = 2 * variance * variance; - m_Coef = 1/( variance * vcl_sqrt(2*M_PI) ); - } - - TInput GetReferencePixel(){ return m_ReferencePixel; }; - double GetVariance(){ return m_Variance; }; - - - protected: + { + m_Variance = variance; + m_Denom = 2 * variance * variance; + m_Coef = 1/( variance * vcl_sqrt(2*M_PI) ); + } + + TInput GetReferencePixel() + { + return m_ReferencePixel; + }; + double GetVariance() + { + return m_Variance; + }; + + +protected: SpectralAngleFunctorType m_SpectralAngleFunctor; TInput m_ReferencePixel; double m_RefNorm; double m_Variance; double m_Denom; double m_Coef; -double maxi; -double maxigauss; -double mini; -double minigauss; + double maxi; + double maxigauss; + double mini; + double minigauss; }; } // end namespace functor diff --git a/Code/FeatureExtraction/otbCloudEstimatorFilter.h b/Code/FeatureExtraction/otbCloudEstimatorFilter.h index 5ba05ec53b6300910b58adb2e0710a8d78e338d1..a32ded658fc163c999bd0c69a1847471fde6077b 100644 --- a/Code/FeatureExtraction/otbCloudEstimatorFilter.h +++ b/Code/FeatureExtraction/otbCloudEstimatorFilter.h @@ -28,15 +28,15 @@ namespace otb * \brief Multiplies by a gaussian coefficient * \brief Applies a color reversal. */ -template <class TInputImage, class TOutputImage, class TFunction = Functor::SpectralAngleFunctor< - ITK_TYPENAME TInputImage::PixelType, ITK_TYPENAME TOutputImage::PixelType> > +template <class TInputImage, class TOutputImage, class TFunction = Functor::SpectralAngleFunctor< +ITK_TYPENAME TInputImage::PixelType, ITK_TYPENAME TOutputImage::PixelType> > class ITK_EXPORT CloudEstimatorFilter : public itk::UnaryFunctorImageFilter< TInputImage, TOutputImage, TFunction > { public: /** Standard class typedefs. */ typedef CloudEstimatorFilter Self; - typedef typename itk::UnaryFunctorImageFilter < TInputImage, TOutputImage, TFunction > - Superclass; + typedef typename itk::UnaryFunctorImageFilter < TInputImage, TOutputImage, TFunction > + Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -64,7 +64,7 @@ public: protected: CloudEstimatorFilter(); - virtual ~CloudEstimatorFilter(){}; + virtual ~CloudEstimatorFilter() {}; virtual void BeforeThreadedGenerateData(); diff --git a/Code/FeatureExtraction/otbCloudEstimatorFunctor.h b/Code/FeatureExtraction/otbCloudEstimatorFunctor.h index b16850c360910c959fb3f2ba5fcd6fa5aba5c2b1..b50b41f98f416918b8bdd4d9a9b11724d81d5e51 100644 --- a/Code/FeatureExtraction/otbCloudEstimatorFunctor.h +++ b/Code/FeatureExtraction/otbCloudEstimatorFunctor.h @@ -23,99 +23,121 @@ namespace otb { - /** \class CloudEstimatorFunctor - * \brief This functor first computes the spectral angle according to a reference pixel. - * \brief Then multiplies the result by a gaussian coefficient - * \brief Binarise the image with a threshold - * \brief And reverse the pixel values. - */ +/** \class CloudEstimatorFunctor + * \brief This functor first computes the spectral angle according to a reference pixel. + * \brief Then multiplies the result by a gaussian coefficient + * \brief Binarise the image with a threshold + * \brief And reverse the pixel values. + */ namespace Functor { template<class TInput,class TOutputValue> class CloudEstimatorFunctor { - public: +public: typedef SpectralAngleFunctor<TInput, TOutputValue> SpectralAngleFunctorType; CloudEstimatorFunctor() - { - m_ReferencePixel.SetSize(4); - m_ReferencePixel.Fill(1); - m_RefNorm = 2.0; - m_Variance = 1.0; - m_Denom = 1.0; - m_Coef = 1.0; - -maxigauss = 0; -maxi = 0; -minigauss = 100000; -mini = 100000; - - }; - - ~CloudEstimatorFunctor(){}; + { + m_ReferencePixel.SetSize(4); + m_ReferencePixel.Fill(1); + m_RefNorm = 2.0; + m_Variance = 1.0; + m_Denom = 1.0; + m_Coef = 1.0; + + maxigauss = 0; + maxi = 0; + minigauss = 100000; + mini = 100000; + + }; + + ~CloudEstimatorFunctor() {}; inline TOutputValue operator()(const TInput& inPix) - { + { - TOutputValue lOut; - double lRes = 0.0; - double lCurPixNorm = 0.0; - double lGaussianCoef = 1.0; + TOutputValue lOut; + double lRes = 0.0; + double lCurPixNorm = 0.0; + double lGaussianCoef = 1.0; - for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) - { - lCurPixNorm += inPix[i]*inPix[i]; - } - lCurPixNorm = vcl_sqrt(static_cast<double>(lCurPixNorm)); - lGaussianCoef = m_Coef * vcl_exp(- vcl_pow(((lCurPixNorm-m_RefNorm)/m_RefNorm),2) / m_Denom ) ; - lRes = lGaussianCoef * (M_PI-m_SpectralAngleFunctor(inPix)); + for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) + { + lCurPixNorm += inPix[i]*inPix[i]; + } + lCurPixNorm = vcl_sqrt(static_cast<double>(lCurPixNorm)); + lGaussianCoef = m_Coef * vcl_exp(- vcl_pow(((lCurPixNorm-m_RefNorm)/m_RefNorm),2) / m_Denom ) ; + lRes = lGaussianCoef * (M_PI-m_SpectralAngleFunctor(inPix)); -if (lGaussianCoef > maxigauss){ maxigauss=lGaussianCoef; std::cout << maxigauss << std::endl;} -if (lRes > maxi){ maxi=lRes; std::cout << maxi << std::endl;} + if (lGaussianCoef > maxigauss) + { + maxigauss=lGaussianCoef; + std::cout << maxigauss << std::endl; + } + if (lRes > maxi) + { + maxi=lRes; + std::cout << maxi << std::endl; + } -if (lGaussianCoef < minigauss){ minigauss=lGaussianCoef; std::cout << minigauss << std::endl;} -if (lRes < mini){ mini=lRes; std::cout << mini << std::endl;} + if (lGaussianCoef < minigauss) + { + minigauss=lGaussianCoef; + std::cout << minigauss << std::endl; + } + if (lRes < mini) + { + mini=lRes; + std::cout << mini << std::endl; + } // lRes = ( (-1)*(lRes/M_PI) ) +1 ; - lOut = static_cast<TOutputValue>(lRes); - return lOut; + lOut = static_cast<TOutputValue>(lRes); + return lOut; - } + } void SetReferencePixel( TInput ref ) - { - m_ReferencePixel = ref; - m_SpectralAngleFunctor.SetReferencePixel(ref); - m_RefNorm = 0.0; - for(unsigned int i = 0; i<ref.Size(); i++) + { + m_ReferencePixel = ref; + m_SpectralAngleFunctor.SetReferencePixel(ref); + m_RefNorm = 0.0; + for (unsigned int i = 0; i<ref.Size(); i++) { m_RefNorm += ref[i]*ref[i]; } - m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); - }; + m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); + }; void SetVariance(double variance) - { - m_Variance = variance; - m_Denom = 2 * variance * variance; - m_Coef = 1/( variance * vcl_sqrt(2*M_PI) ); - } - - TInput GetReferencePixel(){ return m_ReferencePixel; }; - double GetVariance(){ return m_Variance; }; - - - protected: + { + m_Variance = variance; + m_Denom = 2 * variance * variance; + m_Coef = 1/( variance * vcl_sqrt(2*M_PI) ); + } + + TInput GetReferencePixel() + { + return m_ReferencePixel; + }; + double GetVariance() + { + return m_Variance; + }; + + +protected: SpectralAngleFunctorType m_SpectralAngleFunctor; TInput m_ReferencePixel; double m_RefNorm; double m_Variance; double m_Denom; double m_Coef; -double maxi; -double maxigauss; -double mini; -double minigauss; + double maxi; + double maxigauss; + double mini; + double minigauss; }; } // end namespace functor diff --git a/Code/FeatureExtraction/otbCompacityPathFunction.h b/Code/FeatureExtraction/otbCompacityPathFunction.h index afdb041368362b7dd73405c0bdc128b05dccd6e5..ef564f724381536d14e273c9d0dcc7daf2ded160 100644 --- a/Code/FeatureExtraction/otbCompacityPathFunction.h +++ b/Code/FeatureExtraction/otbCompacityPathFunction.h @@ -37,9 +37,9 @@ namespace otb */ template < class TInputPath, - class TOutput = double> +class TOutput = double> class ITK_EXPORT CompacityPathFunction : - public PathFunction< TInputPath, TOutput > + public PathFunction< TInputPath, TOutput > { public: /** Standard class typedefs. */ @@ -70,8 +70,8 @@ public: virtual OutputType Evaluate( ) const; protected: - CompacityPathFunction(){}; - ~CompacityPathFunction(){}; + CompacityPathFunction() {}; + ~CompacityPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbCompacityPathFunction.txx b/Code/FeatureExtraction/otbCompacityPathFunction.txx index 875d6190e966a4dafea0f04617900e4e6f3dbc29..ced1f6cbf0d9d8f6f3701a01011604eb9c7c04c7 100644 --- a/Code/FeatureExtraction/otbCompacityPathFunction.txx +++ b/Code/FeatureExtraction/otbCompacityPathFunction.txx @@ -38,7 +38,7 @@ CompacityPathFunction< TInputPath, TOutput > template < class TInputPath, class TOutput> typename CompacityPathFunction<TInputPath, - TOutput>::OutputType +TOutput>::OutputType CompacityPathFunction<TInputPath,TOutput> ::Evaluate(const PathType& path) const { @@ -56,41 +56,41 @@ CompacityPathFunction<TInputPath,TOutput> vertexList = path.GetVertexList(); nbPath = vertexList->Size(); - if(nbPath >2) - { - for(int i =0; i<nbPath;i++) - { - cindex = vertexList->GetElement(i); - x1 = cindex[0]; - y1 = cindex[1]; - - if( i == (nbPath-1) ) - { - cindex = vertexList->GetElement(0); - } - else - { - cindex = vertexList->GetElement(i+1); - } - x2 = cindex[0]; - y2 = cindex[1]; - - RealType Norm; - - Norm = vcl_sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); - - Perimeter += Norm; - - RealType P = x2 * (y2-y1); - RealType Q = y2 * (x2-x1); - - Surface += ( P - Q ); - } // FOR loop - } // IF loop - else - { - itkExceptionMacro(<<"CompacityPathFunction::Evaluate() FAILED -- path must contains at least 3 points"); - } + if (nbPath >2) + { + for (int i =0; i<nbPath;i++) + { + cindex = vertexList->GetElement(i); + x1 = cindex[0]; + y1 = cindex[1]; + + if ( i == (nbPath-1) ) + { + cindex = vertexList->GetElement(0); + } + else + { + cindex = vertexList->GetElement(i+1); + } + x2 = cindex[0]; + y2 = cindex[1]; + + RealType Norm; + + Norm = vcl_sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); + + Perimeter += Norm; + + RealType P = x2 * (y2-y1); + RealType Q = y2 * (x2-x1); + + Surface += ( P - Q ); + } // FOR loop + } // IF loop + else + { + itkExceptionMacro(<<"CompacityPathFunction::Evaluate() FAILED -- path must contains at least 3 points"); + } Surface /= 2.0; Compacity = Surface / (Perimeter * Perimeter); @@ -102,15 +102,15 @@ CompacityPathFunction<TInputPath,TOutput> template < class TInputPath, class TOutput> typename CompacityPathFunction<TInputPath, - TOutput>::OutputType +TOutput>::OutputType CompacityPathFunction<TInputPath,TOutput> ::Evaluate() const { - if( !this->GetInputPath() ) - { + if ( !this->GetInputPath() ) + { otbMsgDevMacro( << "Problem with GetInputPath" ); return static_cast<OutputType>(itk::NumericTraits<OutputType>::max() ); - } + } OutputType Result = Evaluate( *(this->GetInputPath()) ); diff --git a/Code/FeatureExtraction/otbComplexMomentImageFunction.h b/Code/FeatureExtraction/otbComplexMomentImageFunction.h index b3780c21077e43103b2dcc36527a3dfcf62d672a..7c3a24b164e09d8ee396eebd693ba6ad5bab2c1d 100644 --- a/Code/FeatureExtraction/otbComplexMomentImageFunction.h +++ b/Code/FeatureExtraction/otbComplexMomentImageFunction.h @@ -46,11 +46,11 @@ namespace otb * \ingroup ImageFunctions */ template < class TInput, - class TOutput = std::complex<double>, - class TPrecision = double, - class TCoordRep = float > +class TOutput = std::complex<double>, +class TPrecision = double, +class TCoordRep = float > class ITK_EXPORT ComplexMomentImageFunction : - public GeometricMomentImageFunction<TInput, TOutput, TPrecision, TCoordRep> + public GeometricMomentImageFunction<TInput, TOutput, TPrecision, TCoordRep> { public: /** Standard class typedefs. */ @@ -84,18 +84,18 @@ public: /** Evaluate the function at non-integer positions */ virtual ComplexType Evaluate( const PointType& point ) const - { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); + } virtual ComplexType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const - { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); + } itkSetMacro(P, unsigned int); itkGetConstReferenceMacro(P, unsigned int); @@ -105,7 +105,7 @@ public: protected: ComplexMomentImageFunction(); - ~ComplexMomentImageFunction(){}; + ~ComplexMomentImageFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbComplexMomentImageFunction.txx b/Code/FeatureExtraction/otbComplexMomentImageFunction.txx index 2cd91a5c7f6a3046637b54a46a3f9994a95b7b62..71aef26732511ac168757c6e100c76b5bdde75cc 100644 --- a/Code/FeatureExtraction/otbComplexMomentImageFunction.txx +++ b/Code/FeatureExtraction/otbComplexMomentImageFunction.txx @@ -66,29 +66,29 @@ ComplexMomentImageFunction<TInput,TOutput,TPrecision,TCoordRep> IndexType indexPos = index; typename TInput::SizeType kernelSize; - if( !this->GetInputImage() ) - { + if ( !this->GetInputImage() ) + { otbMsgDevMacro( << "Pb with GetInputImage" ); - return ( ComplexType(itk::NumericTraits<PrecisionType>::Zero, itk::NumericTraits<PrecisionType>::Zero ) ); - } + return ( ComplexType(itk::NumericTraits<PrecisionType>::Zero, itk::NumericTraits<PrecisionType>::Zero ) ); + } - if(this->GetNeighborhoodRadius()<0) - { - ImageSize = this->GetInputImage()->GetBufferedRegion().GetSize(); + if (this->GetNeighborhoodRadius()<0) + { + ImageSize = this->GetInputImage()->GetBufferedRegion().GetSize(); - indexPos[0] = ImageSize[0] / 2; - indexPos[1] = ImageSize[1] / 2; + indexPos[0] = ImageSize[0] / 2; + indexPos[1] = ImageSize[1] / 2; - kernelSize[0] = indexPos[0]; - kernelSize[1] = indexPos[1]; - } - else - { - kernelSize.Fill( this->GetNeighborhoodRadius() ); - } + kernelSize[0] = indexPos[0]; + kernelSize[1] = indexPos[1]; + } + else + { + kernelSize.Fill( this->GetNeighborhoodRadius() ); + } - itk::ConstNeighborhoodIterator<TInput> - it(kernelSize, this->GetInputImage(), this->GetInputImage()->GetBufferedRegion()); + itk::ConstNeighborhoodIterator<TInput> + it(kernelSize, this->GetInputImage(), this->GetInputImage()->GetBufferedRegion()); // Set the iterator at the desired location @@ -102,17 +102,17 @@ ComplexMomentImageFunction<TInput,TOutput,TPrecision,TCoordRep> ValP = ComplexPrecisionType(1.0,0.0); ValQ = ComplexPrecisionType(1.0,0.0); unsigned int p = m_P; - while(p>0) - { + while (p>0) + { ValP *= ComplexPrecisionType(IndexValue[0], IndexValue[1]); --p; - } + } unsigned int q = m_Q; - while(q>0) - { + while (q>0) + { ValQ *= ComplexPrecisionType(IndexValue[0], -IndexValue[1]); --q; - } + } Sum += ( ValP * ValQ * ComplexPrecisionType(static_cast<PrecisionType>(it.GetPixel(i)),0.0) ); diff --git a/Code/FeatureExtraction/otbComplexMomentPathFunction.h b/Code/FeatureExtraction/otbComplexMomentPathFunction.h index f0cd93247097fbea65b813457757114947c1ef0f..49da9da0d22db7dce062f38d5955daf86fa4754f 100644 --- a/Code/FeatureExtraction/otbComplexMomentPathFunction.h +++ b/Code/FeatureExtraction/otbComplexMomentPathFunction.h @@ -46,12 +46,12 @@ namespace otb * \ingroup ImageFunctions */ template < class TInputPath, - class TOutput = std::complex<double>, - class TPrecision = double> +class TOutput = std::complex<double>, +class TPrecision = double> class ITK_EXPORT ComplexMomentPathFunction : - public GeometricMomentPathFunction< TInputPath, - TOutput, - TPrecision > + public GeometricMomentPathFunction< TInputPath, + TOutput, + TPrecision > { public: /** Standard class typedefs. */ @@ -100,7 +100,7 @@ public: protected: ComplexMomentPathFunction(); - ~ComplexMomentPathFunction(){}; + ~ComplexMomentPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbComplexMomentPathFunction.txx b/Code/FeatureExtraction/otbComplexMomentPathFunction.txx index 10c9c21f129b226b2fbcd8eecbd93af32a8d486a..90c022ba74dc6886d91681e06dfa3f6a0481b588 100644 --- a/Code/FeatureExtraction/otbComplexMomentPathFunction.txx +++ b/Code/FeatureExtraction/otbComplexMomentPathFunction.txx @@ -59,34 +59,34 @@ typename ComplexMomentPathFunction<TInputPath,TOutput,TPrecision>::ComplexType ComplexMomentPathFunction<TInputPath,TOutput,TPrecision> ::EvaluateComplexMomentAtIndex(VertexType index) const { - ComplexPrecisionType ValP; - ComplexPrecisionType ValQ; - ComplexPrecisionType Result; - PrecisionType PixelValue(1.0); - - ValP = ComplexPrecisionType(1.0,0.0); - ValQ = ComplexPrecisionType(1.0,0.0); - unsigned int p = m_P; - while(p>0) - { - ValP *= ComplexPrecisionType(index[0], index[1]); - --p; - } - unsigned int q = m_Q; - while(q>0) - { - ValQ *= ComplexPrecisionType(index[0], -index[1]); - --q; - } - - Result = ValP * ValQ * ComplexPrecisionType( static_cast<PrecisionType>(PixelValue), 0.0); - return ( static_cast<ComplexType>(Result) ); + ComplexPrecisionType ValP; + ComplexPrecisionType ValQ; + ComplexPrecisionType Result; + PrecisionType PixelValue(1.0); + + ValP = ComplexPrecisionType(1.0,0.0); + ValQ = ComplexPrecisionType(1.0,0.0); + unsigned int p = m_P; + while (p>0) + { + ValP *= ComplexPrecisionType(index[0], index[1]); + --p; + } + unsigned int q = m_Q; + while (q>0) + { + ValQ *= ComplexPrecisionType(index[0], -index[1]); + --q; + } + + Result = ValP * ValQ * ComplexPrecisionType( static_cast<PrecisionType>(PixelValue), 0.0); + return ( static_cast<ComplexType>(Result) ); } template < class TInputPath, class TOutput, class TPrecision> typename ComplexMomentPathFunction<TInputPath, - TOutput,TPrecision>::OutputType +TOutput,TPrecision>::OutputType ComplexMomentPathFunction<TInputPath,TOutput,TPrecision> ::Evaluate(const PathType& path) const { @@ -102,47 +102,47 @@ ComplexMomentPathFunction<TInputPath,TOutput,TPrecision> vertexList = path.GetVertexList(); nbPath = vertexList->Size(); - if(nbPath >1) - { - for(int i =0; i<nbPath-1;i++) - { - cindex = vertexList->GetElement(i); - PrecisionType x1 = cindex[0]; - PrecisionType y1 = cindex[1]; - cindex = vertexList->GetElement(i+1); - PrecisionType x2 = cindex[0]; - PrecisionType y2 = cindex[1]; - - PrecisionType Theta; - PrecisionType Norm; - - Theta = vcl_atan2(y2-y1,x2-x1); - Norm = vcl_sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); - - for(RealType k = 0; k <=Norm; k+=m_Step) - { - IndexOut[0] = x1 + k * vcl_cos(Theta); - IndexOut[1] = y1 + k * vcl_sin(Theta); - - Value += EvaluateComplexMomentAtIndex(IndexOut ); - } - } // FOR loop - } // IF loop + if (nbPath >1) + { + for (int i =0; i<nbPath-1;i++) + { + cindex = vertexList->GetElement(i); + PrecisionType x1 = cindex[0]; + PrecisionType y1 = cindex[1]; + cindex = vertexList->GetElement(i+1); + PrecisionType x2 = cindex[0]; + PrecisionType y2 = cindex[1]; + + PrecisionType Theta; + PrecisionType Norm; + + Theta = vcl_atan2(y2-y1,x2-x1); + Norm = vcl_sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); + + for (RealType k = 0; k <=Norm; k+=m_Step) + { + IndexOut[0] = x1 + k * vcl_cos(Theta); + IndexOut[1] = y1 + k * vcl_sin(Theta); + + Value += EvaluateComplexMomentAtIndex(IndexOut ); + } + } // FOR loop + } // IF loop return (static_cast<OutputType>(Value) ); } template < class TInputPath, class TOutput, class TPrecision> typename ComplexMomentPathFunction<TInputPath, - TOutput,TPrecision>::OutputType +TOutput,TPrecision>::OutputType ComplexMomentPathFunction<TInputPath,TOutput,TPrecision> ::Evaluate() const { - if( !this->GetInputPath() ) - { + if ( !this->GetInputPath() ) + { otbMsgDevMacro( << "Pb with GetInputPath" ); return static_cast<OutputType>(ComplexPrecisionType( itk::NumericTraits<PrecisionType>::Zero, itk::NumericTraits<PrecisionType>::Zero ) ); - } + } OutputType Result = Evaluate( *(this->GetInputPath()) ); diff --git a/Code/FeatureExtraction/otbExtractSegmentsImageFilter.h b/Code/FeatureExtraction/otbExtractSegmentsImageFilter.h index 7c7e14eeaed4861cca1d58e77f46ddc5ebeb9d19..7e1d69a1656ce26a5cc343b7ca36b3b714923ea5 100644 --- a/Code/FeatureExtraction/otbExtractSegmentsImageFilter.h +++ b/Code/FeatureExtraction/otbExtractSegmentsImageFilter.h @@ -43,17 +43,17 @@ namespace otb */ template <class TInputImage, - class TOutputImage> +class TOutputImage> class ITK_EXPORT ExtractSegmentsImageFilter : -public itk::ImageToImageFilter< TInputImage, TOutputImage > + public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); typedef TInputImage InputImageType; diff --git a/Code/FeatureExtraction/otbExtractSegmentsImageFilter.txx b/Code/FeatureExtraction/otbExtractSegmentsImageFilter.txx index bef492bb64f41b59fe3d6c27b0ceb34bbe0684ed..7802cf62a9d11a981f34e4128768956550c164ed 100644 --- a/Code/FeatureExtraction/otbExtractSegmentsImageFilter.txx +++ b/Code/FeatureExtraction/otbExtractSegmentsImageFilter.txx @@ -48,16 +48,16 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetInputImage( const InputImageType *image) { - this->SetInput(0,image); + this->SetInput(0,image); } template <class TInputImage, class TOutputImage> const typename ExtractSegmentsImageFilter<TInputImage, TOutputImage>::InputImageType * ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::GetInputImage(void) -{ - return static_cast<const InputImageType * > - (this->GetInput(0) ); +{ + return static_cast<const InputImageType * > + (this->GetInput(0) ); } /** @@ -67,16 +67,16 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetInputImageDirection( const InputImageType *image) { - this->SetInput(1,image); + this->SetInput(1,image); } template <class TInputImage, class TOutputImage> const typename ExtractSegmentsImageFilter<TInputImage, TOutputImage>::InputImageType * ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::GetInputImageDirection(void) -{ - return static_cast<const InputImageType * > - (this->GetInput(1) ); +{ + return static_cast<const InputImageType * > + (this->GetInput(1) ); } /** @@ -86,7 +86,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetPixelSuppressionRadius(SizeType Radius) { - m_PixelSuppression->SetRadius(Radius); + m_PixelSuppression->SetRadius(Radius); } template <class TInputImage, class TOutputImage> @@ -101,7 +101,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetPixelSuppressionAngularBeam(float AngularBeam) { - m_PixelSuppression->SetAngularBeam(AngularBeam); + m_PixelSuppression->SetAngularBeam(AngularBeam); } template <class TInputImage, class TOutputImage> @@ -119,7 +119,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetLocalHoughRadius(SizeType Radius) { - m_LocalHough->SetRadius(Radius); + m_LocalHough->SetRadius(Radius); } template <class TInputImage, class TOutputImage> @@ -134,7 +134,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetLocalHoughNumberOfLines(unsigned int NumberOfLines) { - m_LocalHough->SetNumberOfLines(NumberOfLines); + m_LocalHough->SetNumberOfLines(NumberOfLines); } template <class TInputImage, class TOutputImage> @@ -149,7 +149,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetLocalHoughDiscRadius(float DiscRadius) { - m_LocalHough->SetDiscRadius(DiscRadius); + m_LocalHough->SetDiscRadius(DiscRadius); } template <class TInputImage, class TOutputImage> @@ -164,7 +164,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetLocalHoughVariance(float Variance) { - m_LocalHough->SetVariance(Variance); + m_LocalHough->SetVariance(Variance); } template <class TInputImage, class TOutputImage> @@ -182,7 +182,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetFillGapsRadius(float Radius) { - m_FillGaps->SetRadius(Radius); + m_FillGaps->SetRadius(Radius); } template <class TInputImage, class TOutputImage> @@ -197,7 +197,7 @@ template <class TInputImage, class TOutputImage> void ExtractSegmentsImageFilter<TInputImage, TOutputImage> ::SetFillGapsAngularBeam(float AngularBeam) { - m_FillGaps->SetAngularBeam(AngularBeam); + m_FillGaps->SetAngularBeam(AngularBeam); } template <class TInputImage, class TOutputImage> @@ -218,10 +218,10 @@ ExtractSegmentsImageFilter<TInputImage, TOutputImage> m_PixelSuppression->SetInputImageDirection( this->GetInputImageDirection() ); m_Rescaler->SetInput( m_PixelSuppression->GetOutput()); - + /*m_LocalHough->SetInput( m_PixelSuppression->GetOutput() );*/ m_LocalHough->SetInput(m_Rescaler->GetOutput() ); - + m_FillGaps->SetInput ( m_LocalHough->GetOutput() ); m_DrawLineList->SetInput( this->GetInputImage() ); @@ -243,8 +243,8 @@ ExtractSegmentsImageFilter<TInputImage, TOutput> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); -/* os << indent << "Length: " << m_LengthLine << std::endl; - os << indent << "Width: " << m_WidthLine << std::endl;*/ + /* os << indent << "Length: " << m_LengthLine << std::endl; + os << indent << "Width: " << m_WidthLine << std::endl;*/ } diff --git a/Code/FeatureExtraction/otbFillGapsFilter.cxx b/Code/FeatureExtraction/otbFillGapsFilter.cxx index 5a7f389414c568abe809ce40acff0e674144f9e0..2dc47a7844a67a466133181a90dd0cce13bd6b13 100644 --- a/Code/FeatureExtraction/otbFillGapsFilter.cxx +++ b/Code/FeatureExtraction/otbFillGapsFilter.cxx @@ -27,12 +27,12 @@ namespace otb FillGapsFilter::FillGapsFilter() { - this->ProcessObjectType::SetNumberOfRequiredInputs(1); - this->ProcessObjectType::SetNumberOfRequiredOutputs(1); + this->ProcessObjectType::SetNumberOfRequiredInputs(1); + this->ProcessObjectType::SetNumberOfRequiredOutputs(1); - LineSpatialObjectListPointer output = LineSpatialObjectListType::New(); + LineSpatialObjectListPointer output = LineSpatialObjectListType::New(); - this->ProcessObjectType::SetNthOutput(0, output ); + this->ProcessObjectType::SetNthOutput(0, output ); m_Radius = 4.0; m_AngularBeam = 1.0; @@ -44,7 +44,7 @@ FillGapsFilter ::SetInput(const LineSpatialObjectListType * input) { this->ProcessObjectType::SetNthInput(0, - const_cast< LineSpatialObjectListType * >( input ) ); + const_cast< LineSpatialObjectListType * >( input ) ); } @@ -52,8 +52,8 @@ const FillGapsFilter::LineSpatialObjectListType * FillGapsFilter ::GetInput(void) { - return static_cast<const LineSpatialObjectListType *> - (this->ProcessObjectType::GetInput(0) ); + return static_cast<const LineSpatialObjectListType *> + (this->ProcessObjectType::GetInput(0) ); } @@ -61,8 +61,8 @@ FillGapsFilter::LineSpatialObjectListType * FillGapsFilter ::GetOutput(void) { - return static_cast<LineSpatialObjectListType *> - (this->ProcessObjectType::GetOutput(0) ); + return static_cast<LineSpatialObjectListType *> + (this->ProcessObjectType::GetOutput(0) ); } @@ -77,8 +77,8 @@ FillGapsFilter { // Get the LineSpatialObject - const LineSpatialObjectList * inputLine = this->GetInput(); - LineSpatialObjectList * outputLine = this->GetOutput(); + const LineSpatialObjectList * inputLine = this->GetInput(); + LineSpatialObjectList * outputLine = this->GetOutput(); // Get the list of points which consists of two points to represent a // straight line @@ -100,12 +100,12 @@ FillGapsFilter CosTheta = vcl_cos(m_AngularBeam); --itLineListAEnd; - while(itLineListA != itLineListAEnd ) - { + while (itLineListA != itLineListAEnd ) + { itLineListB = itLineListA; ++itLineListB; - PointListType & pointsList = (*itLineListA)->GetPoints(); + PointListType & pointsList = (*itLineListA)->GetPoints(); itPoints = pointsList.begin(); x1 = (*itPoints).GetPosition()[0]; @@ -129,8 +129,8 @@ FillGapsFilter line->ComputeBoundingBox(); outputLine->push_back(line); - while(itLineListB != itLineListBEnd) - { + while (itLineListB != itLineListBEnd) + { pointsList = (*itLineListB)->GetPoints(); itPoints = pointsList.begin(); @@ -152,84 +152,96 @@ FillGapsFilter double Rmin = m_Radius; // Test the lower Radius - if(R13 < Rmin) Rmin = R13; - if(R14 < Rmin) Rmin = R14; - if(R23 < Rmin) Rmin = R23; - if(R24 < Rmin) Rmin = R24; + if (R13 < Rmin) Rmin = R13; + if (R14 < Rmin) Rmin = R14; + if (R23 < Rmin) Rmin = R23; + if (R24 < Rmin) Rmin = R24; - if(Rmin < m_Radius) + if (Rmin < m_Radius) + { + // Sort Points such as the radius of P2 and P3 is the smallest one. + if (Rmin == R24 ) + { + xTemp = x3; + yTemp = y3; + x3 = x4; + y3 = y4; + x4 = xTemp; + y4 = yTemp; + } + if (Rmin == R13 ) + { + xTemp = x1; + yTemp = y1; + x1 = x2; + y1 = y2; + x2 = xTemp; + y2 = yTemp; + } + if (Rmin == R14 ) + { + xTemp = x3; + yTemp = y3; + x3 = x4; + y3 = y4; + x4 = xTemp; + y4 = yTemp; + xTemp = x1; + yTemp = y1; + x1 = x2; + y1 = y2; + x2 = xTemp; + y2 = yTemp; + } + + //Estimate the norm each line + /* double Norm12,Norm23,Norm34; + Norm12 = vcl_sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ); + Norm23 = vcl_sqrt( (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) ); + Norm34 = vcl_sqrt( (x3-x4)*(x3-x4) + (y3-y4)*(y3-y4) ); + */ + double Angle12_23,Angle12_34,Angle23_34; + //Estimate the angle between lines 12-23 and lines 12-34 + /*Angle12_23 = (x2-x1)*(x3-x2) + (y2-y1)*(y3-y2); + Angle12_23 = Angle12_23 / Norm12 / Norm23; + + Angle12_34 = (x2-x1)*(x4-x3) + (y2-y1)*(y4-y3); + Angle12_34 = Angle12_34 / Norm12 / Norm34;*/ + + Angle12_23 = vcl_cos(vcl_atan2((y2-y1), (x2-x1))-vcl_atan2((y3-y2), (x3-x2))); + Angle12_34 = vcl_cos(vcl_atan2((y2-y1), (x2-x1))-vcl_atan2((y4-y3), (x4-x3))); + Angle23_34 = vcl_cos(vcl_atan2((y3-y2), (x3-x2))-vcl_atan2((y4-y3), (x4-x3))); + + + if ( (Angle12_23 > CosTheta) && (Angle12_34 > CosTheta) && (Angle23_34 > CosTheta) ) { - // Sort Points such as the radius of P2 and P3 is the smallest one. - if(Rmin == R24 ) - { - xTemp = x3; yTemp = y3; - x3 = x4; y3 = y4; - x4 = xTemp; y4 = yTemp; - } - if(Rmin == R13 ) - { - xTemp = x1; yTemp = y1; - x1 = x2; y1 = y2; - x2 = xTemp; y2 = yTemp; - } - if(Rmin == R14 ) - { - xTemp = x3; yTemp = y3; - x3 = x4; y3 = y4; - x4 = xTemp; y4 = yTemp; - xTemp = x1; yTemp = y1; - x1 = x2; y1 = y2; - x2 = xTemp; y2 = yTemp; - } - - //Estimate the norm each line -/* double Norm12,Norm23,Norm34; - Norm12 = vcl_sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ); - Norm23 = vcl_sqrt( (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) ); - Norm34 = vcl_sqrt( (x3-x4)*(x3-x4) + (y3-y4)*(y3-y4) ); - */ - double Angle12_23,Angle12_34,Angle23_34; - //Estimate the angle between lines 12-23 and lines 12-34 - /*Angle12_23 = (x2-x1)*(x3-x2) + (y2-y1)*(y3-y2); - Angle12_23 = Angle12_23 / Norm12 / Norm23; - - Angle12_34 = (x2-x1)*(x4-x3) + (y2-y1)*(y4-y3); - Angle12_34 = Angle12_34 / Norm12 / Norm34;*/ - - Angle12_23 = vcl_cos(vcl_atan2((y2-y1), (x2-x1))-vcl_atan2((y3-y2), (x3-x2))); - Angle12_34 = vcl_cos(vcl_atan2((y2-y1), (x2-x1))-vcl_atan2((y4-y3), (x4-x3))); - Angle23_34 = vcl_cos(vcl_atan2((y3-y2), (x3-x2))-vcl_atan2((y4-y3), (x4-x3))); - - - if( (Angle12_23 > CosTheta) && (Angle12_34 > CosTheta) && (Angle23_34 > CosTheta) ) - { - // Store 23-segment - PointType point; - PointListType pointList; + // Store 23-segment + PointType point; + PointListType pointList; - point.SetPosition(x2,y2); - pointList.push_back(point); - point.SetPosition(x3,y3); - pointList.push_back(point); + point.SetPosition(x2,y2); + pointList.push_back(point); + point.SetPosition(x3,y3); + pointList.push_back(point); - LineSpatialObjectType::Pointer line = LineSpatialObjectType::New(); - line->SetId(0); - line->SetPoints( pointList ); - line->ComputeBoundingBox(); - outputLine->push_back(line); + LineSpatialObjectType::Pointer line = LineSpatialObjectType::New(); + line->SetId(0); + line->SetPoints( pointList ); + line->ComputeBoundingBox(); + outputLine->push_back(line); - pointList.clear(); + pointList.clear(); - } - } // if(Rmin < m_Radius) + } + } // if(Rmin < m_Radius) ++itLineListB; - } // while(itLineListB != itLineListBEnd) + } // while(itLineListB != itLineListBEnd) ++itLineListA; - } + } // Insert the last element @@ -260,7 +272,7 @@ void FillGapsFilter ::PrintSelf(std::ostream& os, itk::Indent indent) const { - Superclass::PrintSelf(os,indent); + Superclass::PrintSelf(os,indent); } diff --git a/Code/FeatureExtraction/otbFillGapsFilter.h b/Code/FeatureExtraction/otbFillGapsFilter.h index 832929abe72012b82604e0abfd804071b9b992b2..b18d58e5b57ad05ba44ea2bd12501a544ba493f8 100644 --- a/Code/FeatureExtraction/otbFillGapsFilter.h +++ b/Code/FeatureExtraction/otbFillGapsFilter.h @@ -68,7 +68,7 @@ public: protected: FillGapsFilter(); - virtual ~FillGapsFilter(){}; + virtual ~FillGapsFilter() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; diff --git a/Code/FeatureExtraction/otbFlusserImageFunction.h b/Code/FeatureExtraction/otbFlusserImageFunction.h index 4ac3f50c58c7af1fcc2184be5fe82a29584ca748..a5bb476f588f489a34f844f3bba169b6b1f0632e 100644 --- a/Code/FeatureExtraction/otbFlusserImageFunction.h +++ b/Code/FeatureExtraction/otbFlusserImageFunction.h @@ -60,11 +60,11 @@ namespace otb */ template < class TInput, - class TOutput = double, - class TPrecision = double, - class TCoordRep = float > +class TOutput = double, +class TPrecision = double, +class TCoordRep = float > class ITK_EXPORT FlusserImageFunction : - public RealMomentImageFunction< TInput, TOutput, TPrecision, TCoordRep > + public RealMomentImageFunction< TInput, TOutput, TPrecision, TCoordRep > { public: /** Standard class typedefs. */ @@ -102,18 +102,18 @@ public: /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const - { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); + } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const - { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); + } /** Get/Set the radius of the neighborhood over which the @@ -123,7 +123,7 @@ public: protected: FlusserImageFunction(); - ~FlusserImageFunction(){}; + ~FlusserImageFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbFlusserImageFunction.txx b/Code/FeatureExtraction/otbFlusserImageFunction.txx index ba16f92796c4bffbc686f91748ed26b3af88cf99..a79f0cdef4779e9c66b1d5a33f89c5c52c24ed66 100644 --- a/Code/FeatureExtraction/otbFlusserImageFunction.txx +++ b/Code/FeatureExtraction/otbFlusserImageFunction.txx @@ -62,165 +62,165 @@ FlusserImageFunction<TInput,TOutput,TPrecision,TCoordRep> typedef otb::ComplexMomentImageFunction<InputType,ComplexType> CMType; typename CMType::Pointer function =CMType::New(); - if( !this->GetInputImage() ) - { + if ( !this->GetInputImage() ) + { return ( itk::NumericTraits<RealType>::max() ); - } + } if ( !this->IsInsideBuffer( index ) ) - { + { return ( itk::NumericTraits<RealType>::max() ); - } + } assert(m_MomentNumber > 0); assert(m_MomentNumber < 12); - function->SetInputImage( this->GetInputImage() ); - function->SetNeighborhoodRadius(this->GetNeighborhoodRadius() ); - - switch(m_MomentNumber) - { - case 1 : - { - ComplexType C11; - function->SetP(1); - function->SetQ(1); - C11 = function->EvaluateAtIndex( index ); - FlusserValue = C11.real(); + function->SetInputImage( this->GetInputImage() ); + function->SetNeighborhoodRadius(this->GetNeighborhoodRadius() ); + + switch (m_MomentNumber) + { + case 1 : + { + ComplexType C11; + function->SetP(1); + function->SetQ(1); + C11 = function->EvaluateAtIndex( index ); + FlusserValue = C11.real(); } break; - case 2: - { - ComplexType C21,C12; - function->SetP(2); - function->SetQ(1); - C21 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - FlusserValue = vcl_abs( C21 * C12 ); + case 2: + { + ComplexType C21,C12; + function->SetP(2); + function->SetQ(1); + C21 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + FlusserValue = vcl_abs( C21 * C12 ); } break; - case 3: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C20 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.real(); + case 3: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C20 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.real(); } break; - case 4: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C20 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.imag(); + case 4: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C20 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.imag(); } break; - case 5: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - FlusserValueComplex = C30 * vcl_pow(C12,3); - FlusserValue = FlusserValueComplex.real(); + case 5: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + FlusserValueComplex = C30 * vcl_pow(C12,3); + FlusserValue = FlusserValueComplex.real(); } break; - case 6: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - FlusserValueComplex = C30 * vcl_pow(C12,3); - FlusserValue = FlusserValueComplex.imag(); + case 6: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + FlusserValueComplex = C30 * vcl_pow(C12,3); + FlusserValue = FlusserValueComplex.imag(); } break; - case 7 : - { - ComplexType C22; - function->SetP(2); - function->SetQ(2); - C22 = function->EvaluateAtIndex( index ); - FlusserValue = C22.real(); + case 7 : + { + ComplexType C22; + function->SetP(2); + function->SetQ(2); + C22 = function->EvaluateAtIndex( index ); + FlusserValue = C22.real(); } break; - case 8: - { - ComplexType C31,C12; - function->SetP(3); - function->SetQ(1); - C31 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C31 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.real(); + case 8: + { + ComplexType C31,C12; + function->SetP(3); + function->SetQ(1); + C31 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C31 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.real(); } break; - case 9: - { - ComplexType C31,C12; - function->SetP(3); - function->SetQ(1); - C31 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C31 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.imag(); + case 9: + { + ComplexType C31,C12; + function->SetP(3); + function->SetQ(1); + C31 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C31 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.imag(); } break; - case 10: - { - ComplexType C40,C12; - function->SetP(4); - function->SetQ(0); - C40 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C40 * vcl_pow(C12,4); - FlusserValue = FlusserValueComplex.real(); + case 10: + { + ComplexType C40,C12; + function->SetP(4); + function->SetQ(0); + C40 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C40 * vcl_pow(C12,4); + FlusserValue = FlusserValueComplex.real(); } break; - case 11: - { - ComplexType C40,C12; - function->SetP(4); - function->SetQ(0); - C40 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - FlusserValueComplex = C40 * vcl_pow(C12,4); - FlusserValue = FlusserValueComplex.imag(); + case 11: + { + ComplexType C40,C12; + function->SetP(4); + function->SetQ(0); + C40 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + FlusserValueComplex = C40 * vcl_pow(C12,4); + FlusserValue = FlusserValueComplex.imag(); } break; - default: - itkWarningMacro("Hu's invariant parameters are between 1 and 7"); - } + default: + itkWarningMacro("Hu's invariant parameters are between 1 and 7"); + } return (static_cast<RealType>(FlusserValue) ); diff --git a/Code/FeatureExtraction/otbFlusserPathFunction.h b/Code/FeatureExtraction/otbFlusserPathFunction.h index 10127300d036155514bf0e12fa5afffe8500b783..9e56511c616e24d7940cc7501b96205fe3800521 100644 --- a/Code/FeatureExtraction/otbFlusserPathFunction.h +++ b/Code/FeatureExtraction/otbFlusserPathFunction.h @@ -57,10 +57,10 @@ namespace otb */ template < class TInputPath, - class TOutput = double, - class TPrecision = double> +class TOutput = double, +class TPrecision = double> class ITK_EXPORT FlusserPathFunction : - public RealMomentPathFunction< TInputPath, TOutput, TPrecision > + public RealMomentPathFunction< TInputPath, TOutput, TPrecision > { public: /** Standard class typedefs. */ @@ -97,7 +97,7 @@ public: protected: FlusserPathFunction(); - ~FlusserPathFunction(){}; + ~FlusserPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbFlusserPathFunction.txx b/Code/FeatureExtraction/otbFlusserPathFunction.txx index 9cb3712a00395bb4dcef2327600f06c883a55f24..9c336f29fb399d7e71e4e76c8c967531c1d17d52 100644 --- a/Code/FeatureExtraction/otbFlusserPathFunction.txx +++ b/Code/FeatureExtraction/otbFlusserPathFunction.txx @@ -65,149 +65,149 @@ FlusserPathFunction<TInputPath, TOutput, TPrecision > function->SetStep( this->GetStep() ); function->SetInputPath( this->GetInputPath() ); - switch(m_MomentNumber) - { - case 1 : - { - ComplexType C11; - function->SetP(1); - function->SetQ(1); - C11 = function->Evaluate( ); - FlusserValue = C11.real(); + switch (m_MomentNumber) + { + case 1 : + { + ComplexType C11; + function->SetP(1); + function->SetQ(1); + C11 = function->Evaluate( ); + FlusserValue = C11.real(); } break; - case 2: - { - ComplexType C21,C12; - function->SetP(2); - function->SetQ(1); - C21 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - FlusserValue = vcl_abs( C21 * C12 ); + case 2: + { + ComplexType C21,C12; + function->SetP(2); + function->SetQ(1); + C21 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + FlusserValue = vcl_abs( C21 * C12 ); } break; - case 3: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C20 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.real(); + case 3: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C20 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.real(); } break; - case 4: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C20 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.imag(); + case 4: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C20 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.imag(); } break; - case 5: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - FlusserValueComplex = C30 * vcl_pow(C12,3); - FlusserValue = FlusserValueComplex.real(); + case 5: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + FlusserValueComplex = C30 * vcl_pow(C12,3); + FlusserValue = FlusserValueComplex.real(); } break; - case 6: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - FlusserValueComplex = C30 * vcl_pow(C12,3); - FlusserValue = FlusserValueComplex.imag(); + case 6: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + FlusserValueComplex = C30 * vcl_pow(C12,3); + FlusserValue = FlusserValueComplex.imag(); } break; - case 7 : - { - ComplexType C22; - function->SetP(2); - function->SetQ(2); - C22 = function->Evaluate( ); - FlusserValue = C22.real(); + case 7 : + { + ComplexType C22; + function->SetP(2); + function->SetQ(2); + C22 = function->Evaluate( ); + FlusserValue = C22.real(); } break; - case 8: - { - ComplexType C31,C12; - function->SetP(3); - function->SetQ(1); - C31 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C31 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.real(); + case 8: + { + ComplexType C31,C12; + function->SetP(3); + function->SetQ(1); + C31 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C31 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.real(); } break; - case 9: - { - ComplexType C31,C12; - function->SetP(3); - function->SetQ(1); - C31 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C31 * vcl_pow(C12,2); - FlusserValue = FlusserValueComplex.imag(); + case 9: + { + ComplexType C31,C12; + function->SetP(3); + function->SetQ(1); + C31 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C31 * vcl_pow(C12,2); + FlusserValue = FlusserValueComplex.imag(); } break; - case 10: - { - ComplexType C40,C12; - function->SetP(4); - function->SetQ(0); - C40 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C40 * vcl_pow(C12,4); - FlusserValue = FlusserValueComplex.real(); + case 10: + { + ComplexType C40,C12; + function->SetP(4); + function->SetQ(0); + C40 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C40 * vcl_pow(C12,4); + FlusserValue = FlusserValueComplex.real(); } break; - case 11: - { - ComplexType C40,C12; - function->SetP(4); - function->SetQ(0); - C40 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - FlusserValueComplex = C40 * vcl_pow(C12,4); - FlusserValue = FlusserValueComplex.imag(); + case 11: + { + ComplexType C40,C12; + function->SetP(4); + function->SetQ(0); + C40 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + FlusserValueComplex = C40 * vcl_pow(C12,4); + FlusserValue = FlusserValueComplex.imag(); } break; - default: - itkWarningMacro("Flusser's invariant parameters are between 1 and 11"); - } + default: + itkWarningMacro("Flusser's invariant parameters are between 1 and 11"); + } return (static_cast<RealType>(FlusserValue) ); @@ -219,11 +219,11 @@ typename FlusserPathFunction<TInputPath, TOutput, TPrecision>::RealType FlusserPathFunction<TInputPath, TOutput, TPrecision > ::Evaluate() const { - if( !this->GetInputPath() ) - { + if ( !this->GetInputPath() ) + { otbMsgDevMacro( << "Pb with GetInputPath" ); return static_cast<RealType>( itk::NumericTraits<PrecisionType>::max()); - } + } RealType Result = Evaluate( *(this->GetInputPath()) ); diff --git a/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.h b/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.h index ed961c58d6dc8aefc2d0a3e683680fc9f82710be..34debb692a5a1f1040b6d3b15736ca5543247369 100644 --- a/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.h +++ b/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.h @@ -46,14 +46,14 @@ namespace otb */ template < class TPixel, - class TInterpol, - unsigned int Dimension = 2 > +class TInterpol, +unsigned int Dimension = 2 > class ITK_EXPORT ForwardFourierMellinTransformImageFilter : - public itk::ImageToImageFilter<Image< TPixel , Dimension >, - itk::Image< std::complex<TPixel> , Dimension > > + public itk::ImageToImageFilter<Image< TPixel , Dimension >, + itk::Image< std::complex<TPixel> , Dimension > > { - public: +public: //typedef TPixel PixelType; typedef Image< TPixel , Dimension > InputImageType; @@ -117,8 +117,8 @@ class ITK_EXPORT ForwardFourierMellinTransformImageFilter : itkGetMacro(OutputSize,OutputSizeType); /** Set/Get the Sigma value for the Log-polar resampler */ - itkSetMacro(Sigma,double); - itkGetMacro(Sigma,double); + itkSetMacro(Sigma,double); + itkGetMacro(Sigma,double); /** Set/Get the Default pixel value for the Log-polar resampler */ itkSetMacro(DefaultPixelValue, PixelType); @@ -133,7 +133,7 @@ class ITK_EXPORT ForwardFourierMellinTransformImageFilter : protected: ForwardFourierMellinTransformImageFilter(); - ~ForwardFourierMellinTransformImageFilter(){}; + ~ForwardFourierMellinTransformImageFilter() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main Computation Method */ void GenerateData(); diff --git a/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.txx b/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.txx index 656db229681bcf15d943126e75bc83b74935ec3f..e2e17c90b6b633ec43d6a869d68c61df3a302254 100644 --- a/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.txx +++ b/Code/FeatureExtraction/otbForwardFourierMellinTransformImageFilter.txx @@ -23,55 +23,55 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template < class TPixel,class TInterpol,unsigned int Dimension > - ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > - ::ForwardFourierMellinTransformImageFilter() - { +template < class TPixel,class TInterpol,unsigned int Dimension > +ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > +::ForwardFourierMellinTransformImageFilter() +{ - m_Sigma = 1.0; - m_OutputSize.Fill(512); - m_FFTFilter = FourierImageFilterType::New(); - m_Interpolator = InterpolatorType::New(); - m_Transform = LogPolarTransformType::New(); - m_ResampleFilter = ResampleFilterType::New(); - m_ResampleFilter->SetInterpolator(m_Interpolator); - m_ResampleFilter->SetTransform(m_Transform); - m_DefaultPixelValue=0; - } + m_Sigma = 1.0; + m_OutputSize.Fill(512); + m_FFTFilter = FourierImageFilterType::New(); + m_Interpolator = InterpolatorType::New(); + m_Transform = LogPolarTransformType::New(); + m_ResampleFilter = ResampleFilterType::New(); + m_ResampleFilter->SetInterpolator(m_Interpolator); + m_ResampleFilter->SetTransform(m_Transform); + m_DefaultPixelValue=0; +} - template < class TPixel,class TInterpol,unsigned int Dimension > - void - ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > - ::GenerateOutputInformation(void) - { - Superclass::GenerateOutputInformation(); - - OutputImagePointer outputPtr = this->GetOutput(); - - if(!outputPtr) - { - return; - } - typename OutputImageType::RegionType largestPossibleRegion; - typename OutputImageType::IndexType index; - index.Fill(0); - largestPossibleRegion.SetIndex(index); - largestPossibleRegion.SetSize(m_OutputSize); - outputPtr->SetLargestPossibleRegion(largestPossibleRegion); - } - - template < class TPixel,class TInterpol,unsigned int Dimension > - void - ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > - ::GenerateData() +template < class TPixel,class TInterpol,unsigned int Dimension > +void +ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > +::GenerateOutputInformation(void) +{ + Superclass::GenerateOutputInformation(); + + OutputImagePointer outputPtr = this->GetOutput(); + + if (!outputPtr) { - typename LogPolarTransformType::ParametersType params(4); - // Center the transform - params[0]=0.5*static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[0]); - params[1]=0.5*static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[1]); - params[2]=360./m_OutputSize[0]; - params[3]=vcl_log(vcl_sqrt(vcl_pow(static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[0]),2) - +vcl_pow(static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[1]),2.))/2)/m_OutputSize[1]; + return; + } + typename OutputImageType::RegionType largestPossibleRegion; + typename OutputImageType::IndexType index; + index.Fill(0); + largestPossibleRegion.SetIndex(index); + largestPossibleRegion.SetSize(m_OutputSize); + outputPtr->SetLargestPossibleRegion(largestPossibleRegion); +} + +template < class TPixel,class TInterpol,unsigned int Dimension > +void +ForwardFourierMellinTransformImageFilter<TPixel, TInterpol, Dimension > +::GenerateData() +{ + typename LogPolarTransformType::ParametersType params(4); + // Center the transform + params[0]=0.5*static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[0]); + params[1]=0.5*static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[1]); + params[2]=360./m_OutputSize[0]; + params[3]=vcl_log(vcl_sqrt(vcl_pow(static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[0]),2) + +vcl_pow(static_cast<double>(this->GetInput()->GetLargestPossibleRegion().GetSize()[1]),2.))/2)/m_OutputSize[1]; m_Transform->SetParameters(params); // log polar resampling @@ -90,7 +90,7 @@ namespace otb // Normalization is specific to FourierMellin convergence conditions, and // thus should be implemented here instead of in the resample filter. - for(m_Iterator.GoToBegin();!m_Iterator.IsAtEnd();++m_Iterator) + for (m_Iterator.GoToBegin();!m_Iterator.IsAtEnd();++m_Iterator) { double Rho = m_Iterator.GetIndex()[1]*params[3]; PixelType pixval; @@ -99,18 +99,18 @@ namespace otb valueTemp *=params[3]; PixelType value = static_cast<PixelType>(valueTemp); - if( value < minOutputValue ) - { - pixval = minOutputValue; - } - else if( value > maxOutputValue ) - { - pixval = maxOutputValue; - } + if ( value < minOutputValue ) + { + pixval = minOutputValue; + } + else if ( value > maxOutputValue ) + { + pixval = maxOutputValue; + } else - { - pixval = static_cast<PixelType>(value); - } + { + pixval = static_cast<PixelType>(value); + } m_Iterator.Set(pixval); } m_FFTFilter->SetInput(tempImage ); diff --git a/Code/FeatureExtraction/otbGenericRoadExtractionFilter.h b/Code/FeatureExtraction/otbGenericRoadExtractionFilter.h index cc80cdd6aa6672b8141526d5fb30614c8497031e..d7a6e243f34dd8fcf171d0ae8d780d1309228d9b 100644 --- a/Code/FeatureExtraction/otbGenericRoadExtractionFilter.h +++ b/Code/FeatureExtraction/otbGenericRoadExtractionFilter.h @@ -71,83 +71,83 @@ namespace otb * \sa LikelihoodPathListFilter */ template <class TInputImage, class TOutputPath> - class ITK_EXPORT GenericRoadExtractionFilter - : public ImageToPathListFilter<TInputImage,TOutputPath> - { - public : - /** Standard typedefs */ - typedef GenericRoadExtractionFilter Self; - typedef ImageToPathListFilter<TInputImage,TOutputPath> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory macro */ - itkNewMacro(Self); - /** Type macro */ - itkTypeMacro(GenericRoadExtractionFilter,ImageToPathListFilter); - /** Template parameters typedefs */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputPathType OutputPathType; - typedef typename Superclass::OutputPathListType OutputPathListType; - typedef typename InputImageType::PixelType InputPixelType; - typedef double InternalPixelType; - - typedef otb::VectorImage<InternalPixelType,InputImageType::ImageDimension> VectorImageType; - typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> ModulusType; - typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> DirectionType; - - typedef itk::CovariantVector<InternalPixelType,InputImageType::ImageDimension> - VectorPixelType; - typedef otb::Image<VectorPixelType,InputImageType::ImageDimension> CovariantVectorImageType; - - - typedef itk::SqrtImageFilter< - InputImageType, - InputImageType> SquareRootImageFilterType; - - typedef itk::GradientRecursiveGaussianImageFilter< - InputImageType, - CovariantVectorImageType> GradientFilterType; - - typedef NeighborhoodScalarProductFilter< - CovariantVectorImageType, - ModulusType, - DirectionType> NeighborhoodScalarProductFilterType; - - typedef RemoveIsolatedByDirectionFilter< - ModulusType, - DirectionType, - ModulusType > RemoveIsolatedByDirectionFilterType; - - typedef RemoveWrongDirectionFilter< - ModulusType, - DirectionType, - ModulusType> RemoveWrongDirectionFilterType; - - typedef NonMaxRemovalByDirectionFilter< - ModulusType, - DirectionType, - ModulusType > NonMaxRemovalByDirectionFilterType; - - typedef VectorizationPathListFilter< - ModulusType, - DirectionType, - OutputPathType > VectorizationPathListFilterType; - - typedef SimplifyPathListFilter<OutputPathType> SimplifyPathListFilterType; - typedef BreakAngularPathListFilter<OutputPathType> BreakAngularPathListFilterType; - typedef RemoveTortuousPathListFilter<OutputPathType> RemoveTortuousPathListFilterType; - typedef LinkPathListFilter<OutputPathType> LinkPathListFilterType; - typedef LikelihoodPathListFilter<OutputPathType, ModulusType> LikelihoodPathListFilterType; - - /** Template parameters typedefs for internals filters */ - typedef typename GradientFilterType::RealType SigmaType; - typedef typename VectorizationPathListFilterType::InputPixelType AmplitudeThresholdType; +class ITK_EXPORT GenericRoadExtractionFilter + : public ImageToPathListFilter<TInputImage,TOutputPath> +{ +public : + /** Standard typedefs */ + typedef GenericRoadExtractionFilter Self; + typedef ImageToPathListFilter<TInputImage,TOutputPath> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory macro */ + itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(GenericRoadExtractionFilter,ImageToPathListFilter); + /** Template parameters typedefs */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputPathType OutputPathType; + typedef typename Superclass::OutputPathListType OutputPathListType; + typedef typename InputImageType::PixelType InputPixelType; + typedef double InternalPixelType; + + typedef otb::VectorImage<InternalPixelType,InputImageType::ImageDimension> VectorImageType; + typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> ModulusType; + typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> DirectionType; + + typedef itk::CovariantVector<InternalPixelType,InputImageType::ImageDimension> + VectorPixelType; + typedef otb::Image<VectorPixelType,InputImageType::ImageDimension> CovariantVectorImageType; + + + typedef itk::SqrtImageFilter< + InputImageType, + InputImageType> SquareRootImageFilterType; + + typedef itk::GradientRecursiveGaussianImageFilter< + InputImageType, + CovariantVectorImageType> GradientFilterType; + + typedef NeighborhoodScalarProductFilter< + CovariantVectorImageType, + ModulusType, + DirectionType> NeighborhoodScalarProductFilterType; + + typedef RemoveIsolatedByDirectionFilter< + ModulusType, + DirectionType, + ModulusType > RemoveIsolatedByDirectionFilterType; + + typedef RemoveWrongDirectionFilter< + ModulusType, + DirectionType, + ModulusType> RemoveWrongDirectionFilterType; + + typedef NonMaxRemovalByDirectionFilter< + ModulusType, + DirectionType, + ModulusType > NonMaxRemovalByDirectionFilterType; + + typedef VectorizationPathListFilter< + ModulusType, + DirectionType, + OutputPathType > VectorizationPathListFilterType; + + typedef SimplifyPathListFilter<OutputPathType> SimplifyPathListFilterType; + typedef BreakAngularPathListFilter<OutputPathType> BreakAngularPathListFilterType; + typedef RemoveTortuousPathListFilter<OutputPathType> RemoveTortuousPathListFilterType; + typedef LinkPathListFilter<OutputPathType> LinkPathListFilterType; + typedef LikelihoodPathListFilter<OutputPathType, ModulusType> LikelihoodPathListFilterType; + + /** Template parameters typedefs for internals filters */ + typedef typename GradientFilterType::RealType SigmaType; + typedef typename VectorizationPathListFilterType::InputPixelType AmplitudeThresholdType; // typedef typename SimplifyPathListFilterType::ToleranceType ToleranceType; - typedef double ToleranceType; - typedef typename BreakAngularPathListFilterType::MaxAngleType MaxAngleType; + typedef double ToleranceType; + typedef typename BreakAngularPathListFilterType::MaxAngleType MaxAngleType; // typedef typename RemoveTortuousPathListFilterType::MeanDistanceThresholdType MeanDistanceThresholdType; - typedef double MeanDistanceThresholdType; - typedef typename LinkPathListFilterType::RealType LinkRealType; + typedef double MeanDistanceThresholdType; + typedef typename LinkPathListFilterType::RealType LinkRealType; /** Get/Set the alpha value */ @@ -184,40 +184,40 @@ template <class TInputImage, class TOutputPath> itkGetMacro(DistanceThreshold,LinkRealType); - protected: - /** Constructor */ - GenericRoadExtractionFilter(); - /** Destructor */ - ~GenericRoadExtractionFilter() {}; +protected: + /** Constructor */ + GenericRoadExtractionFilter(); + /** Destructor */ + ~GenericRoadExtractionFilter() {}; - /** Prepare main computation method */ - void BeforeGenerateData(void); + /** Prepare main computation method */ + void BeforeGenerateData(void); - /** Main computation method */ - void GenerateData(void); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Main computation method */ + void GenerateData(void); + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : +private : - GenericRoadExtractionFilter(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented + GenericRoadExtractionFilter(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented - typename SquareRootImageFilterType::Pointer m_SquareRootImageFilter; - typename GradientFilterType::Pointer m_GradientFilter; - typename NeighborhoodScalarProductFilterType::Pointer m_NeighborhoodScalarProductFilter; - typename RemoveIsolatedByDirectionFilterType::Pointer m_RemoveIsolatedByDirectionFilter; - typename RemoveWrongDirectionFilterType::Pointer m_RemoveWrongDirectionFilter; - typename NonMaxRemovalByDirectionFilterType::Pointer m_NonMaxRemovalByDirectionFilter; - typename VectorizationPathListFilterType::Pointer m_VectorizationPathListFilter; - typename SimplifyPathListFilterType::Pointer m_FirstSimplifyPathListFilter; - typename SimplifyPathListFilterType::Pointer m_SecondSimplifyPathListFilter; - typename BreakAngularPathListFilterType::Pointer m_BreakAngularPathListFilter; - typename RemoveTortuousPathListFilterType::Pointer m_FirstRemoveTortuousPathListFilter; - typename RemoveTortuousPathListFilterType::Pointer m_SecondRemoveTortuousPathListFilter; - typename LinkPathListFilterType::Pointer m_LinkPathListFilter; - typename LikelihoodPathListFilterType::Pointer m_LikelihoodPathListFilter; + typename SquareRootImageFilterType::Pointer m_SquareRootImageFilter; + typename GradientFilterType::Pointer m_GradientFilter; + typename NeighborhoodScalarProductFilterType::Pointer m_NeighborhoodScalarProductFilter; + typename RemoveIsolatedByDirectionFilterType::Pointer m_RemoveIsolatedByDirectionFilter; + typename RemoveWrongDirectionFilterType::Pointer m_RemoveWrongDirectionFilter; + typename NonMaxRemovalByDirectionFilterType::Pointer m_NonMaxRemovalByDirectionFilter; + typename VectorizationPathListFilterType::Pointer m_VectorizationPathListFilter; + typename SimplifyPathListFilterType::Pointer m_FirstSimplifyPathListFilter; + typename SimplifyPathListFilterType::Pointer m_SecondSimplifyPathListFilter; + typename BreakAngularPathListFilterType::Pointer m_BreakAngularPathListFilter; + typename RemoveTortuousPathListFilterType::Pointer m_FirstRemoveTortuousPathListFilter; + typename RemoveTortuousPathListFilterType::Pointer m_SecondRemoveTortuousPathListFilter; + typename LinkPathListFilterType::Pointer m_LinkPathListFilter; + typename LikelihoodPathListFilterType::Pointer m_LikelihoodPathListFilter; /** Amplitude threshold to start following a path (use by the VectorizationPathListFilter)*/ @@ -243,7 +243,7 @@ template <class TInputImage, class TOutputPath> This value is set bye the image's spacing.*/ double m_Resolution; - }; +}; }// End namespace otb diff --git a/Code/FeatureExtraction/otbGenericRoadExtractionFilter.txx b/Code/FeatureExtraction/otbGenericRoadExtractionFilter.txx index 0ffd9dd74998e326dd446fe238efa809e83b5066..51f68a024367ecfa77e534afed4b752a867ee1b5 100644 --- a/Code/FeatureExtraction/otbGenericRoadExtractionFilter.txx +++ b/Code/FeatureExtraction/otbGenericRoadExtractionFilter.txx @@ -30,45 +30,45 @@ template <class TInputImage,class TOutputPath> GenericRoadExtractionFilter<TInputImage, TOutputPath> ::GenericRoadExtractionFilter() { - this->SetNumberOfRequiredInputs(1); - this->SetNumberOfRequiredOutputs(1); + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); m_SquareRootImageFilter = SquareRootImageFilterType::New(); - m_GradientFilter = GradientFilterType::New(); - m_NeighborhoodScalarProductFilter = NeighborhoodScalarProductFilterType::New(); - m_RemoveIsolatedByDirectionFilter = RemoveIsolatedByDirectionFilterType::New(); - m_RemoveWrongDirectionFilter = RemoveWrongDirectionFilterType::New(); - m_NonMaxRemovalByDirectionFilter = NonMaxRemovalByDirectionFilterType::New(); - m_VectorizationPathListFilter = VectorizationPathListFilterType::New(); - m_FirstSimplifyPathListFilter = SimplifyPathListFilterType::New(); - m_SecondSimplifyPathListFilter = SimplifyPathListFilterType::New(); - m_BreakAngularPathListFilter = BreakAngularPathListFilterType::New(); - m_FirstRemoveTortuousPathListFilter = RemoveTortuousPathListFilterType::New(); - m_SecondRemoveTortuousPathListFilter = RemoveTortuousPathListFilterType::New(); - m_LinkPathListFilter = LinkPathListFilterType::New(); - m_LikelihoodPathListFilter = LikelihoodPathListFilterType::New(); - - /** Amplitude threshold to start following a path (use by the VectorizationPathListFilter)*/ - m_AmplitudeThreshold = static_cast<AmplitudeThresholdType>(0.00005 ); - /** Tolerance for segment consistency (tolerance in terms of distance) (use by the SimplifyPathFilter)*/ - m_Tolerance = static_cast<ToleranceType>(1.); - /** Max angle (use bye the BreakAngularPathListFilter)*/ - m_MaxAngle = static_cast<MaxAngleType>(M_PI/8.); - /** Tolerance for segment consistency (tolerance in terms of distance) (use by RemoveTortuousPathFilter)*/ - m_FirstMeanDistanceThreshold = static_cast<MeanDistanceThresholdType>(1.); - m_SecondMeanDistanceThreshold = static_cast<MeanDistanceThresholdType>(10.); - /** The angular threshold (use by LinkPathFilter) */ - m_AngularThreshold = static_cast<LinkRealType>(M_PI/8.); - - /** The distance threshold (use by LinkPathFilter) */ - m_DistanceThreshold = 25.; - - /** Alpha value */ - /** Use to calculate the sigma value use by the GradientRecursiveGaussianImageFilter */ - m_Alpha = 1.0; - - /** Resolution of the image */ - m_Resolution = 1.; + m_GradientFilter = GradientFilterType::New(); + m_NeighborhoodScalarProductFilter = NeighborhoodScalarProductFilterType::New(); + m_RemoveIsolatedByDirectionFilter = RemoveIsolatedByDirectionFilterType::New(); + m_RemoveWrongDirectionFilter = RemoveWrongDirectionFilterType::New(); + m_NonMaxRemovalByDirectionFilter = NonMaxRemovalByDirectionFilterType::New(); + m_VectorizationPathListFilter = VectorizationPathListFilterType::New(); + m_FirstSimplifyPathListFilter = SimplifyPathListFilterType::New(); + m_SecondSimplifyPathListFilter = SimplifyPathListFilterType::New(); + m_BreakAngularPathListFilter = BreakAngularPathListFilterType::New(); + m_FirstRemoveTortuousPathListFilter = RemoveTortuousPathListFilterType::New(); + m_SecondRemoveTortuousPathListFilter = RemoveTortuousPathListFilterType::New(); + m_LinkPathListFilter = LinkPathListFilterType::New(); + m_LikelihoodPathListFilter = LikelihoodPathListFilterType::New(); + + /** Amplitude threshold to start following a path (use by the VectorizationPathListFilter)*/ + m_AmplitudeThreshold = static_cast<AmplitudeThresholdType>(0.00005 ); + /** Tolerance for segment consistency (tolerance in terms of distance) (use by the SimplifyPathFilter)*/ + m_Tolerance = static_cast<ToleranceType>(1.); + /** Max angle (use bye the BreakAngularPathListFilter)*/ + m_MaxAngle = static_cast<MaxAngleType>(M_PI/8.); + /** Tolerance for segment consistency (tolerance in terms of distance) (use by RemoveTortuousPathFilter)*/ + m_FirstMeanDistanceThreshold = static_cast<MeanDistanceThresholdType>(1.); + m_SecondMeanDistanceThreshold = static_cast<MeanDistanceThresholdType>(10.); + /** The angular threshold (use by LinkPathFilter) */ + m_AngularThreshold = static_cast<LinkRealType>(M_PI/8.); + + /** The distance threshold (use by LinkPathFilter) */ + m_DistanceThreshold = 25.; + + /** Alpha value */ + /** Use to calculate the sigma value use by the GradientRecursiveGaussianImageFilter */ + m_Alpha = 1.0; + + /** Resolution of the image */ + m_Resolution = 1.; } /** * Prepare main computation method @@ -82,10 +82,10 @@ GenericRoadExtractionFilter<TInputImage, TOutputPath> typename InputImageType::SpacingType spacing = this->GetInput()->GetSpacing(); // Getting x Spacing for the resolution m_Resolution = static_cast<double>(spacing[0]); - if( m_Resolution == 0. ) + if ( m_Resolution == 0. ) { - itkWarningMacro(<< "The image spacing is zero. So the resolution used in the filter is forced to 1."); - m_Resolution = 1.; + itkWarningMacro(<< "The image spacing is zero. So the resolution used in the filter is forced to 1."); + m_Resolution = 1.; } } @@ -99,8 +99,8 @@ GenericRoadExtractionFilter<TInputImage, TOutputPath> ::GenerateData() { // // Input images pointers - typename InputImageType::ConstPointer inputImage = this->GetInput(); - typename OutputPathListType::Pointer outputPathList = this->GetOutput(); + typename InputImageType::ConstPointer inputImage = this->GetInput(); + typename OutputPathListType::Pointer outputPathList = this->GetOutput(); /////////////////////////////////////// //// Algorithm for road extraction //// @@ -156,13 +156,13 @@ GenericRoadExtractionFilter<TInputImage, TOutputPath> // m_LikelihoodPathListFilter->GraftOutput(this->GetOutput()); m_LikelihoodPathListFilter->Update(); // outputPathList = m_LikelihoodPathListFilter->GetOutput(); - for(typename LikelihoodPathListFilterType::PathListType::ConstIterator it - = m_LikelihoodPathListFilter->GetOutput()->Begin(); - it!=m_LikelihoodPathListFilter->GetOutput()->End(); - ++it) - { - outputPathList->PushBack(it.Get()); - } + for (typename LikelihoodPathListFilterType::PathListType::ConstIterator it + = m_LikelihoodPathListFilter->GetOutput()->Begin(); + it!=m_LikelihoodPathListFilter->GetOutput()->End(); + ++it) + { + outputPathList->PushBack(it.Get()); + } } /** * PrintSelf method diff --git a/Code/FeatureExtraction/otbGeometricMomentImageFunction.h b/Code/FeatureExtraction/otbGeometricMomentImageFunction.h index 35787ff956e5380159dc37e2a5df7d23ab0097cf..5ab94c5b37f2ca2c471220310d38ac0e12535bd1 100644 --- a/Code/FeatureExtraction/otbGeometricMomentImageFunction.h +++ b/Code/FeatureExtraction/otbGeometricMomentImageFunction.h @@ -32,11 +32,11 @@ namespace otb */ template < class TInput, - class TOutput = float, - class TPrecision = double, - class TCoordRep = float > +class TOutput = float, +class TPrecision = double, +class TCoordRep = float > class ITK_EXPORT GeometricMomentImageFunction : - public itk::ImageFunction<TInput, TOutput,TCoordRep > + public itk::ImageFunction<TInput, TOutput,TCoordRep > { public: /** Standard class typedefs. */ @@ -66,16 +66,16 @@ public: protected: GeometricMomentImageFunction() - { - m_NeighborhoodRadius = -1; + { + m_NeighborhoodRadius = -1; }; - ~GeometricMomentImageFunction(){}; + ~GeometricMomentImageFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf( os, indent ); - os << indent << " m_NeighborhoodRadius: " << m_NeighborhoodRadius << std::endl; - } + { + Superclass::PrintSelf( os, indent ); + os << indent << " m_NeighborhoodRadius: " << m_NeighborhoodRadius << std::endl; + } private: GeometricMomentImageFunction( const Self& ); //purposely not implemented diff --git a/Code/FeatureExtraction/otbGeometricMomentPathFunction.h b/Code/FeatureExtraction/otbGeometricMomentPathFunction.h index 479bf4b36a0a03c1f5629117c48d579c40cf90eb..67bacb5468374e6350c73e2987061f082f270ba6 100644 --- a/Code/FeatureExtraction/otbGeometricMomentPathFunction.h +++ b/Code/FeatureExtraction/otbGeometricMomentPathFunction.h @@ -32,10 +32,10 @@ namespace otb */ template < class TInputPath, - class TOutput, - class TPrecision = double> +class TOutput, +class TPrecision = double> class ITK_EXPORT GeometricMomentPathFunction : - public PathFunction< TInputPath, TOutput> + public PathFunction< TInputPath, TOutput> { public: /** Standard class typedefs. */ @@ -61,11 +61,11 @@ public: protected: GeometricMomentPathFunction() {}; - ~GeometricMomentPathFunction(){}; + ~GeometricMomentPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf( os, indent ); - } + { + Superclass::PrintSelf( os, indent ); + } private: GeometricMomentPathFunction( const Self& ); //purposely not implemented diff --git a/Code/FeatureExtraction/otbHarrisImageFilter.h b/Code/FeatureExtraction/otbHarrisImageFilter.h index f447f88e26f1ab9eef0daeda40439ee5b6a6220d..2af22448a277fc05bf2d9fb4928dfac333044065 100644 --- a/Code/FeatureExtraction/otbHarrisImageFilter.h +++ b/Code/FeatureExtraction/otbHarrisImageFilter.h @@ -54,10 +54,10 @@ class HarrisImageFilter : public itk::ImageToImageFilter< TInputImage, TOutputI public: itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); typedef TInputImage InputImageType; @@ -80,14 +80,14 @@ public: // typedef typename InputImageType::SizeType SizeType; typedef itk::Image< itk::SymmetricSecondRankTensor< - typename itk::NumericTraits< InputPixelType>::RealType, - ::itk::GetImageDimension<InputImageType>::ImageDimension >, - ::itk::GetImageDimension<InputImageType>::ImageDimension > TensorType; + typename itk::NumericTraits< InputPixelType>::RealType, + ::itk::GetImageDimension<InputImageType>::ImageDimension >, + ::itk::GetImageDimension<InputImageType>::ImageDimension > TensorType; typedef itk::HessianRecursiveGaussianImageFilter<InputImageType,TensorType > HessianFilterType; typedef itk::RecursiveGaussianImageFilter<TensorType, - TensorType> GaussianFilterType; + TensorType> GaussianFilterType; typedef otb::HessianToScalarImageFilter<TensorType,OutputImageType > HessianToScalarFilterType; typedef otb::MultiplyByScalarImageFilter<OutputImageType,OutputImageType> MultiplyScalarFilterType; diff --git a/Code/FeatureExtraction/otbHarrisImageToPointSetFilter.h b/Code/FeatureExtraction/otbHarrisImageToPointSetFilter.h index fc01ac46b4a6e0afc1f4b87540d1ce60094f3df0..8182d995f2b5aaf39b03343e9d1355352ad1e782 100644 --- a/Code/FeatureExtraction/otbHarrisImageToPointSetFilter.h +++ b/Code/FeatureExtraction/otbHarrisImageToPointSetFilter.h @@ -30,14 +30,14 @@ namespace otb */ template <class TInputImage, - class TOutputPointSet = itk::PointSet<ITK_TYPENAME TInputImage::PixelType,2> > +class TOutputPointSet = itk::PointSet<ITK_TYPENAME TInputImage::PixelType,2> > class ITK_EXPORT HarrisImageToPointSetFilter : - public ImageToPointSetFilter< TInputImage,TOutputPointSet > + public ImageToPointSetFilter< TInputImage,TOutputPointSet > { public: itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); typedef TInputImage InputImageType; @@ -57,7 +57,7 @@ public: typedef typename otb::HarrisImageFilter<InputImageType,InputImageType> HarrisImageFilterType; typedef typename otb::ThresholdImageToPointSetFilter<InputImageType, - OutputPointSetType> ThresholdImageToPointSetType; + OutputPointSetType> ThresholdImageToPointSetType; typedef typename OutputPointSetType::PixelType OutputPixelType; diff --git a/Code/FeatureExtraction/otbHessianToScalarImageFilter.h b/Code/FeatureExtraction/otbHessianToScalarImageFilter.h index 8fb50ad83ef5bdfca5688a1d17e06d4f048932b7..99fab2af9a076c14f499caaaf7c668e95c680269 100644 --- a/Code/FeatureExtraction/otbHessianToScalarImageFilter.h +++ b/Code/FeatureExtraction/otbHessianToScalarImageFilter.h @@ -27,13 +27,17 @@ namespace otb * */ -namespace Functor { +namespace Functor +{ template< class TInput, class TOutput > class HessianToScalar { public: - HessianToScalar() {m_Alpha = 1.0;} + HessianToScalar() + { + m_Alpha = 1.0; + } ~HessianToScalar() {}; inline TOutput operator()( const TInput & Hessian ) { @@ -66,21 +70,21 @@ private: template <class TInputImage, class TOutputImage> class ITK_EXPORT HessianToScalarImageFilter : - public itk::UnaryFunctorImageFilter< - TInputImage,TOutputImage, - Functor::HessianToScalar< - ITK_TYPENAME TInputImage::PixelType, - ITK_TYPENAME TOutputImage::PixelType> > + public itk::UnaryFunctorImageFilter< + TInputImage,TOutputImage, + Functor::HessianToScalar< + ITK_TYPENAME TInputImage::PixelType, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef HessianToScalarImageFilter Self; typedef typename itk::UnaryFunctorImageFilter< - TInputImage, - TOutputImage, - Functor::HessianToScalar< - ITK_TYPENAME TInputImage::PixelType, - ITK_TYPENAME TOutputImage::PixelType> > Superclass; + TInputImage, + TOutputImage, + Functor::HessianToScalar< + ITK_TYPENAME TInputImage::PixelType, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -89,12 +93,12 @@ public: void SetAlpha(double Alpha) { - this->GetFunctor().SetAlpha( Alpha ); - this->Modified(); + this->GetFunctor().SetAlpha( Alpha ); + this->Modified(); } double GetAlpha(void)const { - return( this->GetFunctor().GetAlpha() ); + return( this->GetFunctor().GetAlpha() ); } protected: HessianToScalarImageFilter() {} diff --git a/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.h b/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.h index 1ab568cd41f94f6c821158687149c6268565c93f..8da15424e376f1cbdc3c7aaf211e8d664223be7b 100644 --- a/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.h +++ b/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.h @@ -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. =========================================================================*/ @@ -32,38 +32,38 @@ namespace otb * \class HoughTransform2DLinesImageFilter * \brief Performs the Hough Transform to find 2D straight lines * in a 2D image. - * + * * This filter derives from ImageToImageFilter * The input is an image, and all pixels above some threshold are those * to be extracted. The output is the image of the accumulator. * GetLines() returns a list of LinesSpatialObjects * * Lines are parameterized in the form: R = x*vcl_cos(Teta)+y*vcl_sin(Teta) - * where R is the perpendicular distance from the origin and Teta + * where R is the perpendicular distance from the origin and Teta * the angle with the normal. * * The output is the accumulator array: - * -The first dimension (X) represents the distance R from the origin + * -The first dimension (X) represents the distance R from the origin * to the line. This is the distance axis. Its size depends on the size * of the diagonal of the input image. - * + * * -The second dimension (Y) represents the angle between the X axis * and the normal to the line. This is the angle axis. Its size depends * on the AngleAxisSize parameter (500 by default) and its bounds can be * set with the AngleAxisMinimum and AngleAxisMaximum parameters * (-PI and +PI by default). * - * \ingroup ImageFeatureExtraction + * \ingroup ImageFeatureExtraction * \sa LineSpatialObject * * */ template<typename TInputPixelType, typename TOutputPixelType> class ITK_EXPORT HoughTransform2DLinesImageFilter : - public itk::ImageToImageFilter< itk::Image<TInputPixelType,2>, itk::Image<TOutputPixelType,2> > + public itk::ImageToImageFilter< itk::Image<TInputPixelType,2>, itk::Image<TOutputPixelType,2> > { public: - + /** Standard "Self" typedef. */ typedef HoughTransform2DLinesImageFilter Self; @@ -71,7 +71,7 @@ public: typedef itk::Image<TInputPixelType,2> InputImageType; typedef typename InputImageType::Pointer InputImagePointer; typedef typename InputImageType::ConstPointer InputImageConstPointer; - + /** Output Image typedef */ typedef itk::Image<TOutputPixelType,2> OutputImageType; typedef typename OutputImageType::Pointer OutputImagePointer; @@ -102,7 +102,7 @@ public: itkTypeMacro( HoughTransform2DLinesImageFilter, ImageToImageFilter ); /** Method for creation through the object factory. */ - itkNewMacro(Self); + itkNewMacro(Self); /** Method for evaluating the implicit function over the image. */ void GenerateData(); @@ -205,13 +205,13 @@ protected: void EnlargeOutputRequestedRegion(itk::DataObject *output); int GetAngleIndex(double); - + double GetAngleValue(int); - + int GetDistanceIndex(double); - + double GetDistanceValue(int); - + private: unsigned int m_AngleAxisSize; diff --git a/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.txx b/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.txx index 1aef4765167070ef7f4cdfb42b0241d51a148d0a..efce6ccda01c250a998b73aa4ddda0065ee05935 100644 --- a/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.txx +++ b/Code/FeatureExtraction/otbHoughTransform2DLinesImageFilter.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. =========================================================================*/ @@ -54,7 +54,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> } template<typename TInputPixelType, typename TOutputPixelType> -void +void HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> ::EnlargeOutputRequestedRegion(itk::DataObject *output) { @@ -66,7 +66,7 @@ HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> -void +void HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> ::GenerateOutputInformation() { @@ -78,9 +78,9 @@ HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> OutputImagePointer output = this->GetOutput(); if ( !input || !output ) - { + { return; - } + } // Compute the size of the output image if (m_DistanceAxisSize +1 == 0) @@ -104,16 +104,16 @@ HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> -void +void HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> ::GenerateInputRequestedRegion() { Superclass::GenerateInputRequestedRegion(); if ( this->GetInput() ) - { + { InputImagePointer image = const_cast< InputImageType * >( this->GetInput() ); image->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -147,36 +147,36 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> std::vector<double> sinAngle(nbAngles,0.); //const double nPI = 4.0 * vcl_atan( 1.0 ); Unused in this method - for(unsigned int indexAngle = 0; indexAngle < nbAngles; indexAngle ++ ) - { - double angle = this->GetAngleValue(indexAngle); - cosAngle[indexAngle] = vcl_cos(angle); - sinAngle[indexAngle] = vcl_sin(angle); - } + for (unsigned int indexAngle = 0; indexAngle < nbAngles; indexAngle ++ ) + { + double angle = this->GetAngleValue(indexAngle); + cosAngle[indexAngle] = vcl_cos(angle); + sinAngle[indexAngle] = vcl_sin(angle); + } - while( !image_it.IsAtEnd() ) + while ( !image_it.IsAtEnd() ) + { + if (image_it.Get()>m_Threshold) { - if(image_it.Get()>m_Threshold) - { - for(unsigned int indexAngle = 0; indexAngle < nbAngles; indexAngle ++ ) - { - double r = image_it.GetIndex()[0]*cosAngle[indexAngle]+image_it.GetIndex()[1]*sinAngle[indexAngle]; - unsigned int indexR = this->GetDistanceIndex(r); - index[0]= indexR; // m_R - index[1]= indexAngle; // m_Theta - if ( outputImage->GetBufferedRegion().IsInside(index) ) - { - outputImage->SetPixel(index, outputImage->GetPixel(index)+image_it.Get()); - } + for (unsigned int indexAngle = 0; indexAngle < nbAngles; indexAngle ++ ) + { + double r = image_it.GetIndex()[0]*cosAngle[indexAngle]+image_it.GetIndex()[1]*sinAngle[indexAngle]; + unsigned int indexR = this->GetDistanceIndex(r); + index[0]= indexR; // m_R + index[1]= indexAngle; // m_Theta + if ( outputImage->GetBufferedRegion().IsInside(index) ) + { + outputImage->SetPixel(index, outputImage->GetPixel(index)+image_it.Get()); } } - ++image_it; } + ++image_it; + } } -/** Simplify the accumulator - * Do the same iteration process as the Update() method but find the maximum +/** Simplify the accumulator + * Do the same iteration process as the Update() method but find the maximum * along the curve and then remove the curve */ template<typename TInputPixelType, typename TOutputPixelType> void @@ -187,10 +187,10 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> InputImageConstPointer inputImage = this->GetInput(0); OutputImagePointer outputImage = this->GetOutput(0); - if(!inputImage || !outputImage) - { + if (!inputImage || !outputImage) + { itkExceptionMacro("Update() must be called before Simplify()."); - } + } /** Allocate the simplify accumulator */ m_SimplifyAccumulator = OutputImageType::New(); @@ -204,65 +204,65 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> itk::Index<2> maxIndex; typename OutputImageType::PixelType value; typename OutputImageType::PixelType valuemax; - + itk::ImageRegionConstIteratorWithIndex< InputImageType > image_it( inputImage, inputImage->GetRequestedRegion() ); image_it.GoToBegin(); - while( !image_it.IsAtEnd() ) + while ( !image_it.IsAtEnd() ) + { + if (image_it.Get()>m_Threshold) { - if(image_it.Get()>m_Threshold) - { - // Look for maximum along the curve and remove the curve at the same time + // Look for maximum along the curve and remove the curve at the same time valuemax = -1; maxIndex[0]=0; maxIndex[1]=0; - for(double angle = m_AngleAxisMinimum; angle < m_AngleAxisMaximum; angle += m_AngleAxisIncrement ) - { + for (double angle = m_AngleAxisMinimum; angle < m_AngleAxisMaximum; angle += m_AngleAxisIncrement ) + { index[0]= (long int)(image_it.GetIndex()[0]*vcl_cos(angle)+image_it.GetIndex()[1]*vcl_sin(angle)); // m_R index[1]= (long int)( this->GetAngleIndex(angle)); // m_Theta - + if ( outputImage->GetBufferedRegion().IsInside(index) ) - { + { value = outputImage->GetPixel(index); - if( value > valuemax) - { + if ( value > valuemax) + { valuemax = value; maxIndex = index; - } } - } - m_SimplifyAccumulator->SetPixel(maxIndex,m_SimplifyAccumulator->GetPixel(maxIndex)+1); + } } - ++image_it; + m_SimplifyAccumulator->SetPixel(maxIndex,m_SimplifyAccumulator->GetPixel(maxIndex)+1); } - - itk::ImageRegionConstIteratorWithIndex< OutputImageType > accusimple_it( m_SimplifyAccumulator, m_SimplifyAccumulator->GetRequestedRegion() ); - itk::ImageRegionIteratorWithIndex< OutputImageType > accu_it( outputImage, outputImage->GetRequestedRegion() ); + ++image_it; + } + + itk::ImageRegionConstIteratorWithIndex< OutputImageType > accusimple_it( m_SimplifyAccumulator, m_SimplifyAccumulator->GetRequestedRegion() ); + itk::ImageRegionIteratorWithIndex< OutputImageType > accu_it( outputImage, outputImage->GetRequestedRegion() ); + - accusimple_it.GoToBegin(); accu_it.GoToBegin(); - while( !accusimple_it.IsAtEnd() ) - { + while ( !accusimple_it.IsAtEnd() ) + { accu_it.Set(accusimple_it.Get()); ++accu_it; ++accusimple_it; - } + } } /** Get the list of lines. This recomputes the lines */ template<typename TInputPixelType, typename TOutputPixelType> -typename HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType>::LinesListType & +typename HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType>::LinesListType & HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> ::GetLines(unsigned int n) { - if((this->GetMTime() == m_OldModifiedTime) && (n == m_OldNumberOfLines)) // if the filter has not been updated - { + if ((this->GetMTime() == m_OldModifiedTime) && (n == m_OldNumberOfLines)) // if the filter has not been updated + { return m_LinesList; - } + } m_LinesList.clear(); @@ -270,19 +270,19 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> typedef float InternalImagePixelType; typedef itk::Image< InternalImagePixelType,2 > InternalImageType; - OutputImagePointer outputImage = this->GetOutput(0); + OutputImagePointer outputImage = this->GetOutput(0); - if( !outputImage ) - { + if ( !outputImage ) + { itkExceptionMacro("Update() must be called before GetLines()."); - } + } /** Convert the accumulator output image type to internal image type*/ - typedef itk::CastImageFilter< OutputImageType, InternalImageType> CastImageFilterType; + typedef itk::CastImageFilter< OutputImageType, InternalImageType> CastImageFilterType; typename CastImageFilterType::Pointer castImageFilter = CastImageFilterType::New(); castImageFilter->SetInput(outputImage); - + typedef itk::DiscreteGaussianImageFilter<InternalImageType,InternalImageType> GaussianFilterType; typename GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New(); @@ -296,8 +296,8 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> typedef itk::MinimumMaximumImageCalculator<InternalImageType> MinMaxCalculatorType; typename MinMaxCalculatorType::Pointer minMaxCalculator = MinMaxCalculatorType::New(); - itk::ImageRegionIterator<InternalImageType> - it_input(postProcessImage,postProcessImage->GetLargestPossibleRegion()); + itk::ImageRegionIterator<InternalImageType> + it_input(postProcessImage,postProcessImage->GetLargestPossibleRegion()); const double nPI = 4.0 * vcl_atan( 1.0 ); @@ -308,20 +308,20 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> // Find maxima do - { + { minMaxCalculator->SetImage(postProcessImage); minMaxCalculator->ComputeMaximum(); InternalImageType::PixelType max = minMaxCalculator->GetMaximum(); found = false; - for(it_input.GoToBegin();!it_input.IsAtEnd();++it_input) + for (it_input.GoToBegin();!it_input.IsAtEnd();++it_input) + { + if (it_input.Get() == max) { - if(it_input.Get() == max) - { // Create the line LineType::PointListType list; // insert two points per line - double radius = this->GetDistanceValue(it_input.GetIndex()[0]) ; + double radius = this->GetDistanceValue(it_input.GetIndex()[0]) ; double teta = this->GetAngleValue(it_input.GetIndex()[1]) ; double Vx = radius*vcl_cos(teta ); double Vy = radius*vcl_sin(teta ); @@ -329,30 +329,30 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> double VxNorm = Vx/norm; double VyNorm = Vy/norm; - if((teta<=0) || (teta >= nPI / 2 ) ) + if ((teta<=0) || (teta >= nPI / 2 ) ) + { + if (teta >= nPI/2) { - if(teta >= nPI/2) - { VyNorm = - VyNorm; VxNorm = - VxNorm; - } + } LinePointType p; p.SetPosition(Vx,Vy); list.push_back(p); p.SetPosition(Vx-VyNorm*5,Vy+VxNorm*5); list.push_back(p); - } + } else // if teta>0 - { + { LinePointType p; p.SetPosition(Vx,Vy); list.push_back(p); p.SetPosition(Vx-VyNorm*5,Vy+VxNorm*5); list.push_back(p); - } // end if(teta>0) - - + } // end if(teta>0) + + // Create a Line Spatial Object LinePointer Line = LineType::New(); Line->SetId(lines); @@ -360,31 +360,32 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> Line->ComputeBoundingBox(); m_LinesList.push_back(Line); - + // Remove a black disc from the hough space domain - for(double angle = m_AngleAxisMinimum; angle <= m_AngleAxisMaximum ; angle += m_AngleAxisIncrement) - { - for(double length = 0; length < m_DiscRadius;length += 1) - { + for (double angle = m_AngleAxisMinimum; angle <= m_AngleAxisMaximum ; angle += m_AngleAxisIncrement) + { + for (double length = 0; length < m_DiscRadius;length += 1) + { index[0] = (long int)(it_input.GetIndex()[0] + length * vcl_cos(angle)); index[1] = (long int)(it_input.GetIndex()[1] + length * vcl_sin(angle)); - if( postProcessImage->GetBufferedRegion().IsInside(index) ) - { + if ( postProcessImage->GetBufferedRegion().IsInside(index) ) + { postProcessImage->SetPixel(index,0); - } - } + } } + } minMaxCalculator->SetImage(postProcessImage); minMaxCalculator->ComputeMaximum(); max = minMaxCalculator->GetMaximum(); - + lines++; found = true; - if(lines == m_NumberOfLines) break; - } + if (lines == m_NumberOfLines) break; } - } while((lines<m_NumberOfLines) && (found)); - + } + } + while ((lines<m_NumberOfLines) && (found)); + m_OldModifiedTime = this->GetMTime(); m_OldNumberOfLines = m_LinesList.size(); return m_LinesList; @@ -394,7 +395,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> void HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> - ::PrintSelf(std::ostream& os, itk::Indent indent) const +::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os,indent); @@ -412,7 +413,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> int HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> - ::GetAngleIndex(double angle) +::GetAngleIndex(double angle) { int indexAngle = static_cast<int>((angle-m_AngleAxisMinimum)/m_AngleAxisIncrement); return indexAngle; @@ -422,7 +423,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> double HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> - ::GetAngleValue(int indexAngle) +::GetAngleValue(int indexAngle) { double angle = m_AngleAxisMinimum + indexAngle * m_AngleAxisIncrement; return angle; @@ -432,7 +433,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> int HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> - ::GetDistanceIndex(double distance) +::GetDistanceIndex(double distance) { int indexDistance = static_cast<int>((distance-m_DistanceAxisMinimum)/m_DistanceAxisIncrement); return indexDistance; @@ -442,7 +443,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> template<typename TInputPixelType, typename TOutputPixelType> double HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType> - ::GetDistanceValue(int indexDistance) +::GetDistanceValue(int indexDistance) { double distance = m_DistanceAxisMinimum + indexDistance * m_DistanceAxisIncrement; return distance; diff --git a/Code/FeatureExtraction/otbHuImageFunction.h b/Code/FeatureExtraction/otbHuImageFunction.h index f4e631a4b10c1f921092e1c4cbd6f89cd0c1928d..31bcb5cc8aa627ae4de0d7237f57c0ef2f18a224 100644 --- a/Code/FeatureExtraction/otbHuImageFunction.h +++ b/Code/FeatureExtraction/otbHuImageFunction.h @@ -54,11 +54,11 @@ namespace otb // public itk::ImageFunction< TInput, TOutput,TCoordRep > template < class TInput, - class TOutput = double, - class TPrecision = double, - class TCoordRep = float > +class TOutput = double, +class TPrecision = double, +class TCoordRep = float > class ITK_EXPORT HuImageFunction : - public RealMomentImageFunction< TInput, TOutput, TPrecision, TCoordRep > + public RealMomentImageFunction< TInput, TOutput, TPrecision, TCoordRep > { public: /** Standard class typedefs. */ @@ -93,20 +93,20 @@ public: /** Evalulate the function at specified index */ virtual RealType EvaluateAtIndex( const IndexType& index ) const; - /** Evaluate the function at non-integer positions */ + /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const - { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); + } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const - { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ); - } + { + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); + } /** Get/Set the radius of the neighborhood over which the @@ -116,7 +116,7 @@ public: protected: HuImageFunction(); - ~HuImageFunction(){}; + ~HuImageFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbHuImageFunction.txx b/Code/FeatureExtraction/otbHuImageFunction.txx index d02b83fe000f282cc66fbcb45c0deb0bd717669a..baa05b181af31be63a34372217032284f9d17eaa 100644 --- a/Code/FeatureExtraction/otbHuImageFunction.txx +++ b/Code/FeatureExtraction/otbHuImageFunction.txx @@ -62,124 +62,124 @@ HuImageFunction<TInput,TOutput,TPrecision,TCoordRep> typedef otb::ComplexMomentImageFunction<InputType,ComplexType> CMType; typename CMType::Pointer function =CMType::New(); - if( !this->GetInputImage() ) - { + if ( !this->GetInputImage() ) + { return ( itk::NumericTraits<RealType>::max() ); - } + } if ( !this->IsInsideBuffer( index ) ) - { + { otbMsgDevMacro( << index ); return ( itk::NumericTraits<RealType>::max() ); - } + } assert(m_MomentNumber > 0); assert(m_MomentNumber < 8); - function->SetInputImage( this->GetInputImage() ); - function->SetNeighborhoodRadius(this->GetNeighborhoodRadius() ); - - switch(m_MomentNumber) - { - case 1 : - { - ComplexType C11; - function->SetP(1); - function->SetQ(1); - C11 = function->EvaluateAtIndex( index ); - HuValue = C11.real(); + function->SetInputImage( this->GetInputImage() ); + function->SetNeighborhoodRadius(this->GetNeighborhoodRadius() ); + + switch (m_MomentNumber) + { + case 1 : + { + ComplexType C11; + function->SetP(1); + function->SetQ(1); + C11 = function->EvaluateAtIndex( index ); + HuValue = C11.real(); } break; - case 2: - { - ComplexType C20,C02; - function->SetP(2); - function->SetQ(0); - C20 = function->EvaluateAtIndex( index ); - function->SetP(0); - function->SetQ(2); - C02 = function->EvaluateAtIndex( index ); - - HuValue = vcl_abs( C20 * C02 ); + case 2: + { + ComplexType C20,C02; + function->SetP(2); + function->SetQ(0); + C20 = function->EvaluateAtIndex( index ); + function->SetP(0); + function->SetQ(2); + C02 = function->EvaluateAtIndex( index ); + + HuValue = vcl_abs( C20 * C02 ); } break; - case 3: - { - ComplexType C30,C03; - function->SetP(3); - function->SetQ(0); - C30 = function->EvaluateAtIndex( index ); - function->SetP(0); - function->SetQ(3); - C03 = function->EvaluateAtIndex( index ); - - HuValue = vcl_abs( C30 * C03 ); + case 3: + { + ComplexType C30,C03; + function->SetP(3); + function->SetQ(0); + C30 = function->EvaluateAtIndex( index ); + function->SetP(0); + function->SetQ(3); + C03 = function->EvaluateAtIndex( index ); + + HuValue = vcl_abs( C30 * C03 ); } break; - case 4: - { - ComplexType C21,C12; - function->SetP(2); - function->SetQ(1); - C21 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - HuValue = vcl_abs( C21 * C12 ); + case 4: + { + ComplexType C21,C12; + function->SetP(2); + function->SetQ(1); + C21 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + HuValue = vcl_abs( C21 * C12 ); } break; - case 5: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - HuValueComplex = C30 * vcl_pow(C12,3); - HuValue = HuValueComplex.real(); + case 5: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + HuValueComplex = C30 * vcl_pow(C12,3); + HuValue = HuValueComplex.real(); } break; - case 6: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - HuValueComplex = C20 * vcl_pow( C12 ,2 ); - HuValue = HuValueComplex.real(); + case 6: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + HuValueComplex = C20 * vcl_pow( C12 ,2 ); + HuValue = HuValueComplex.real(); } break; - case 7: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->EvaluateAtIndex( index ); - function->SetP(1); - function->SetQ(2); - C12 = function->EvaluateAtIndex( index ); - - HuValueComplex = C30 * vcl_pow( C12 , 3); - HuValue = HuValueComplex.imag(); + case 7: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->EvaluateAtIndex( index ); + function->SetP(1); + function->SetQ(2); + C12 = function->EvaluateAtIndex( index ); + + HuValueComplex = C30 * vcl_pow( C12 , 3); + HuValue = HuValueComplex.imag(); } break; - default: - itkWarningMacro("Hu's invariant parameters are between 1 and 7"); - } + default: + itkWarningMacro("Hu's invariant parameters are between 1 and 7"); + } return (static_cast<RealType>(HuValue) ); diff --git a/Code/FeatureExtraction/otbHuPathFunction.h b/Code/FeatureExtraction/otbHuPathFunction.h index be01c3749c00646eb5c2a3af7d332534fa969301..46f798baca1a53d4e2a8c7fbf2401fc4546c91a9 100644 --- a/Code/FeatureExtraction/otbHuPathFunction.h +++ b/Code/FeatureExtraction/otbHuPathFunction.h @@ -53,10 +53,10 @@ namespace otb */ template < class TInputPath, - class TOutput = double, - class TPrecision = double> +class TOutput = double, +class TPrecision = double> class ITK_EXPORT HuPathFunction : - public RealMomentPathFunction< TInputPath, TOutput, TPrecision > + public RealMomentPathFunction< TInputPath, TOutput, TPrecision > { public: /** Standard class typedefs. */ @@ -94,7 +94,7 @@ public: protected: HuPathFunction(); - ~HuPathFunction(){}; + ~HuPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbHuPathFunction.txx b/Code/FeatureExtraction/otbHuPathFunction.txx index ac67014aaae87bdb9bcb52c29e1e1c0d88796251..fe47a85f1749e9222609c295a7b8f5c5471ea9d4 100644 --- a/Code/FeatureExtraction/otbHuPathFunction.txx +++ b/Code/FeatureExtraction/otbHuPathFunction.txx @@ -66,106 +66,106 @@ HuPathFunction<TInputPath, TOutput, TPrecision > function->SetStep( this->GetStep() ); function->SetInputPath( this->GetInputPath() ); - switch(m_MomentNumber) - { - case 1 : - { - ComplexType C11; - function->SetP(1); - function->SetQ(1); - C11 = function->Evaluate( ); - HuValue = C11.real(); + switch (m_MomentNumber) + { + case 1 : + { + ComplexType C11; + function->SetP(1); + function->SetQ(1); + C11 = function->Evaluate( ); + HuValue = C11.real(); } break; - case 2: - { - ComplexType C20,C02; - function->SetP(2); - function->SetQ(0); - C20 = function->Evaluate( ); - function->SetP(0); - function->SetQ(2); - C02 = function->Evaluate( ); - - HuValue = vcl_abs( C20 * C02 ); + case 2: + { + ComplexType C20,C02; + function->SetP(2); + function->SetQ(0); + C20 = function->Evaluate( ); + function->SetP(0); + function->SetQ(2); + C02 = function->Evaluate( ); + + HuValue = vcl_abs( C20 * C02 ); } break; - case 3: - { - ComplexType C30,C03; - function->SetP(3); - function->SetQ(0); - C30 = function->Evaluate( ); - function->SetP(0); - function->SetQ(3); - C03 = function->Evaluate( ); - - HuValue = vcl_abs( C30 * C03 ); + case 3: + { + ComplexType C30,C03; + function->SetP(3); + function->SetQ(0); + C30 = function->Evaluate( ); + function->SetP(0); + function->SetQ(3); + C03 = function->Evaluate( ); + + HuValue = vcl_abs( C30 * C03 ); } break; - case 4: - { - ComplexType C21,C12; - function->SetP(2); - function->SetQ(1); - C21 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - HuValue = vcl_abs( C21 * C12 ); + case 4: + { + ComplexType C21,C12; + function->SetP(2); + function->SetQ(1); + C21 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + HuValue = vcl_abs( C21 * C12 ); } break; - case 5: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - HuValueComplex = C30 * vcl_pow(C12,3); - HuValue = HuValueComplex.real(); + case 5: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + HuValueComplex = C30 * vcl_pow(C12,3); + HuValue = HuValueComplex.real(); } break; - case 6: - { - ComplexType C20,C12; - function->SetP(2); - function->SetQ(0); - C20 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - HuValueComplex = C20 * vcl_pow( C12 ,2 ); - HuValue = HuValueComplex.real(); + case 6: + { + ComplexType C20,C12; + function->SetP(2); + function->SetQ(0); + C20 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + HuValueComplex = C20 * vcl_pow( C12 ,2 ); + HuValue = HuValueComplex.real(); } break; - case 7: - { - ComplexType C30,C12; - function->SetP(3); - function->SetQ(0); - C30 = function->Evaluate( ); - function->SetP(1); - function->SetQ(2); - C12 = function->Evaluate( ); - - HuValueComplex = C30 * vcl_pow( C12 , 3); - HuValue = HuValueComplex.imag(); + case 7: + { + ComplexType C30,C12; + function->SetP(3); + function->SetQ(0); + C30 = function->Evaluate( ); + function->SetP(1); + function->SetQ(2); + C12 = function->Evaluate( ); + + HuValueComplex = C30 * vcl_pow( C12 , 3); + HuValue = HuValueComplex.imag(); } break; - default: - itkWarningMacro("Hu's invariant parameters are between 1 and 7"); - } + default: + itkWarningMacro("Hu's invariant parameters are between 1 and 7"); + } return (static_cast<RealType>(HuValue) ); @@ -176,11 +176,11 @@ typename HuPathFunction<TInputPath, TOutput, TPrecision >::RealType HuPathFunction<TInputPath, TOutput, TPrecision > ::Evaluate( ) const { - if( !this->GetInputPath() ) - { + if ( !this->GetInputPath() ) + { otbMsgDevMacro( << "Pb with GetInputPath" ); return static_cast<RealType>( itk::NumericTraits<PrecisionType>::max()); - } + } RealType Result = Evaluate( *(this->GetInputPath()) ); diff --git a/Code/FeatureExtraction/otbImageFittingPolygonListFilter.h b/Code/FeatureExtraction/otbImageFittingPolygonListFilter.h index 9dc20463576bfc7b0e051ccc9efb31f777d4618a..86345016aa91081e2ab426f7bbdf15e65576d6ec 100644 --- a/Code/FeatureExtraction/otbImageFittingPolygonListFilter.h +++ b/Code/FeatureExtraction/otbImageFittingPolygonListFilter.h @@ -33,9 +33,9 @@ namespace otb */ template <class TPath, class TImage> class ITK_EXPORT ImageFittingPolygonListFilter - : public PathListToPathListFilter<TPath> + : public PathListToPathListFilter<TPath> { - public: +public: /** Standard typedefs */ typedef ImageFittingPolygonListFilter Self; typedef PathListToPathListFilter<TPath> Superclass; diff --git a/Code/FeatureExtraction/otbImageFittingPolygonListFilter.txx b/Code/FeatureExtraction/otbImageFittingPolygonListFilter.txx index 61fbc7faf0adee02cc386d954680d28e7b161806..f68014fd66db8a1b38bbea336f02faf8e947a5bc 100644 --- a/Code/FeatureExtraction/otbImageFittingPolygonListFilter.txx +++ b/Code/FeatureExtraction/otbImageFittingPolygonListFilter.txx @@ -52,10 +52,10 @@ const typename ImageFittingPolygonListFilter<TPath, TImage> ImageFittingPolygonListFilter<TPath, TImage> ::GetInputImage(void) { - if(this->GetNumberOfInputs()<1) - { - return 0; - } + if (this->GetNumberOfInputs()<1) + { + return 0; + } return static_cast<const ImageType *>(this->itk::ProcessObject::GetInput(1)); } @@ -86,130 +86,130 @@ ImageFittingPolygonListFilter<TPath, TImage> typename ImageType::IndexType start; //go through all the polygons in the list - for(IteratorType it = inputPtr->Begin(); it != inputPtr->End(); ++it) + for (IteratorType it = inputPtr->Begin(); it != inputPtr->End(); ++it) { PathPointerType polygon = it.Get(); - if(polygon->GetVertexList()->Size()>2) + if (polygon->GetVertexList()->Size()>2) { for (unsigned int iteration=0;iteration < m_NumberOfIterations;++iteration) { PathPointerType newPolygon = PathType::New(); - VertexListConstIteratorType vertexIt = polygon->GetVertexList()->Begin(); - //We are now going to go through all the vertex, we won't start to process - // first as we need to know the last one for that. - VertexType firstPoint = vertexIt.Value(); - VertexType previousPoint = vertexIt.Value(); - ++vertexIt; - VertexType currentPoint = vertexIt.Value(); - ++vertexIt; - while (vertexIt != polygon->GetVertexList()->End()) - { - VertexType nextPoint=vertexIt.Value(); - - /** try all the possible neighbor for the current point - * to factorize - * */ + VertexListConstIteratorType vertexIt = polygon->GetVertexList()->Begin(); + //We are now going to go through all the vertex, we won't start to process + // first as we need to know the last one for that. + VertexType firstPoint = vertexIt.Value(); + VertexType previousPoint = vertexIt.Value(); + ++vertexIt; + VertexType currentPoint = vertexIt.Value(); + ++vertexIt; + while (vertexIt != polygon->GetVertexList()->End()) { + VertexType nextPoint=vertexIt.Value(); - start[0] = static_cast<long int>(currentPoint[0]-m_Radius); - start[1] = static_cast<long int>(currentPoint[1]-m_Radius); - region.SetIndex(start); - - NeighborhoodIteratorType nIt(inputImagePtr, region); - double maxValue=0.0; - VertexType maxPoint = currentPoint; - for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) - { - if(regionLargest.IsInside(nIt.GetIndex())) + /** try all the possible neighbor for the current point + * to factorize + * */ { - VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); - double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); - if (currentValue > maxValue) + + start[0] = static_cast<long int>(currentPoint[0]-m_Radius); + start[1] = static_cast<long int>(currentPoint[1]-m_Radius); + region.SetIndex(start); + + NeighborhoodIteratorType nIt(inputImagePtr, region); + double maxValue=0.0; + VertexType maxPoint = currentPoint; + for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) { - maxValue=currentValue; - maxPoint=middlePoint; + if (regionLargest.IsInside(nIt.GetIndex())) + { + VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); + double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); + if (currentValue > maxValue) + { + maxValue=currentValue; + maxPoint=middlePoint; + } + } } + currentPoint=maxPoint; + newPolygon->AddVertex(maxPoint); } - } - currentPoint=maxPoint; - newPolygon->AddVertex(maxPoint); - } - /** End 'to factorize' */ + /** End 'to factorize' */ - ++vertexIt; - previousPoint=currentPoint; - currentPoint=nextPoint; + ++vertexIt; + previousPoint=currentPoint; + currentPoint=nextPoint; - } - //We now need to process the last and the first point + } + //We now need to process the last and the first point - VertexType nextPoint = firstPoint; - /** try all the possible neighbor for the current point - * to factorize - * */ - { - start[0] = static_cast<long int>(currentPoint[0]-m_Radius); - start[1] = static_cast<long int>(currentPoint[1]-m_Radius); - region.SetIndex(start); - - NeighborhoodIteratorType nIt(inputImagePtr, region); - double maxValue=0.0; - VertexType maxPoint = currentPoint; - for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) - { - if(regionLargest.IsInside(nIt.GetIndex())) + VertexType nextPoint = firstPoint; + /** try all the possible neighbor for the current point + * to factorize + * */ { - VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); - double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); - if (currentValue > maxValue) + start[0] = static_cast<long int>(currentPoint[0]-m_Radius); + start[1] = static_cast<long int>(currentPoint[1]-m_Radius); + region.SetIndex(start); + + NeighborhoodIteratorType nIt(inputImagePtr, region); + double maxValue=0.0; + VertexType maxPoint = currentPoint; + for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) { - maxValue=currentValue; - maxPoint=middlePoint; + if (regionLargest.IsInside(nIt.GetIndex())) + { + VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); + double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); + if (currentValue > maxValue) + { + maxValue=currentValue; + maxPoint=middlePoint; + } + } } + currentPoint=maxPoint; + newPolygon->AddVertex(maxPoint); } - } - currentPoint=maxPoint; - newPolygon->AddVertex(maxPoint); - } - /** End 'to factorize' */ + /** End 'to factorize' */ - previousPoint = currentPoint; - currentPoint= firstPoint; - vertexIt = newPolygon->GetVertexList()->Begin(); - nextPoint=vertexIt.Value(); + previousPoint = currentPoint; + currentPoint= firstPoint; + vertexIt = newPolygon->GetVertexList()->Begin(); + nextPoint=vertexIt.Value(); - /** try all the possible neighbor for the current point - * to factorize - * */ - { + /** try all the possible neighbor for the current point + * to factorize + * */ + { - start[0] = static_cast<long int>(currentPoint[0]-m_Radius); - start[1] = static_cast<long int>(currentPoint[1]-m_Radius); - region.SetIndex(start); + start[0] = static_cast<long int>(currentPoint[0]-m_Radius); + start[1] = static_cast<long int>(currentPoint[1]-m_Radius); + region.SetIndex(start); - NeighborhoodIteratorType nIt(inputImagePtr, region); - double maxValue=0.0; - VertexType maxPoint = currentPoint; - for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) - { - if(regionLargest.IsInside(nIt.GetIndex())) - { - VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); - double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); - if (currentValue > maxValue) + NeighborhoodIteratorType nIt(inputImagePtr, region); + double maxValue=0.0; + VertexType maxPoint = currentPoint; + for (nIt.GoToBegin();!nIt.IsAtEnd();++nIt) { - maxValue=currentValue; - maxPoint=middlePoint; + if (regionLargest.IsInside(nIt.GetIndex())) + { + VertexType middlePoint=static_cast<VertexType>(nIt.GetIndex()); + double currentValue = computeValue(inputImagePtr, middlePoint, previousPoint, nextPoint); + if (currentValue > maxValue) + { + maxValue=currentValue; + maxPoint=middlePoint; + } + } } + currentPoint=maxPoint; + newPolygon->AddVertex(maxPoint); } - } - currentPoint=maxPoint; - newPolygon->AddVertex(maxPoint); - } - /** End 'to factorize' */ + /** End 'to factorize' */ - polygon = newPolygon;//prepare the next iteration + polygon = newPolygon;//prepare the next iteration } } @@ -221,9 +221,9 @@ ImageFittingPolygonListFilter<TPath, TImage> } template <class TPath, class TImage> - double - ImageFittingPolygonListFilter<TPath, TImage> - ::computeValue(ImageConstPointerType image, VertexType middlePoint, VertexType previousPoint, VertexType nextPoint) const +double +ImageFittingPolygonListFilter<TPath, TImage> +::computeValue(ImageConstPointerType image, VertexType middlePoint, VertexType previousPoint, VertexType nextPoint) const { typedef typename ImageType::IndexType IndexType; IndexType middleIndex; diff --git a/Code/FeatureExtraction/otbImageToCarvingPathFilter.h b/Code/FeatureExtraction/otbImageToCarvingPathFilter.h index 440e3362a003f27b43907bcf977f8a8eb120d3f0..72aedc79b20f7f226dc4c1ccd6018fb20d4ba91a 100644 --- a/Code/FeatureExtraction/otbImageToCarvingPathFilter.h +++ b/Code/FeatureExtraction/otbImageToCarvingPathFilter.h @@ -21,7 +21,8 @@ #include "otbImageToPathFilter.h" #include "itkImageSliceConstIteratorWithIndex.h" -namespace otb { +namespace otb +{ /** * \class ImageToCarvingPathFilter * \brief This filter find the minimum energy path of an image. @@ -53,7 +54,7 @@ namespace otb { template <class TInputImage, class TOutputPath> class ITK_EXPORT ImageToCarvingPathFilter - : public ImageToPathFilter<TInputImage, TOutputPath> + : public ImageToPathFilter<TInputImage, TOutputPath> { public: /** standards typedefs */ @@ -90,7 +91,7 @@ public: protected: ImageToCarvingPathFilter(); - virtual ~ImageToCarvingPathFilter(){}; + virtual ~ImageToCarvingPathFilter() {}; virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void GenerateOutputInformation() {}; //does nothing virtual void GenerateData(); diff --git a/Code/FeatureExtraction/otbImageToCarvingPathFilter.txx b/Code/FeatureExtraction/otbImageToCarvingPathFilter.txx index fca798e8ec65846c6b1828a026bfb159ccc5a98d..22d6f7e68ceda68d05bfc9b279a2846f87b160ac 100644 --- a/Code/FeatureExtraction/otbImageToCarvingPathFilter.txx +++ b/Code/FeatureExtraction/otbImageToCarvingPathFilter.txx @@ -36,8 +36,8 @@ ImageToCarvingPathFilter<TInputImage, TOutputPath> ::ImageToCarvingPathFilter() { m_ForegroundValue = PixelType(255); - m_Direction = 0; - m_EnergyPerPix = 0.0; + m_Direction = 0; + m_EnergyPerPix = 0.0; } /** * Main computation method. @@ -52,12 +52,12 @@ ImageToCarvingPathFilter<TInputImage, TOutputPath> OutputPathType * outputPath = this->GetOutput(); typedef itk::ImageSliceConstIteratorWithIndex - <InputImageType> IteratorType; + <InputImageType> IteratorType; typedef itk::NeighborhoodIterator< InputImageType > - NeighborhoodIteratorType; + NeighborhoodIteratorType; IteratorType it(inputImage, - inputImage->GetLargestPossibleRegion()); + inputImage->GetLargestPossibleRegion()); it.GoToBegin(); PixelType maxValue = itk::NumericTraits< PixelType >::max(); @@ -81,14 +81,14 @@ ImageToCarvingPathFilter<TInputImage, TOutputPath> typename IteratorType::OffsetType NEXT; - const typename IteratorType::OffsetType LEFT ={{-1,0}}; - const typename IteratorType::OffsetType RIGHT ={{1,0}}; - const typename IteratorType::OffsetType UP ={{0,-1}}; - const typename IteratorType::OffsetType DOWN ={{0,1}}; - const typename IteratorType::OffsetType LEFTUP ={{-1,-1}}; + const typename IteratorType::OffsetType LEFT ={{-1,0}}; + const typename IteratorType::OffsetType RIGHT ={{1,0}}; + const typename IteratorType::OffsetType UP ={{0,-1}}; + const typename IteratorType::OffsetType DOWN ={{0,1}}; + const typename IteratorType::OffsetType LEFTUP ={{-1,-1}}; // const typename IteratorType::OffsetType RIGHTDOWN ={{1,1}}; - const typename IteratorType::OffsetType RIGHTUP ={{1,-1}}; - const typename IteratorType::OffsetType LEFTDOWN ={{-1,1}}; + const typename IteratorType::OffsetType RIGHTUP ={{1,-1}}; + const typename IteratorType::OffsetType LEFTDOWN ={{-1,1}}; // const typename IteratorType::OffsetType CENTER ={{0,0}}; if (m_Direction == 0) @@ -114,12 +114,13 @@ ImageToCarvingPathFilter<TInputImage, TOutputPath> * with cumulative energy (dynamic programming first step) */ it.SetFirstDirection( dir0 ); it.SetSecondDirection( dir1 ); - it.GoToBegin(); neighIt.GoToBegin(); + it.GoToBegin(); + neighIt.GoToBegin(); while (!it.IsAtEnd()) { while (!it.IsAtEndOfSlice()) { - while(!it.IsAtEndOfLine()) + while (!it.IsAtEndOfLine()) { neighIt.SetLocation(it.GetIndex());//TODO bad for performances... find a better option // this is really about 20% of total processing time !!! @@ -171,24 +172,24 @@ ImageToCarvingPathFilter<TInputImage, TOutputPath> - /** Follow the minima bottom-up or right-left - * (dynamic programming second step) */ + /** Follow the minima bottom-up or right-left + * (dynamic programming second step) */ //find the starting point to follow on the last line typedef itk::ImageLinearConstIteratorWithIndex< InputImageType > - LinearIteratorType; + LinearIteratorType; LinearIteratorType LinIt(energyImage, - energyImage->GetLargestPossibleRegion()); + energyImage->GetLargestPossibleRegion()); LinIt.SetDirection(dir0); LinIt.GoToReverseBegin(); typedef typename InputImageType::IndexType IndexType; PixelType min = maxValue; IndexType indexToAdd; - while(!LinIt.IsAtReverseEndOfLine()) + while (!LinIt.IsAtReverseEndOfLine()) { - if(LinIt.Get()<min) + if (LinIt.Get()<min) { min=LinIt.Get(); indexToAdd=LinIt.GetIndex(); diff --git a/Code/FeatureExtraction/otbImageToEdgePathFilter.h b/Code/FeatureExtraction/otbImageToEdgePathFilter.h index 35d74fab9c6e4d8e0c4b2e99d8ce6079005fd703..e0c830bd915ba0b9d61aea979ab194d0f92c8515 100644 --- a/Code/FeatureExtraction/otbImageToEdgePathFilter.h +++ b/Code/FeatureExtraction/otbImageToEdgePathFilter.h @@ -20,7 +20,8 @@ #include "otbImageToPathFilter.h" -namespace otb { +namespace otb +{ /** * \class ImageToEdgePathFilter * \brief This filter compute the closed edge path of a labelled object @@ -51,7 +52,7 @@ namespace otb { template <class TInputImage, class TOutputPath> class ITK_EXPORT ImageToEdgePathFilter - : public ImageToPathFilter<TInputImage, TOutputPath> + : public ImageToPathFilter<TInputImage, TOutputPath> { public: /** standards typedefs */ @@ -80,7 +81,7 @@ public: protected: ImageToEdgePathFilter(); - virtual ~ImageToEdgePathFilter(){}; + virtual ~ImageToEdgePathFilter() {}; virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void GenerateOutputInformation() {}; //does nothing virtual void GenerateData(); diff --git a/Code/FeatureExtraction/otbImageToEdgePathFilter.txx b/Code/FeatureExtraction/otbImageToEdgePathFilter.txx index 746395b4381c6ee79dc202ce559816c7a45ce286..557a8fa03e49f0f3f4d57ea396cb23f13e7ee692 100644 --- a/Code/FeatureExtraction/otbImageToEdgePathFilter.txx +++ b/Code/FeatureExtraction/otbImageToEdgePathFilter.txx @@ -50,7 +50,7 @@ ImageToEdgePathFilter<TInputImage, TOutputPath> otbMsgDebugMacro(<<"Foreground value : "<<m_ForegroundValue); PixelType initPadConstant(0); - if( initPadConstant == m_ForegroundValue ) + if ( initPadConstant == m_ForegroundValue ) { initPadConstant = 1; } @@ -71,19 +71,19 @@ ImageToEdgePathFilter<TInputImage, TOutputPath> LinearIteratorType linIter(pad->GetOutput(),pad->GetOutput()->GetLargestPossibleRegion()); linIter.GoToBegin(); bool flag = true; - while(flag && !linIter.IsAtEnd()) + while (flag && !linIter.IsAtEnd()) + { + if (linIter.Get() == m_ForegroundValue ) { - if(linIter.Get() == m_ForegroundValue ) - { flag=false; - } - else - { + } + else + { ++linIter; - } } + } typename InputImageType::IndexType start = linIter.GetIndex(); - // outputPath->AddVertex(start); +// outputPath->AddVertex(start); // Neighborhood definition typename IteratorType::RadiusType radius; @@ -123,13 +123,13 @@ ImageToEdgePathFilter<TInputImage, TOutputPath> ContinuousIndexType newVertex = it.GetIndex(CENTER); - if(it.GetPixel(RIGHT)==m_ForegroundValue) + if (it.GetPixel(RIGHT)==m_ForegroundValue) newVertex[0]-=0.5; - if(it.GetPixel(LEFT)==m_ForegroundValue) + if (it.GetPixel(LEFT)==m_ForegroundValue) newVertex[0]+=0.5; - if(it.GetPixel(UP)==m_ForegroundValue) + if (it.GetPixel(UP)==m_ForegroundValue) newVertex[1]+=0.5; - if(it.GetPixel(DOWN)==m_ForegroundValue) + if (it.GetPixel(DOWN)==m_ForegroundValue) newVertex[1]-=0.5; outputPath->AddVertex(newVertex); @@ -141,8 +141,8 @@ ImageToEdgePathFilter<TInputImage, TOutputPath> // nexstart gives a clue of where to begin searching in next step of the search int nextStart=0; // While the search has not eended - while(flag) - { + while (flag) + { // move is used to walk the neighnorhood clock-wise int move = nextStart; // edgeFound indicate that the edge has been found. @@ -150,66 +150,66 @@ ImageToEdgePathFilter<TInputImage, TOutputPath> // LastWasPositive indicate wether the previous pixel belong to the object or not bool LastWasPositive(false); // While unexplored pixels remain and no edge was found - while((move<nextStart+8)&&(!EdgeFound)) - { + while ((move<nextStart+8)&&(!EdgeFound)) + { //otbMsgDevMacro(<<"SEARCH: "<<move%8<<" "<<it.GetPixel(rotation[move%8])<<" LAST: "<<LastWasPositive); // If last pixel was not in the object and the current is, we have found the edge - if((!LastWasPositive) && (it.GetPixel(rotation[move%8]) == m_ForegroundValue) ) - { - EdgeFound=true; - } + if ((!LastWasPositive) && (it.GetPixel(rotation[move%8]) == m_ForegroundValue) ) + { + EdgeFound=true; + } else - { - // Else goes on - LastWasPositive=(it.GetPixel(rotation[move%8]) == m_ForegroundValue); - move++; - } + { + // Else goes on + LastWasPositive=(it.GetPixel(rotation[move%8]) == m_ForegroundValue); + move++; } + } // Once the search has been completed, if an edge pixel was found - if(EdgeFound) - { + if (EdgeFound) + { // Update the output path it+=rotation[move%8]; nextStart=(move+5)%8; newVertex = it.GetIndex(CENTER); - if(it.GetPixel(RIGHT)==m_ForegroundValue) - newVertex[0]-=0.5; - if(it.GetPixel(LEFT)==m_ForegroundValue) - newVertex[0]+=0.5; - if(it.GetPixel(UP)==m_ForegroundValue) - newVertex[1]+=0.5; - if(it.GetPixel(DOWN)==m_ForegroundValue) - newVertex[1]-=0.5; + if (it.GetPixel(RIGHT)==m_ForegroundValue) + newVertex[0]-=0.5; + if (it.GetPixel(LEFT)==m_ForegroundValue) + newVertex[0]+=0.5; + if (it.GetPixel(UP)==m_ForegroundValue) + newVertex[1]+=0.5; + if (it.GetPixel(DOWN)==m_ForegroundValue) + newVertex[1]-=0.5; outputPath->AddVertex(newVertex); otbMsgDebugMacro(<<newVertex); // If we came back to our start point after a sufficient number of moves - if((it.GetIndex(CENTER)==start)&&(nbMove>=2)) - { - // search end + if ((it.GetIndex(CENTER)==start)&&(nbMove>=2)) + { + // search end flag=false; - } + } else - { - // else - for(int i=0;i<8;i++) - { - // If we came back near our starting pointer after a sufficient number of moves - if((it.GetIndex(rotation[i])==start)&&(nbMove>=2)) { - // search end + // else + for (int i=0;i<8;i++) + { + // If we came back near our starting pointer after a sufficient number of moves + if ((it.GetIndex(rotation[i])==start)&&(nbMove>=2)) + { + // search end flag=false; + } + } } } - } - } - // else - else - { + // else + else + { // search ended, no pixel can be added to the edge path. flag=false; - } - nbMove++; } + nbMove++; + } } template <class TInputImage, class TOutputPath> void diff --git a/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.h b/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.h index 2773708889159c7af1fc2e1502fdfbd95c3f041d..cf5261f6066beb578752e2d93d522c4a5e3c7bc1 100644 --- a/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.h +++ b/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.h @@ -32,125 +32,125 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace Functor - { - /** \class HessianDeterminant - * \brief This functor computes the determinant of symmetric 2*2 matrix . - * - * A Hessian matrix is symmetric, we compute only the 3 first parameters - * The First component is : Dxx - * The Second component is : Dyy - * The Third component is : Dxy - */ - template <class TInput, class TOutput> - class HessianDeterminant - { - public: - HessianDeterminant(){}; - ~HessianDeterminant(){}; - - /* - * - * \param input : A symetric Hessian Matrix - * \return Determinant of the Hessian Matrix - */ - inline TOutput operator()(const TInput& input) - { - return static_cast<TOutput>(input[0]*input[1] - input[2]*input[2]); - } - - - bool operator !=(const HessianDeterminant) const - { - return false; - } - - bool operator==(const HessianDeterminant & other) const - { - return !(*this != other); - } - }; - } - /** \class ImageToHessianDeterminantImageFilter - * \brief This class compute the Hessian determinant of each pixel of an input image - * - * For an input image, the Hessian matrix of each pixel is computed an then the determinant - * of each pixel's matrix is computed. +namespace Functor +{ +/** \class HessianDeterminant + * \brief This functor computes the determinant of symmetric 2*2 matrix . + * + * A Hessian matrix is symmetric, we compute only the 3 first parameters + * The First component is : Dxx + * The Second component is : Dyy + * The Third component is : Dxy + */ +template <class TInput, class TOutput> +class HessianDeterminant +{ +public: + HessianDeterminant() {}; + ~HessianDeterminant() {}; + + /* * - * \sa itk::HessianRecursiveGaussianImageFilter + * \param input : A symetric Hessian Matrix + * \return Determinant of the Hessian Matrix */ - template <class TInputImage, class TOutputImage, class TPrecision = double> - class ITK_EXPORT ImageToHessianDeterminantImageFilter - : public itk::ImageToImageFilter< TInputImage, TOutputImage > - { - - public: - - /** Standard class typedefs. */ - typedef ImageToHessianDeterminantImageFilter Self; - typedef itk::ImageToImageFilter<TInputImage, TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Set/Get the number of iterations */ - itkSetMacro(Sigma,double); - itkGetMacro(Sigma,double); - - /** Run-time type information (and related methods). */ - itkTypeMacro(ImageToHessianDeterminantImageFilter,ImageToImageFilter); - - /* Initialisation of Input & Output Images*/ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::PixelType OutputPixelType; - - - typedef itk::FixedArray<TPrecision,3> VectorType; - typedef otb::Image<VectorType,2> VectorImageType; - typedef typename VectorImageType::Pointer VectorImagePointerType; - - /** Internal filters typedefs */ - typedef itk::HessianRecursiveGaussianImageFilter - <InputImageType,VectorImageType> ImageToHessianImageFilterType; - typedef typename ImageToHessianImageFilterType::Pointer ImageToHessianImageFilterPointerType; - typedef Functor::HessianDeterminant<VectorType,OutputPixelType> DeterminantFunctorType; - typedef itk::UnaryFunctorImageFilter<VectorImageType,OutputImageType,DeterminantFunctorType> DeterminantFilterType; - typedef typename DeterminantFilterType::Pointer DeterminantFilterPointerType; - - - protected: - /** - * Constructor. - */ - ImageToHessianDeterminantImageFilter(); - /** - * Destructor. - */ - virtual ~ImageToHessianDeterminantImageFilter(); - /** - * Standard PrintSelf method. - */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Main computation method. - */ - virtual void GenerateData(); - - private: - - /** Hessian filter */ - ImageToHessianImageFilterPointerType m_HessianFilter; - /** Hessian Determinant Computation filter */ - DeterminantFilterPointerType m_DeterminantFilter; - - /** Width of the Gaussian used in the HessianRecursiveGaussianImageFilter */ - double m_Sigma; - }; + inline TOutput operator()(const TInput& input) + { + return static_cast<TOutput>(input[0]*input[1] - input[2]*input[2]); + } + + + bool operator !=(const HessianDeterminant) const + { + return false; + } + + bool operator==(const HessianDeterminant & other) const + { + return !(*this != other); + } +}; +} +/** \class ImageToHessianDeterminantImageFilter + * \brief This class compute the Hessian determinant of each pixel of an input image + * + * For an input image, the Hessian matrix of each pixel is computed an then the determinant + * of each pixel's matrix is computed. + * + * \sa itk::HessianRecursiveGaussianImageFilter + */ +template <class TInputImage, class TOutputImage, class TPrecision = double> +class ITK_EXPORT ImageToHessianDeterminantImageFilter + : public itk::ImageToImageFilter< TInputImage, TOutputImage > +{ + +public: + + /** Standard class typedefs. */ + typedef ImageToHessianDeterminantImageFilter Self; + typedef itk::ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Set/Get the number of iterations */ + itkSetMacro(Sigma,double); + itkGetMacro(Sigma,double); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageToHessianDeterminantImageFilter,ImageToImageFilter); + + /* Initialisation of Input & Output Images*/ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::PixelType OutputPixelType; + + + typedef itk::FixedArray<TPrecision,3> VectorType; + typedef otb::Image<VectorType,2> VectorImageType; + typedef typename VectorImageType::Pointer VectorImagePointerType; + + /** Internal filters typedefs */ + typedef itk::HessianRecursiveGaussianImageFilter + <InputImageType,VectorImageType> ImageToHessianImageFilterType; + typedef typename ImageToHessianImageFilterType::Pointer ImageToHessianImageFilterPointerType; + typedef Functor::HessianDeterminant<VectorType,OutputPixelType> DeterminantFunctorType; + typedef itk::UnaryFunctorImageFilter<VectorImageType,OutputImageType,DeterminantFunctorType> DeterminantFilterType; + typedef typename DeterminantFilterType::Pointer DeterminantFilterPointerType; + + +protected: + /** + * Constructor. + */ + ImageToHessianDeterminantImageFilter(); + /** + * Destructor. + */ + virtual ~ImageToHessianDeterminantImageFilter(); + /** + * Standard PrintSelf method. + */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Main computation method. + */ + virtual void GenerateData(); + +private: + + /** Hessian filter */ + ImageToHessianImageFilterPointerType m_HessianFilter; + /** Hessian Determinant Computation filter */ + DeterminantFilterPointerType m_DeterminantFilter; + + /** Width of the Gaussian used in the HessianRecursiveGaussianImageFilter */ + double m_Sigma; +}; } #ifndef OTB_MANUAL_INSTANTIATION #include "otbImageToHessianDeterminantImageFilter.txx" diff --git a/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.txx b/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.txx index 79b1ce3bdb94b3644ef31b9728bf453fe3ef97b7..8448118c322575f6740f2a45a7d98f35435e4bc1 100644 --- a/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.txx +++ b/Code/FeatureExtraction/otbImageToHessianDeterminantImageFilter.txx @@ -25,49 +25,49 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputImage, class TOutputImage, class TPrecision> - ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> - ::ImageToHessianDeterminantImageFilter() - { - // Filter intialisation - m_HessianFilter = ImageToHessianImageFilterType::New(); - m_DeterminantFilter = DeterminantFilterType::New(); - - // pipeline wiring - m_DeterminantFilter->SetInput(m_HessianFilter->GetOutput()); - - // default parameter value - m_Sigma = 1.0; - } - - template <class TInputImage, class TOutputImage, class TPrecision> - ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> - ::~ImageToHessianDeterminantImageFilter() - {} - - - template <class TInputImage, class TOutputImage, class TPrecision> - void - ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> - ::GenerateData(void) - { - // Execute minipipeline - m_HessianFilter->SetInput(this->GetInput()); - m_HessianFilter->SetSigma(m_Sigma); - m_DeterminantFilter->GraftOutput(this->GetOutput()); - m_DeterminantFilter->Update(); - this->GraftOutput(m_DeterminantFilter->GetOutput()); - } - - /*PrintSelf*/ - template <class TInputImage, class TOutputImage, class TPrecision > - void - ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent <<"Sigma: " << m_Sigma << std::endl; - } +template <class TInputImage, class TOutputImage, class TPrecision> +ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> +::ImageToHessianDeterminantImageFilter() +{ + // Filter intialisation + m_HessianFilter = ImageToHessianImageFilterType::New(); + m_DeterminantFilter = DeterminantFilterType::New(); + + // pipeline wiring + m_DeterminantFilter->SetInput(m_HessianFilter->GetOutput()); + + // default parameter value + m_Sigma = 1.0; +} + +template <class TInputImage, class TOutputImage, class TPrecision> +ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> +::~ImageToHessianDeterminantImageFilter() +{} + + +template <class TInputImage, class TOutputImage, class TPrecision> +void +ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> +::GenerateData(void) +{ + // Execute minipipeline + m_HessianFilter->SetInput(this->GetInput()); + m_HessianFilter->SetSigma(m_Sigma); + m_DeterminantFilter->GraftOutput(this->GetOutput()); + m_DeterminantFilter->Update(); + this->GraftOutput(m_DeterminantFilter->GetOutput()); +} + +/*PrintSelf*/ +template <class TInputImage, class TOutputImage, class TPrecision > +void +ImageToHessianDeterminantImageFilter<TInputImage,TOutputImage,TPrecision> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent <<"Sigma: " << m_Sigma << std::endl; +} } #endif diff --git a/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.h b/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.h index a9ea29e8d174a0768b5f783d2db8e131fb88dafb..82c165a43dde75050a898691c6cc5ed31ff988a1 100644 --- a/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.h +++ b/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.h @@ -35,17 +35,17 @@ namespace otb * */ template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage > +class TOutputImage, +class TOutputImageDirection = TOutputImage > class ITK_EXPORT ImageToModulusAndDirectionImageFilter : public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ diff --git a/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.txx b/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.txx index 6f234ba865cfad9f207a782c7c1c1ba2fb898ab7..e101f47153f11856404a97fe9dc82db00630936d 100644 --- a/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.txx +++ b/Code/FeatureExtraction/otbImageToModulusAndDirectionImageFilter.txx @@ -48,11 +48,11 @@ ImageToModulusAndDirectionImageFilter<TInputImage, TOutputImage, TOutputImageDir GetOutput() const { if (this->GetNumberOfOutputs() < 1) - { - return 0; - } + { + return 0; + } return static_cast<const OutputImageType * > - (this->itk::ProcessObject::GetOutput(0) ); + (this->itk::ProcessObject::GetOutput(0) ); } /** Return the output image modulus */ template <class TInputImage, class TOutputImage, class TOutputImageDirection > @@ -61,11 +61,11 @@ ImageToModulusAndDirectionImageFilter<TInputImage, TOutputImage, TOutputImageDir GetOutput() { if (this->GetNumberOfOutputs() < 1) - { - return 0; - } + { + return 0; + } return static_cast<OutputImageType * > - (this->itk::ProcessObject::GetOutput(0) ); + (this->itk::ProcessObject::GetOutput(0) ); } /** Return the const output image direction */ @@ -75,11 +75,11 @@ ImageToModulusAndDirectionImageFilter<TInputImage, TOutputImage, TOutputImageDir GetOutputDirection()const { if (this->GetNumberOfOutputs() < 2) - { - return 0; - } + { + return 0; + } return static_cast<const OutputImageDirectionType * > - (this->itk::ProcessObject::GetOutput(1) ); + (this->itk::ProcessObject::GetOutput(1) ); } /** Return the output image direction */ @@ -89,11 +89,11 @@ ImageToModulusAndDirectionImageFilter<TInputImage, TOutputImage, TOutputImageDir GetOutputDirection() { if (this->GetNumberOfOutputs() < 2) - { - return 0; - } + { + return 0; + } return static_cast<OutputImageDirectionType * > - (this->itk::ProcessObject::GetOutput(1) ); + (this->itk::ProcessObject::GetOutput(1) ); } /** diff --git a/Code/FeatureExtraction/otbImageToPathListAlignFilter.h b/Code/FeatureExtraction/otbImageToPathListAlignFilter.h index 5cf31ebcd1db5c392ba64e801804d0fcabd860b1..5d881755d4c6f553b7eba952022bca71d9ea6d92 100644 --- a/Code/FeatureExtraction/otbImageToPathListAlignFilter.h +++ b/Code/FeatureExtraction/otbImageToPathListAlignFilter.h @@ -121,7 +121,7 @@ protected: ImageToPathListAlignFilter(); ~ImageToPathListAlignFilter(); - virtual void GenerateOutputInformation(){}; // do nothing + virtual void GenerateOutputInformation() {}; // do nothing virtual void GenerateData(); virtual std::vector<double> tab(int n,double p,double m); virtual void AngleCalculate( const InputImageType* InputImageIn); diff --git a/Code/FeatureExtraction/otbImageToPathListAlignFilter.txx b/Code/FeatureExtraction/otbImageToPathListAlignFilter.txx index d51cd5dcefe7712a00a63c1981fa3c97ae10ad1f..71ceea50c08ead9ceec038ea483fb38d7bb5865a 100644 --- a/Code/FeatureExtraction/otbImageToPathListAlignFilter.txx +++ b/Code/FeatureExtraction/otbImageToPathListAlignFilter.txx @@ -53,11 +53,11 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> m_Eps=0.0; for (unsigned int i = 0; i < InputImageDimension; i++) - { + { // Set an image spacing for the user m_Spacing[i] = 1.0; m_Origin[i] = 0; - } + } m_PathValue = itk::NumericTraits<ValueType>::One; m_BackgroundValue = itk::NumericTraits<ValueType>::Zero; @@ -79,20 +79,20 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> { unsigned int i; for (i=0; i<InputImageDimension; i++) - { + { if ( spacing[i] != m_Spacing[i] ) - { + { break; - } } + } if ( i < InputImageDimension ) - { + { for (i=0; i<InputImageDimension; i++) - { + { m_Spacing[i] = spacing[i]; - } - this->Modified(); } + this->Modified(); + } } template <class TInputImage, class TOutputPath> @@ -102,20 +102,20 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> { unsigned int i; for (i=0; i<InputImageDimension; i++) - { + { if ( (double)spacing[i] != m_Spacing[i] ) - { + { break; - } } + } if ( i < InputImageDimension ) - { + { for (i=0; i<InputImageDimension; i++) - { + { m_Spacing[i] = spacing[i]; - } - this->Modified(); } + this->Modified(); + } } template <class TInputImage, class TOutputPath> @@ -134,19 +134,19 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> { unsigned int i; for (i=0; i<InputImageDimension; i++) - { + { if ( origin[i] != m_Origin[i] ) - { + { break; - } } + } if ( i < InputImageDimension ) - { + { for (i=0; i<InputImageDimension; i++) - { + { m_Origin[i] = origin[i]; - } } + } } template <class TInputImage, class TOutputPath> @@ -156,19 +156,19 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> { unsigned int i; for (i=0; i<InputImageDimension; i++) - { + { if ( (double)origin[i] != m_Origin[i] ) - { + { break; - } } + } if ( i < InputImageDimension ) - { + { for (i=0; i<InputImageDimension; i++) - { + { m_Origin[i] = origin[i]; - } } + } } template <class TInputImage, class TOutputPath> @@ -197,7 +197,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> /*** compute proba (=x among y) ***/ out[0] = 1.0; - for (y=1,adr2=0;y<=n;y++) { + for (y=1,adr2=0;y<=n;y++) + { adr1 = adr2; adr2 += n+1; out[adr2] = q*out[adr1]; @@ -249,17 +250,19 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> typename InputImageType::IndexType idx; - for (x=0;x<p;x++){ - idx[0] = (n-1); - idx[1] = x; + for (x=0;x<p;x++) + { + idx[0] = (n-1); + idx[1] = x; // indice = (n-1)*p +x - m_AngleImage->SetPixel(idx,static_cast<RealType>(-1000.0)); + m_AngleImage->SetPixel(idx,static_cast<RealType>(-1000.0)); } - for (y=0;y<n;y++){ - idx[0] = y; - idx[1] = p-1; + for (y=0;y<n;y++) + { + idx[0] = y; + idx[1] = p-1; // indice = p*y+p-1 - m_AngleImage->SetPixel(idx,static_cast<RealType>(-1000.0)); + m_AngleImage->SetPixel(idx,static_cast<RealType>(-1000.0)); } typename InputImageType::IndexType adr; @@ -267,7 +270,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> RealType com1,com2,gx,gy,norm; for (x=0;x<p-1;x++) - for (y=0;y<n-1;y++) { + for (y=0;y<n-1;y++) + { // indice = y*p+x adr[0] = y; adr[1] = x; @@ -302,8 +306,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> norm = gx*gx + gy*gy; if (norm <=threshold) - m_AngleImage->SetPixel(adr,static_cast<RealType>(-1000.0)); - else m_AngleImage->SetPixel(adr,static_cast<RealType>(vcl_atan2(gx,-gy))); + m_AngleImage->SetPixel(adr,static_cast<RealType>(-1000.0)); + else m_AngleImage->SetPixel(adr,static_cast<RealType>(vcl_atan2(gx,-gy))); } } @@ -339,7 +343,7 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> OutputPathListType * OutputPath = this->GetOutput(); // Generate the image -/* Filter algorithm */ + /* Filter algorithm */ Taille = InputImage->GetLargestPossibleRegion().GetSize(); nx = Taille[0]; @@ -359,12 +363,12 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> /*** compute P(k,l) ***/ test = tab(n,1.0/(double)(m_NbGradDirection),(double)(nx*ny)*(double)(nx*ny)); - /*** initialization ***/ + /*** initialization ***/ prec = M_PI/(double)(m_NbGradDirection); ntheta = m_NbLineDirection/2; /* i.e. # directions of NON-ORIENTED lines */ dtheta = M_PI/(double)ntheta; -/******************** memory allocation ********************/ + /******************** memory allocation ********************/ max_nblocs = n/2+1; /* maximal number of blocs */ count.resize(max_nblocs); @@ -384,7 +388,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> /******************** first loop : the four sides ********************/ - for (side=0;side<4;side++) { + for (side=0;side<4;side++) + { printf("side %d/4 ",side+1); theta0 = 0.5*M_PI*(double)side; @@ -397,7 +402,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> /*** second loop : angles ***/ - for (itheta = 0; itheta<ntheta; itheta++) { + for (itheta = 0; itheta<ntheta; itheta++) + { printf("."); fflush(stdout); theta = theta0 + (double)(itheta)*dtheta; @@ -405,109 +411,123 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> dy = (double)vcl_sin((double)theta); /*** third loop : start positions ***/ - for (pos=0;pos<posmax;pos++) { + for (pos=0;pos<posmax;pos++) + { - /* clear segment array */ - iseg = 0; + /* clear segment array */ + iseg = 0; - /*** fourth loop : phase for two-spaced pixels ***/ - for (lphase=0;lphase<2;lphase++) { + /*** fourth loop : phase for two-spaced pixels ***/ + for (lphase=0;lphase<2;lphase++) + { - /*** detect aligned points by blocs ***/ - inbloc = nblocs = cur = l = count[0] = 0; - xx = ox+pos*mx + (int)(dx*(double)(l*2+lphase)); - yy = oy+pos*my + (int)(dy*(double)(l*2+lphase)); + /*** detect aligned points by blocs ***/ + inbloc = nblocs = cur = l = count[0] = 0; + xx = ox+pos*mx + (int)(dx*(double)(l*2+lphase)); + yy = oy+pos*my + (int)(dy*(double)(l*2+lphase)); - for (;xx>=0 && xx<nx && yy>=0 && yy<ny;) { + for (;xx>=0 && xx<nx && yy>=0 && yy<ny;) + { indexAngle[0] = xx; - indexAngle[1] = yy; - // indice = yy*nx+xx - assert( indexAngle[0] < nx ); - assert( indexAngle[1] < ny ); - assert( indexAngle[0] >= 0 ); - assert( indexAngle[1] >= 0 ); - - error = static_cast<double>( m_AngleImage->GetPixel(indexAngle) ); - if (error>-100.0) { - error -= theta; - while (error<=-M_PI) error += 2.0*M_PI; - while (error>M_PI) error -= 2.0*M_PI; - if (error<0.0) error = -error; - if (error<prec) { - cur++; - if (!inbloc) { - startbloc[nblocs]=l; - inbloc=1; - } - } else { - if (inbloc) { - endbloc[nblocs] = l-1; - nblocs++; - count[nblocs] = cur; - } - inbloc=0; - } - } - /* compute next point */ - l++; - xx = ox+pos*mx + (int)(dx*(double)(l*2+lphase)); - yy = oy+pos*my + (int)(dy*(double)(l*2+lphase)); - } - - /*** detect meaningful segments ***/ - for (i=0;i<nblocs;i++) - for (j=i;j<nblocs;j++) - if ((nfa = test[count[j+1]-count[i] - +(n+1)*(1+endbloc[j]-startbloc[i])]) < max_nfa) { - seg[iseg].start = startbloc[i]*2+lphase; - seg[iseg].end = endbloc[j]*2+lphase; - seg[iseg].nfa = nfa; - seg[iseg].ok = 1; - iseg++; - /* reallocate if necessary */ - if (iseg==size_seg) { - size_seg = (size_seg*3)/2; - seg.resize(size_seg); + indexAngle[1] = yy; + // indice = yy*nx+xx + assert( indexAngle[0] < nx ); + assert( indexAngle[1] < ny ); + assert( indexAngle[0] >= 0 ); + assert( indexAngle[1] >= 0 ); + + error = static_cast<double>( m_AngleImage->GetPixel(indexAngle) ); + if (error>-100.0) + { + error -= theta; + while (error<=-M_PI) error += 2.0*M_PI; + while (error>M_PI) error -= 2.0*M_PI; + if (error<0.0) error = -error; + if (error<prec) + { + cur++; + if (!inbloc) + { + startbloc[nblocs]=l; + inbloc=1; + } + } + else + { + if (inbloc) + { + endbloc[nblocs] = l-1; + nblocs++; + count[nblocs] = cur; + } + inbloc=0; + } + } + /* compute next point */ + l++; + xx = ox+pos*mx + (int)(dx*(double)(l*2+lphase)); + yy = oy+pos*my + (int)(dy*(double)(l*2+lphase)); + } + + /*** detect meaningful segments ***/ + for (i=0;i<nblocs;i++) + for (j=i;j<nblocs;j++) + if ((nfa = test[count[j+1]-count[i] + +(n+1)*(1+endbloc[j]-startbloc[i])]) < max_nfa) + { + seg[iseg].start = startbloc[i]*2+lphase; + seg[iseg].end = endbloc[j]*2+lphase; + seg[iseg].nfa = nfa; + seg[iseg].ok = 1; + iseg++; + /* reallocate if necessary */ + if (iseg==size_seg) + { + size_seg = (size_seg*3)/2; + seg.resize(size_seg); // if (!seg) // mwerror(FATAL,1,"Not enough memory."); - } + } + } } - } - /*** end of phase loop ***/ - - /*** remove non-maximal segments ***/ - if (!m_isMeaningfulSegment) - for (i=0;i<iseg;i++) - for (j=0;j<iseg;j++) - if (i!=j) - - /* seg[i] is included in seg[j] ? */ - if (seg[i].start>=seg[j].start && seg[i].end<=seg[j].end) { - - /* remove the less meaningful of seg[i] and seg[j] */ - if (seg[i].nfa<seg[j].nfa) seg[j].ok=0; - else seg[i].ok=0; - - } - - /*** store detected segments ***/ - for (i=0;i<iseg;i++) - if (seg[i].ok) { - seglist[iseglist*5 ]=(double)(ox+pos*mx)+dx*(double)(seg[i].start); - seglist[iseglist*5+1]=(double)(oy+pos*my)+dy*(double)(seg[i].start); - seglist[iseglist*5+2]=(double)(ox+pos*mx)+dx*(double)(seg[i].end); - seglist[iseglist*5+3]=(double)(oy+pos*my)+dy*(double)(seg[i].end); - seglist[iseglist*5+4]=-(double)log10(seg[i].nfa); - iseglist++; - /* reallocate seglist if necessary */ - if (iseglist==size_seglist) { - size_seglist = (size_seglist*3)/2; - seglist.resize(size_seglist); + /*** end of phase loop ***/ + + /*** remove non-maximal segments ***/ + if (!m_isMeaningfulSegment) + for (i=0;i<iseg;i++) + for (j=0;j<iseg;j++) + if (i!=j) + + /* seg[i] is included in seg[j] ? */ + if (seg[i].start>=seg[j].start && seg[i].end<=seg[j].end) + { + + /* remove the less meaningful of seg[i] and seg[j] */ + if (seg[i].nfa<seg[j].nfa) seg[j].ok=0; + else seg[i].ok=0; + + } + + /*** store detected segments ***/ + for (i=0;i<iseg;i++) + if (seg[i].ok) + { + seglist[iseglist*5 ]=(double)(ox+pos*mx)+dx*(double)(seg[i].start); + seglist[iseglist*5+1]=(double)(oy+pos*my)+dy*(double)(seg[i].start); + seglist[iseglist*5+2]=(double)(ox+pos*mx)+dx*(double)(seg[i].end); + seglist[iseglist*5+3]=(double)(oy+pos*my)+dy*(double)(seg[i].end); + seglist[iseglist*5+4]=-(double)log10(seg[i].nfa); + iseglist++; + /* reallocate seglist if necessary */ + if (iseglist==size_seglist) + { + size_seglist = (size_seglist*3)/2; + seglist.resize(size_seglist); // if (!seglist) // mwerror(FATAL,1,"Not enough memory."); - } - } + } + } } } /*** end of second loop ***/ @@ -533,7 +553,8 @@ ImageToPathListAlignFilter<TInputImage,TOutputPath> typename InputImageType::PointType point; ContinuousIndexType cindex; - for (i=0;i<iseglist;i++) { + for (i=0;i<iseglist;i++) + { OutputPathPointerType path = OutputPathType::New(); diff --git a/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.h b/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.h index 51c1edea7b62391abcd9908fd0c668a19e27921c..afab59bf63bcc636e259c8f50ef5c508387c98bb 100644 --- a/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.h +++ b/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.h @@ -39,350 +39,350 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace Functor - { - /** \class MagnitudeFunctor - * \brief This functor computes the magnitude of a covariant vector. - */ - template <class TInputPixel,class TOutputPixel> - class MagnitudeFunctor - { - public: - - inline TOutputPixel operator()(const TInputPixel& input) - { - return vcl_sqrt(input[0]*input[0]+input[1]*input[1]); - } - }; - - /** \class OrientationFunctor - * \brief This functor computes the orientation of a cavariant vector<br> - * Orientation values lies between 0 and 2*Pi. - */ - template <class TInputPixel,class TOutputPixel> - class OrientationFunctor +namespace Functor +{ +/** \class MagnitudeFunctor + * \brief This functor computes the magnitude of a covariant vector. + */ +template <class TInputPixel,class TOutputPixel> +class MagnitudeFunctor +{ +public: + + inline TOutputPixel operator()(const TInputPixel& input) { - public: + return vcl_sqrt(input[0]*input[0]+input[1]*input[1]); + } +}; + +/** \class OrientationFunctor + * \brief This functor computes the orientation of a cavariant vector<br> + * Orientation values lies between 0 and 2*Pi. + */ +template <class TInputPixel,class TOutputPixel> +class OrientationFunctor +{ +public: - inline TOutputPixel operator()(const TInputPixel& input) - { - TOutputPixel resp = vcl_atan2(input[1],input[0]); - if(resp<0) + inline TOutputPixel operator()(const TInputPixel& input) + { + TOutputPixel resp = vcl_atan2(input[1],input[0]); + if (resp<0) { resp+=2*M_PI; } - return resp; - } - }; - }// end namespace Functor + return resp; + } +}; +}// end namespace Functor + +/** \class ImageToSIFTKeyPointSetFilter + * \brief This class extracts key points from an input image, trough a pyramidal decomposition. + * + * This class implements the SIFT key point detector proposed by David G. Lowe in proceedings of International + * Conference on Computer Vision, Corfu, september 1999. + * + * \li Input image is downsample by factor 2 + * \li Pyramid of gaussians is obtained by filtering input image with + * variable length sigma, each separated by a constant k = 2^(1/S) + * where S is the number of scales + * \li Difference of gaussian are compute with the difference of two + * adjacent gaussian image results + * \li Detector is laucnched on each difference of gaussian to find key point + * \li A key point is a local minimum or a local maximum on 3*3 neighborhood + * \li An interpolated location of the maximum key point is compute with fitting + * a 3D quadratic function + * \li DoG low constrast are discarded (DoG < 3%) + * \li High edge responses key point are discarded + * + * Selected key points are stored in a itk::PointSet structure. + * Data points contains a list of (magnitude, main orientation) for each level + * of the pyramidal decomposition. + * + * Orientation is expressed in degree in the range [0,360] with a precision of 10 degrees. + * + * \example FeatureExtraction/SIFTExample.cxx + * + */ +template <class TInputImage, class TOutputPointSet> +class ITK_EXPORT ImageToSIFTKeyPointSetFilter + : public ImageToPointSetFilter<TInputImage,TOutputPointSet> +{ +public: + /** Standard typedefs */ + typedef ImageToSIFTKeyPointSetFilter Self; + typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Creation through object factory macro */ + itkNewMacro(Self); + + /** Type macro */ + itkTypeMacro(ImageToSIFTKeyPointSetFilter,ImageToPointSetFilter); + + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef typename TInputImage::Pointer InputImagePointerType; + typedef typename TInputImage::PixelType PixelType; + + typedef TOutputPointSet OutputPointSetType; + typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; + typedef typename TOutputPointSet::PixelType OutputPixelType; + typedef typename TOutputPointSet::PointType OutputPointType; + typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; + + typedef itk::Vector<PixelType,3> VectorPointType; + + /** Set/Get the number of octaves */ + itkSetMacro(OctavesNumber, unsigned int); + itkGetMacro(OctavesNumber, unsigned int); + + /** Set/Get the number of scales */ + itkSetMacro(ScalesNumber, unsigned int); + itkGetMacro(ScalesNumber, unsigned int); + + /** Set/Get the expand factors */ + itkSetMacro(ExpandFactors, unsigned int); + itkGetMacro(ExpandFactors, unsigned int); + + /** Set/Get the shrink factors */ + itkSetMacro(ShrinkFactors, unsigned int); + itkGetMacro(ShrinkFactors, unsigned int); + + /** Set/Get the sigma 0 */ + itkSetMacro(Sigma0, double); + itkGetMacro(Sigma0, double); + + /** Set/Get the Difference of gaussian threshold + * eliminating low contrast key point + */ + itkSetMacro(DoGThreshold, double); + itkGetMacro(DoGThreshold, double); + + /** Set/Get Edgethreshold + * Eliminating edge responses + */ + itkSetMacro(EdgeThreshold, double); + itkGetMacro(EdgeThreshold, double); + + /** Set/Get Gauss sigma factor orientation */ + itkSetMacro(SigmaFactorOrientation, double); + itkGetMacro(SigmaFactorOrientation, double); + + /** Set/Get Gauss sigma factor descriptor */ + itkSetMacro(SigmaFactorDescriptor, double); + itkGetMacro(SigmaFactorDescriptor, double); + + /** Internal typedefs */ + typedef itk::ExpandImageFilter<TInputImage, TInputImage> ExpandFilterType; + typedef typename ExpandFilterType::Pointer ExpandFilterPointerType; + + typedef itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkFilterType; + typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; + + typedef itk::RecursiveGaussianImageFilter<InputImageType,InputImageType> GaussianFilterType; + typedef typename GaussianFilterType::Pointer GaussianFilterPointerType; + + typedef otb::ImageList<InputImageType> ImageListType; + typedef typename ImageListType::Pointer ImageListPointerType; + + typedef itk::SubtractImageFilter<InputImageType,InputImageType,InputImageType> SubtractFilterType; + typedef typename SubtractFilterType::Pointer SubtractFilterPointerType; + + typedef itk::ConstNeighborhoodIterator<InputImageType> NeighborhoodIteratorType; + typedef typename NeighborhoodIteratorType::NeighborhoodType NeighborhoodType; + typedef typename NeighborhoodType::OffsetType OffsetType; + + typedef itk::ImageRegionConstIterator<InputImageType> RegionIteratorType; + + typedef itk::MinimumMaximumImageCalculator<InputImageType> MinimumMaximumCalculatorType; + typedef typename MinimumMaximumCalculatorType::Pointer MinimumMaximumCalculatorPointerType; + + typedef itk::GradientImageFilter<InputImageType,PixelType,PixelType> GradientFilterType; + typedef typename GradientFilterType::Pointer GradientFilterPointerType; + typedef typename GradientFilterType::OutputImageType GradientOutputImageType; + + typedef itk::UnaryFunctorImageFilter<GradientOutputImageType,InputImageType, + Functor::MagnitudeFunctor<typename GradientOutputImageType::PixelType,typename InputImageType::PixelType> > MagnitudeFilterType; + typedef typename MagnitudeFilterType::Pointer MagnitudeFilterPointerType; + + typedef itk::UnaryFunctorImageFilter<GradientOutputImageType,InputImageType, + Functor::OrientationFunctor<typename GradientOutputImageType::PixelType,typename InputImageType::PixelType> > OrientationFilterType; + typedef typename OrientationFilterType::Pointer OrientationFilterPointerType; + +protected: + /** Actually process the input */ + virtual void GenerateData(); + + /** Constructor */ + ImageToSIFTKeyPointSetFilter(); + + /** Destructor */ + virtual ~ImageToSIFTKeyPointSetFilter() {} + + /** PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** \class ImageToSIFTKeyPointSetFilter - * \brief This class extracts key points from an input image, trough a pyramidal decomposition. + /** Initialize input image */ + void InitializeInputImage(); + + /** Compute differenec of gaussian * - * This class implements the SIFT key point detector proposed by David G. Lowe in proceedings of International - * Conference on Computer Vision, Corfu, september 1999. + * \param input, current input in process + */ + void ComputeDifferenceOfGaussian(InputImagePointerType input); + + /** Localize key point */ + void DetectKeyPoint( const unsigned int octave ); + + /** Check local extremum for 26 neighbors (current and adjacents scales) * - * \li Input image is downsample by factor 2 - * \li Pyramid of gaussians is obtained by filtering input image with - * variable length sigma, each separated by a constant k = 2^(1/S) - * where S is the number of scales - * \li Difference of gaussian are compute with the difference of two - * adjacent gaussian image results - * \li Detector is laucnched on each difference of gaussian to find key point - * \li A key point is a local minimum or a local maximum on 3*3 neighborhood - * \li An interpolated location of the maximum key point is compute with fitting - * a 3D quadratic function - * \li DoG low constrast are discarded (DoG < 3%) - * \li High edge responses key point are discarded + * \param currentScale + * \param previousScale + * \param nextScale * - * Selected key points are stored in a itk::PointSet structure. - * Data points contains a list of (magnitude, main orientation) for each level - * of the pyramidal decomposition. + * \return true if the pixel is extremum + */ + bool IsLocalExtremum( const NeighborhoodIteratorType& currentScale, + const NeighborhoodIteratorType& previousScale, + const NeighborhoodIteratorType& nextScale ) const; + + /** Refine location key point * - * Orientation is expressed in degree in the range [0,360] with a precision of 10 degrees. + * \li Discard keypoints with low contrats DoG < DoGThreshold + * \li Discard keypoints that have a ratio between the principles + * curvature greater than EdgeTrhesold (=10) * - * \example FeatureExtraction/SIFTExample.cxx + * \param currentScale iterator + * \param previousScale iterator + * \param nextScale iterator + * \param offset pixel location * + * \return true if key point is accepted, false otherwise */ - template <class TInputImage, class TOutputPointSet> - class ITK_EXPORT ImageToSIFTKeyPointSetFilter - : public ImageToPointSetFilter<TInputImage,TOutputPointSet> - { - public: - /** Standard typedefs */ - typedef ImageToSIFTKeyPointSetFilter Self; - typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Creation through object factory macro */ - itkNewMacro(Self); - - /** Type macro */ - itkTypeMacro(ImageToSIFTKeyPointSetFilter,ImageToPointSetFilter); + bool RefineLocationKeyPoint( const NeighborhoodIteratorType& currentScale, + const NeighborhoodIteratorType& previousScale, + const NeighborhoodIteratorType& nextScale, + VectorPointType& solution); - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef typename TInputImage::Pointer InputImagePointerType; - typedef typename TInputImage::PixelType PixelType; - - typedef TOutputPointSet OutputPointSetType; - typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; - typedef typename TOutputPointSet::PixelType OutputPixelType; - typedef typename TOutputPointSet::PointType OutputPointType; - typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; + /** Assign key point orientation + * + * \param currentScale neighborhood iterator + * \param scale current scale + * \param translation refine offset pixel location + * + * \return orientation key point orientation + */ + std::vector<PixelType> ComputeKeyPointOrientations(const NeighborhoodIteratorType& currentScale, + const unsigned int scale, + const PixelType translation); - typedef itk::Vector<PixelType,3> VectorPointType; + /** Compute local image descriptor + * + * \param currentScale neighborhood iterator + * \param scale + * \param orientation + * + * \return histogram descriptor + */ + std::vector<PixelType> ComputeKeyPointDescriptor(const NeighborhoodIteratorType& currentScale, + const unsigned int scale, + const PixelType& orientation); - /** Set/Get the number of octaves */ - itkSetMacro(OctavesNumber, unsigned int); - itkGetMacro(OctavesNumber, unsigned int); +private: + ImageToSIFTKeyPointSetFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - /** Set/Get the number of scales */ - itkSetMacro(ScalesNumber, unsigned int); - itkGetMacro(ScalesNumber, unsigned int); + /** Number of octaves */ + unsigned int m_OctavesNumber; - /** Set/Get the expand factors */ - itkSetMacro(ExpandFactors, unsigned int); - itkGetMacro(ExpandFactors, unsigned int); + /** Number of scale for each octave */ + unsigned int m_ScalesNumber; - /** Set/Get the shrink factors */ - itkSetMacro(ShrinkFactors, unsigned int); - itkGetMacro(ShrinkFactors, unsigned int); + /** Expand factors */ + unsigned int m_ExpandFactors; - /** Set/Get the sigma 0 */ - itkSetMacro(Sigma0, double); - itkGetMacro(Sigma0, double); + /** Shrink factors */ + unsigned int m_ShrinkFactors; - /** Set/Get the Difference of gaussian threshold - * eliminating low contrast key point - */ - itkSetMacro(DoGThreshold, double); - itkGetMacro(DoGThreshold, double); + /** Threshold DoG */ + double m_DoGThreshold; - /** Set/Get Edgethreshold - * Eliminating edge responses - */ - itkSetMacro(EdgeThreshold, double); - itkGetMacro(EdgeThreshold, double); + /** Edge Threshold */ + double m_EdgeThreshold; - /** Set/Get Gauss sigma factor orientation */ - itkSetMacro(SigmaFactorOrientation, double); - itkGetMacro(SigmaFactorOrientation, double); + /** Ratio threshold compute */ + double m_RatioEdgeThreshold; - /** Set/Get Gauss sigma factor descriptor */ - itkSetMacro(SigmaFactorDescriptor, double); - itkGetMacro(SigmaFactorDescriptor, double); + /** Histogram sift keys descriptors gradient magnitude threshold */ + PixelType m_GradientMagnitudeThreshold; - /** Internal typedefs */ - typedef itk::ExpandImageFilter<TInputImage, TInputImage> ExpandFilterType; - typedef typename ExpandFilterType::Pointer ExpandFilterPointerType; + /** Sigma 0 */ + typename GaussianFilterType::ScalarRealType m_Sigma0; - typedef itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkFilterType; - typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; + /** Sigma k */ + double m_Sigmak; - typedef itk::RecursiveGaussianImageFilter<InputImageType,InputImageType> GaussianFilterType; - typedef typename GaussianFilterType::Pointer GaussianFilterPointerType; + /** Gauss factor length for key point orientation */ + double m_SigmaFactorOrientation; - typedef otb::ImageList<InputImageType> ImageListType; - typedef typename ImageListType::Pointer ImageListPointerType; + /** Descriptor size */ + double m_SigmaFactorDescriptor; - typedef itk::SubtractImageFilter<InputImageType,InputImageType,InputImageType> SubtractFilterType; - typedef typename SubtractFilterType::Pointer SubtractFilterPointerType; + /** Expand filter */ + ExpandFilterPointerType m_ExpandFilter; - typedef itk::ConstNeighborhoodIterator<InputImageType> NeighborhoodIteratorType; - typedef typename NeighborhoodIteratorType::NeighborhoodType NeighborhoodType; - typedef typename NeighborhoodType::OffsetType OffsetType; + /** Shrink filter */ + ShrinkFilterPointerType m_ShrinkFilter; - typedef itk::ImageRegionConstIterator<InputImageType> RegionIteratorType; + /** Gaussian filter */ + GaussianFilterPointerType m_XGaussianFilter; + GaussianFilterPointerType m_YGaussianFilter; - typedef itk::MinimumMaximumImageCalculator<InputImageType> MinimumMaximumCalculatorType; - typedef typename MinimumMaximumCalculatorType::Pointer MinimumMaximumCalculatorPointerType; + /** Gaussian image pointer */ + InputImagePointerType m_LastGaussian; - typedef itk::GradientImageFilter<InputImageType,PixelType,PixelType> GradientFilterType; - typedef typename GradientFilterType::Pointer GradientFilterPointerType; - typedef typename GradientFilterType::OutputImageType GradientOutputImageType; + /** Difference of gaussian list */ + ImageListPointerType m_DoGList; - typedef itk::UnaryFunctorImageFilter<GradientOutputImageType,InputImageType, - Functor::MagnitudeFunctor<typename GradientOutputImageType::PixelType,typename InputImageType::PixelType> > MagnitudeFilterType; - typedef typename MagnitudeFilterType::Pointer MagnitudeFilterPointerType; + /** Magnitude image list */ + ImageListPointerType m_MagnitudeList; - typedef itk::UnaryFunctorImageFilter<GradientOutputImageType,InputImageType, - Functor::OrientationFunctor<typename GradientOutputImageType::PixelType,typename InputImageType::PixelType> > OrientationFilterType; - typedef typename OrientationFilterType::Pointer OrientationFilterPointerType; - - protected: - /** Actually process the input */ - virtual void GenerateData(); - - /** Constructor */ - ImageToSIFTKeyPointSetFilter(); - - /** Destructor */ - virtual ~ImageToSIFTKeyPointSetFilter() {} - - /** PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /** Initialize input image */ - void InitializeInputImage(); - - /** Compute differenec of gaussian - * - * \param input, current input in process - */ - void ComputeDifferenceOfGaussian(InputImagePointerType input); - - /** Localize key point */ - void DetectKeyPoint( const unsigned int octave ); - - /** Check local extremum for 26 neighbors (current and adjacents scales) - * - * \param currentScale - * \param previousScale - * \param nextScale - * - * \return true if the pixel is extremum - */ - bool IsLocalExtremum( const NeighborhoodIteratorType& currentScale, - const NeighborhoodIteratorType& previousScale, - const NeighborhoodIteratorType& nextScale ) const; - - /** Refine location key point - * - * \li Discard keypoints with low contrats DoG < DoGThreshold - * \li Discard keypoints that have a ratio between the principles - * curvature greater than EdgeTrhesold (=10) - * - * \param currentScale iterator - * \param previousScale iterator - * \param nextScale iterator - * \param offset pixel location - * - * \return true if key point is accepted, false otherwise - */ - bool RefineLocationKeyPoint( const NeighborhoodIteratorType& currentScale, - const NeighborhoodIteratorType& previousScale, - const NeighborhoodIteratorType& nextScale, - VectorPointType& solution); - - /** Assign key point orientation - * - * \param currentScale neighborhood iterator - * \param scale current scale - * \param translation refine offset pixel location - * - * \return orientation key point orientation - */ - std::vector<PixelType> ComputeKeyPointOrientations(const NeighborhoodIteratorType& currentScale, - const unsigned int scale, - const PixelType translation); - - /** Compute local image descriptor - * - * \param currentScale neighborhood iterator - * \param scale - * \param orientation - * - * \return histogram descriptor - */ - std::vector<PixelType> ComputeKeyPointDescriptor(const NeighborhoodIteratorType& currentScale, - const unsigned int scale, - const PixelType& orientation); - - private: - ImageToSIFTKeyPointSetFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Number of octaves */ - unsigned int m_OctavesNumber; - - /** Number of scale for each octave */ - unsigned int m_ScalesNumber; - - /** Expand factors */ - unsigned int m_ExpandFactors; - - /** Shrink factors */ - unsigned int m_ShrinkFactors; - - /** Threshold DoG */ - double m_DoGThreshold; - - /** Edge Threshold */ - double m_EdgeThreshold; - - /** Ratio threshold compute */ - double m_RatioEdgeThreshold; - - /** Histogram sift keys descriptors gradient magnitude threshold */ - PixelType m_GradientMagnitudeThreshold; - - /** Sigma 0 */ - typename GaussianFilterType::ScalarRealType m_Sigma0; - - /** Sigma k */ - double m_Sigmak; - - /** Gauss factor length for key point orientation */ - double m_SigmaFactorOrientation; - - /** Descriptor size */ - double m_SigmaFactorDescriptor; - - /** Expand filter */ - ExpandFilterPointerType m_ExpandFilter; - - /** Shrink filter */ - ShrinkFilterPointerType m_ShrinkFilter; - - /** Gaussian filter */ - GaussianFilterPointerType m_XGaussianFilter; - GaussianFilterPointerType m_YGaussianFilter; - - /** Gaussian image pointer */ - InputImagePointerType m_LastGaussian; - - /** Difference of gaussian list */ - ImageListPointerType m_DoGList; - - /** Magnitude image list */ - ImageListPointerType m_MagnitudeList; - - /** Orientation image list */ - ImageListPointerType m_OrientationList; + /** Orientation image list */ + ImageListPointerType m_OrientationList; - /** Subtract filter */ - SubtractFilterPointerType m_SubtractFilter; + /** Subtract filter */ + SubtractFilterPointerType m_SubtractFilter; - /** Gradient filter */ - GradientFilterPointerType m_GradientFilter; + /** Gradient filter */ + GradientFilterPointerType m_GradientFilter; - /** Magnitude filter */ - MagnitudeFilterPointerType m_MagnitudeFilter; + /** Magnitude filter */ + MagnitudeFilterPointerType m_MagnitudeFilter; - /** Orientation filter */ - OrientationFilterPointerType m_OrientationFilter; + /** Orientation filter */ + OrientationFilterPointerType m_OrientationFilter; - /** Number of key points */ - OutputPointIdentifierType m_ValidatedKeyPoints; + /** Number of key points */ + OutputPointIdentifierType m_ValidatedKeyPoints; - /** Number of key point which offset is larger than 0.5 per octave*/ - unsigned int m_DifferentSamplePoints; + /** Number of key point which offset is larger than 0.5 per octave*/ + unsigned int m_DifferentSamplePoints; - /** Number of discarded key points */ - unsigned int m_DiscardedKeyPoints; + /** Number of discarded key points */ + unsigned int m_DiscardedKeyPoints; - /** Number of change sample max */ - unsigned int m_ChangeSamplePointsMax; + /** Number of change sample max */ + unsigned int m_ChangeSamplePointsMax; - /** Gaussian sigma for histogram smoothing */ - static const double m_HistogramGaussianWeights[73]; + /** Gaussian sigma for histogram smoothing */ + static const double m_HistogramGaussianWeights[73]; - /** Offsets vector, conveniance datas */ - static const OffsetType m_Offsets[8]; - }; + /** Offsets vector, conveniance datas */ + static const OffsetType m_Offsets[8]; +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbImageToSIFTKeyPointSetFilter.txx" diff --git a/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.txx b/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.txx index f46813ccbca72a337430e7ecbe22b98312c5e039..d80e693c785060ec9a1093684a8f99716112a101 100644 --- a/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.txx +++ b/Code/FeatureExtraction/otbImageToSIFTKeyPointSetFilter.txx @@ -27,210 +27,213 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputImage, class TOutputPointSet> - const double - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::m_HistogramGaussianWeights[73] = { - 2.3771112282795414e-07, 3.8860734758633732e-07, 6.2655544995978937e-07, 9.9631120821413786e-07, 1.5624909838697011e-06, 2.4167238265599128e-06, 3.6865788528530121e-06, - 5.5463469229192623e-06, 8.2295774080263437e-06, 1.2043009749602365e-05, 1.738119136656513e-05, 2.4740646513897326e-05, 3.4731980398846277e-05, 4.808781565748272e-05, - 6.5664032975164266e-05, 8.8431512984476723e-05, 0.00011745555408931643, 0.00015386047198026335, 0.00019877765486783745, 0.00025327659834301937, 0.00031828015928190065, - 0.00039446735551235698, 0.00048216931692246382, 0.00058126620279441276, 0.00069109471776775144, 0.00081037694122312908, 0.00093718121775182789, 0.0010689246133776746, - 0.0012024238404411182, 0.0013339976954896103, 0.0014596192424447215, 0.0015751106965100009, 0.0016763688464699555, 0.0017596045720966803, 0.0018215772013714365, - 0.0018598035923515156, 0.0018727231637146351, 0.0018598035923515156, 0.0018215772013714365, 0.0017596045720966803, 0.0016763688464699555, 0.0015751106965100009, - 0.0014596192424447215, 0.0013339976954896103, 0.0012024238404411182, 0.0010689246133776746, 0.00093718121775182789, 0.00081037694122312908, 0.00069109471776775144, - 0.00058126620279441276, 0.00048216931692246382, 0.00039446735551235698, 0.00031828015928190065, 0.00025327659834301937, 0.00019877765486783745, 0.00015386047198026335, - 0.00011745555408931643, 8.8431512984476723e-05, 6.5664032975164266e-05, 4.808781565748272e-05, 3.4731980398846277e-05, 2.4740646513897326e-05, 1.738119136656513e-05, - 1.2043009749602365e-05, 8.2295774080263437e-06, 5.5463469229192623e-06, 3.6865788528530121e-06, 2.4167238265599128e-06, 1.5624909838697011e-06, 9.9631120821413786e-07, - 6.2655544995978937e-07, 3.8860734758633732e-07, 2.3771112282795414e-07}; - - template <class TInputImage, class TOutputPointSet> - const typename ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::OffsetType - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::m_Offsets[8] = { - {{-1,-1}}, //0 - {{-1, 0}}, //1 - {{-1, 1}}, //2 - {{ 0,-1}}, //3 - {{ 0, 1}}, //4 - {{ 1,-1}}, //5 - {{ 1, 0}}, //6 - {{ 1, 1}}, //7 - }; - - /** - * Constructor - */ - template <class TInputImage, class TOutputPointSet> - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::ImageToSIFTKeyPointSetFilter() - { - m_OctavesNumber = 1; - m_ScalesNumber = 3; - m_ExpandFactors = 2; - m_ShrinkFactors = 2; - m_Sigma0 = 1.6; - m_Sigmak = 0; - - m_DoGThreshold = 0.03; - m_EdgeThreshold = 10; - m_RatioEdgeThreshold = 0; - - m_ValidatedKeyPoints = 0; - m_DifferentSamplePoints = 0; - m_DiscardedKeyPoints = 0; - m_ChangeSamplePointsMax = 2; +template <class TInputImage, class TOutputPointSet> +const double +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::m_HistogramGaussianWeights[73] = +{ + 2.3771112282795414e-07, 3.8860734758633732e-07, 6.2655544995978937e-07, 9.9631120821413786e-07, 1.5624909838697011e-06, 2.4167238265599128e-06, 3.6865788528530121e-06, + 5.5463469229192623e-06, 8.2295774080263437e-06, 1.2043009749602365e-05, 1.738119136656513e-05, 2.4740646513897326e-05, 3.4731980398846277e-05, 4.808781565748272e-05, + 6.5664032975164266e-05, 8.8431512984476723e-05, 0.00011745555408931643, 0.00015386047198026335, 0.00019877765486783745, 0.00025327659834301937, 0.00031828015928190065, + 0.00039446735551235698, 0.00048216931692246382, 0.00058126620279441276, 0.00069109471776775144, 0.00081037694122312908, 0.00093718121775182789, 0.0010689246133776746, + 0.0012024238404411182, 0.0013339976954896103, 0.0014596192424447215, 0.0015751106965100009, 0.0016763688464699555, 0.0017596045720966803, 0.0018215772013714365, + 0.0018598035923515156, 0.0018727231637146351, 0.0018598035923515156, 0.0018215772013714365, 0.0017596045720966803, 0.0016763688464699555, 0.0015751106965100009, + 0.0014596192424447215, 0.0013339976954896103, 0.0012024238404411182, 0.0010689246133776746, 0.00093718121775182789, 0.00081037694122312908, 0.00069109471776775144, + 0.00058126620279441276, 0.00048216931692246382, 0.00039446735551235698, 0.00031828015928190065, 0.00025327659834301937, 0.00019877765486783745, 0.00015386047198026335, + 0.00011745555408931643, 8.8431512984476723e-05, 6.5664032975164266e-05, 4.808781565748272e-05, 3.4731980398846277e-05, 2.4740646513897326e-05, 1.738119136656513e-05, + 1.2043009749602365e-05, 8.2295774080263437e-06, 5.5463469229192623e-06, 3.6865788528530121e-06, 2.4167238265599128e-06, 1.5624909838697011e-06, 9.9631120821413786e-07, + 6.2655544995978937e-07, 3.8860734758633732e-07, 2.3771112282795414e-07 +}; + +template <class TInputImage, class TOutputPointSet> +const typename ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::OffsetType +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::m_Offsets[8] = +{ + {{-1,-1}}, //0 + {{-1, 0}}, //1 + {{-1, 1}}, //2 + {{ 0,-1}}, //3 + {{ 0, 1}}, //4 + {{ 1,-1}}, //5 + {{ 1, 0}}, //6 + {{ 1, 1}}, //7 +}; + +/** + * Constructor + */ +template <class TInputImage, class TOutputPointSet> +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::ImageToSIFTKeyPointSetFilter() +{ + m_OctavesNumber = 1; + m_ScalesNumber = 3; + m_ExpandFactors = 2; + m_ShrinkFactors = 2; + m_Sigma0 = 1.6; + m_Sigmak = 0; + + m_DoGThreshold = 0.03; + m_EdgeThreshold = 10; + m_RatioEdgeThreshold = 0; + + m_ValidatedKeyPoints = 0; + m_DifferentSamplePoints = 0; + m_DiscardedKeyPoints = 0; + m_ChangeSamplePointsMax = 2; - m_SigmaFactorOrientation = 3; - m_SigmaFactorDescriptor = 1.5; + m_SigmaFactorOrientation = 3; + m_SigmaFactorDescriptor = 1.5; - m_GradientMagnitudeThreshold = 0.2; + m_GradientMagnitudeThreshold = 0.2; - m_ExpandFilter = ExpandFilterType::New(); - } + m_ExpandFilter = ExpandFilterType::New(); +} - template <class TInputImage, class TOutputPointSet> - void - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::GenerateData() - { - // First, subsample the input image - InitializeInputImage(); +template <class TInputImage, class TOutputPointSet> +void +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::GenerateData() +{ + // First, subsample the input image + InitializeInputImage(); - InputImagePointerType input = m_ExpandFilter->GetOutput(); - typename InputImageType::PointType point; - typename InputImageType::IndexType index; - index[0] = 0; - index[1] = 0; + InputImagePointerType input = m_ExpandFilter->GetOutput(); + typename InputImageType::PointType point; + typename InputImageType::IndexType index; + index[0] = 0; + index[1] = 0; - m_ExpandFilter->GetOutput()->TransformIndexToPhysicalPoint(index, point); + m_ExpandFilter->GetOutput()->TransformIndexToPhysicalPoint(index, point); - // for each octave, compute the difference of gaussian - unsigned int lOctave = 0; - m_Sigmak = vcl_pow(2, static_cast<double>(1/(double)(m_ScalesNumber+1))); - m_RatioEdgeThreshold = (m_EdgeThreshold+1)*(m_EdgeThreshold+1)/m_EdgeThreshold; + // for each octave, compute the difference of gaussian + unsigned int lOctave = 0; + m_Sigmak = vcl_pow(2, static_cast<double>(1/(double)(m_ScalesNumber+1))); + m_RatioEdgeThreshold = (m_EdgeThreshold+1)*(m_EdgeThreshold+1)/m_EdgeThreshold; - for (lOctave = 0; lOctave != m_OctavesNumber; lOctave++) - { - m_DifferentSamplePoints = 0; - m_DiscardedKeyPoints = 0; + for (lOctave = 0; lOctave != m_OctavesNumber; lOctave++) + { + m_DifferentSamplePoints = 0; + m_DiscardedKeyPoints = 0; - typename InputImageType::PointType origin0 = input->GetOrigin(); + typename InputImageType::PointType origin0 = input->GetOrigin(); - ComputeDifferenceOfGaussian(input); - DetectKeyPoint(lOctave); + ComputeDifferenceOfGaussian(input); + DetectKeyPoint(lOctave); - // Get the last gaussian for subsample and - // repeat the process - m_ShrinkFilter = ShrinkFilterType::New(); - m_ShrinkFilter->SetInput(m_LastGaussian); - m_ShrinkFilter->SetShrinkFactors(m_ShrinkFactors); - m_ShrinkFilter->Update(); + // Get the last gaussian for subsample and + // repeat the process + m_ShrinkFilter = ShrinkFilterType::New(); + m_ShrinkFilter->SetInput(m_LastGaussian); + m_ShrinkFilter->SetShrinkFactors(m_ShrinkFactors); + m_ShrinkFilter->Update(); - input = m_ShrinkFilter->GetOutput(); + input = m_ShrinkFilter->GetOutput(); - typename InputImageType::PointType origin1; - typename InputImageType::SpacingType spacing = input->GetSpacing(); + typename InputImageType::PointType origin1; + typename InputImageType::SpacingType spacing = input->GetSpacing(); - origin1[0] = origin0[0] + spacing[0]*0.25; - origin1[1] = origin0[1] + spacing[1]*0.25; + origin1[0] = origin0[0] + spacing[0]*0.25; + origin1[1] = origin0[1] + spacing[1]*0.25; - input->SetOrigin(origin1); + input->SetOrigin(origin1); - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number total key points : " \ - << m_ValidatedKeyPoints); - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number different sample key points per octave : " \ - << m_DifferentSamplePoints ); - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number discarded key points per octave : " \ - << m_DiscardedKeyPoints ); - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Resample image factor : " \ - << m_ShrinkFactors); + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number total key points : " \ + << m_ValidatedKeyPoints); + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number different sample key points per octave : " \ + << m_DifferentSamplePoints ); + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number discarded key points per octave : " \ + << m_DiscardedKeyPoints ); + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Resample image factor : " \ + << m_ShrinkFactors); - } + } - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Total number key points : " \ - << this->GetOutput()->GetNumberOfPoints()); + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Total number key points : " \ + << this->GetOutput()->GetNumberOfPoints()); - } +} - /** - * Initialize the input image - */ - template <class TInputImage, class TOutputPointSet> - void - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::InitializeInputImage() - { - m_ExpandFilter->SetInput( this->GetInput()); - m_ExpandFilter->SetExpandFactors(m_ExpandFactors); - m_ExpandFilter->Update(); +/** + * Initialize the input image + */ +template <class TInputImage, class TOutputPointSet> +void +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::InitializeInputImage() +{ + m_ExpandFilter->SetInput( this->GetInput()); + m_ExpandFilter->SetExpandFactors(m_ExpandFactors); + m_ExpandFilter->Update(); - typename InputImageType::PointType origin0 = this->GetInput()->GetOrigin(); - typename InputImageType::PointType origin1; - typename InputImageType::SpacingType spacing = m_ExpandFilter->GetOutput()->GetSpacing(); + typename InputImageType::PointType origin0 = this->GetInput()->GetOrigin(); + typename InputImageType::PointType origin1; + typename InputImageType::SpacingType spacing = m_ExpandFilter->GetOutput()->GetSpacing(); - origin1[0] = origin0[0]-spacing[0]*0.5; - origin1[1] = origin0[1]-spacing[1]*0.5; + origin1[0] = origin0[0]-spacing[0]*0.5; + origin1[1] = origin0[1]-spacing[1]*0.5; - m_ExpandFilter->GetOutput()->SetOrigin(origin1); - } + m_ExpandFilter->GetOutput()->SetOrigin(origin1); +} - /** - * Compute the difference of gaussian - */ - template <class TInputImage, class TOutputPointSet> - void - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::ComputeDifferenceOfGaussian(InputImagePointerType input) - { - unsigned int lScale = 0; - InputImagePointerType previousGaussian; +/** + * Compute the difference of gaussian + */ +template <class TInputImage, class TOutputPointSet> +void +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::ComputeDifferenceOfGaussian(InputImagePointerType input) +{ + unsigned int lScale = 0; + InputImagePointerType previousGaussian; - m_DoGList = ImageListType::New(); + m_DoGList = ImageListType::New(); - m_MagnitudeList = ImageListType::New(); - m_OrientationList = ImageListType::New(); + m_MagnitudeList = ImageListType::New(); + m_OrientationList = ImageListType::New(); // m_GaussianWeightOrientationList = ImageListType::New(); // m_GaussianWeightDescriptorList = ImageListType::New(); - // itkRecursiveGaussian use spacing to compute - // length sigma gaussian (in mm) - // sigma = sigma/spacing - // - // with multiply by spacing before filtering, length sigma gaussian - // is compute in pixel - double xsigman = vcl_abs(input->GetSpacing()[0])*m_Sigma0; - double ysigman = vcl_abs(input->GetSpacing()[1])*m_Sigma0; + // itkRecursiveGaussian use spacing to compute + // length sigma gaussian (in mm) + // sigma = sigma/spacing + // + // with multiply by spacing before filtering, length sigma gaussian + // is compute in pixel + double xsigman = vcl_abs(input->GetSpacing()[0])*m_Sigma0; + double ysigman = vcl_abs(input->GetSpacing()[1])*m_Sigma0; - for (lScale = 0; lScale != m_ScalesNumber+2; lScale++) - { - m_XGaussianFilter = GaussianFilterType::New(); - m_YGaussianFilter = GaussianFilterType::New(); + for (lScale = 0; lScale != m_ScalesNumber+2; lScale++) + { + m_XGaussianFilter = GaussianFilterType::New(); + m_YGaussianFilter = GaussianFilterType::New(); - m_XGaussianFilter->SetSigma(xsigman); - m_XGaussianFilter->SetDirection(0); - m_XGaussianFilter->SetInput(input); + m_XGaussianFilter->SetSigma(xsigman); + m_XGaussianFilter->SetDirection(0); + m_XGaussianFilter->SetInput(input); - m_YGaussianFilter->SetSigma(ysigman); - m_YGaussianFilter->SetDirection(1); - m_YGaussianFilter->SetInput(m_XGaussianFilter->GetOutput()); + m_YGaussianFilter->SetSigma(ysigman); + m_YGaussianFilter->SetDirection(1); + m_YGaussianFilter->SetInput(m_XGaussianFilter->GetOutput()); - m_YGaussianFilter->Update(); + m_YGaussianFilter->Update(); - m_GradientFilter = GradientFilterType::New(); - m_MagnitudeFilter = MagnitudeFilterType::New(); - m_OrientationFilter = OrientationFilterType::New(); + m_GradientFilter = GradientFilterType::New(); + m_MagnitudeFilter = MagnitudeFilterType::New(); + m_OrientationFilter = OrientationFilterType::New(); - m_GradientFilter->SetInput(m_YGaussianFilter->GetOutput()); - m_MagnitudeFilter->SetInput(m_GradientFilter->GetOutput()); - m_OrientationFilter->SetInput(m_GradientFilter->GetOutput()); + m_GradientFilter->SetInput(m_YGaussianFilter->GetOutput()); + m_MagnitudeFilter->SetInput(m_GradientFilter->GetOutput()); + m_OrientationFilter->SetInput(m_GradientFilter->GetOutput()); - m_MagnitudeFilter->Update(); - m_OrientationFilter->Update(); + m_MagnitudeFilter->Update(); + m_OrientationFilter->Update(); - m_MagnitudeList->PushBack(m_MagnitudeFilter->GetOutput()); - m_OrientationList->PushBack(m_OrientationFilter->GetOutput()); + m_MagnitudeList->PushBack(m_MagnitudeFilter->GetOutput()); + m_OrientationList->PushBack(m_OrientationFilter->GetOutput()); - if (lScale>0) + if (lScale>0) { m_SubtractFilter = SubtractFilterType::New(); m_SubtractFilter->SetInput1(m_YGaussianFilter->GetOutput()); @@ -239,31 +242,31 @@ namespace otb m_DoGList->PushBack(m_SubtractFilter->GetOutput()); } - previousGaussian = m_YGaussianFilter->GetOutput(); - xsigman = xsigman*m_Sigmak; - ysigman = ysigman*m_Sigmak; - } - m_LastGaussian = previousGaussian; - otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number of DoG "<<m_DoGList->Size() ); + previousGaussian = m_YGaussianFilter->GetOutput(); + xsigman = xsigman*m_Sigmak; + ysigman = ysigman*m_Sigmak; } - - /** - * Localize key point - */ - template <class TInputImage, class TOutputPointSet> - void - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::DetectKeyPoint( const unsigned int octave ) + m_LastGaussian = previousGaussian; + otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: Number of DoG "<<m_DoGList->Size() ); +} + +/** + * Localize key point + */ +template <class TInputImage, class TOutputPointSet> +void +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::DetectKeyPoint( const unsigned int octave ) +{ + // need at least 3 DoG, ie 2 scales + if (m_ScalesNumber > 1 ) { - // need at least 3 DoG, ie 2 scales - if (m_ScalesNumber > 1 ) - { - typename ImageListType::Iterator lIterDoG = m_DoGList->Begin()+1; - unsigned int lScale = 1; - OutputPointSetPointerType outputPointSet = this->GetOutput(); - typename InputImageType::SpacingType spacing = lIterDoG.Get()->GetSpacing(); + typename ImageListType::Iterator lIterDoG = m_DoGList->Begin()+1; + unsigned int lScale = 1; + OutputPointSetPointerType outputPointSet = this->GetOutput(); + typename InputImageType::SpacingType spacing = lIterDoG.Get()->GetSpacing(); - while ( (lIterDoG+1) != m_DoGList->End()) + while ( (lIterDoG+1) != m_DoGList->End()) { otbGenericMsgDebugMacro( <<"ImageToSIFTKeyPointSetFilter:: octave: " << octave << " scale: " << lScale); // Compute max of DoG @@ -277,319 +280,319 @@ namespace otb typename ImageListType::Iterator lIterPrev = lIterDoG-1; NeighborhoodIteratorType lIterCurrent(lRadius, - lIterDoG.Get(), - lIterDoG.Get()->GetLargestPossibleRegion()); + lIterDoG.Get(), + lIterDoG.Get()->GetLargestPossibleRegion()); NeighborhoodIteratorType lIterLowerAdjacent(lRadius, - lIterPrev.Get(), - lIterPrev.Get()->GetLargestPossibleRegion()); + lIterPrev.Get(), + lIterPrev.Get()->GetLargestPossibleRegion()); NeighborhoodIteratorType lIterUpperAdjacent(lRadius, - lIterNext.Get(), - lIterNext.Get()->GetLargestPossibleRegion()); + lIterNext.Get(), + lIterNext.Get()->GetLargestPossibleRegion()); while ( !lIterCurrent.IsAtEnd() && - !lIterLowerAdjacent.IsAtEnd() && - !lIterUpperAdjacent.IsAtEnd() ) - { - // check local min/max - if (IsLocalExtremum(lIterCurrent, - lIterLowerAdjacent, - lIterUpperAdjacent) ) + !lIterLowerAdjacent.IsAtEnd() && + !lIterUpperAdjacent.IsAtEnd() ) { - VectorPointType lTranslation(PixelType(0)); - OffsetType lOffsetZero = {{0,0}}; - - unsigned int lChangeSamplePoints = 0; - NeighborhoodIteratorType neighborCurrentScale(lIterCurrent); - NeighborhoodIteratorType neighborPreviousScale(lIterLowerAdjacent); - NeighborhoodIteratorType neighborNextScale(lIterUpperAdjacent); - - bool accepted = false; - bool changed = true; - while (lChangeSamplePoints < m_ChangeSamplePointsMax && - changed ) + // check local min/max + if (IsLocalExtremum(lIterCurrent, + lIterLowerAdjacent, + lIterUpperAdjacent) ) + { + VectorPointType lTranslation(PixelType(0)); + OffsetType lOffsetZero = {{0,0}}; + + unsigned int lChangeSamplePoints = 0; + NeighborhoodIteratorType neighborCurrentScale(lIterCurrent); + NeighborhoodIteratorType neighborPreviousScale(lIterLowerAdjacent); + NeighborhoodIteratorType neighborNextScale(lIterUpperAdjacent); + + bool accepted = false; + bool changed = true; + while (lChangeSamplePoints < m_ChangeSamplePointsMax && + changed ) { - accepted = RefineLocationKeyPoint(neighborCurrentScale, - neighborPreviousScale, - neighborNextScale, - lTranslation); + accepted = RefineLocationKeyPoint(neighborCurrentScale, + neighborPreviousScale, + neighborNextScale, + lTranslation); - OffsetType lTranslateOffset = {{0,0}}; + OffsetType lTranslateOffset = {{0,0}}; - lTranslateOffset[0] += static_cast<int>(lTranslation[0]>0.5); - lTranslateOffset[0] += -static_cast<int>(lTranslation[0]<-0.5); + lTranslateOffset[0] += static_cast<int>(lTranslation[0]>0.5); + lTranslateOffset[0] += -static_cast<int>(lTranslation[0]<-0.5); - lTranslateOffset[1] += static_cast<int>(lTranslation[1]>0.5); - lTranslateOffset[1] += -static_cast<int>(lTranslation[1]<-0.5); + lTranslateOffset[1] += static_cast<int>(lTranslation[1]>0.5); + lTranslateOffset[1] += -static_cast<int>(lTranslation[1]<-0.5); - NeighborhoodIteratorType moveIterator = neighborCurrentScale+lTranslateOffset; + NeighborhoodIteratorType moveIterator = neighborCurrentScale+lTranslateOffset; - if ( moveIterator.InBounds()) - { - changed = lTranslateOffset != lOffsetZero; + if ( moveIterator.InBounds()) + { + changed = lTranslateOffset != lOffsetZero; - // move iterator - neighborCurrentScale+=lTranslateOffset; - neighborPreviousScale+=lTranslateOffset; - neighborNextScale+=lTranslateOffset; - } - else - { - changed = false; - } - lChangeSamplePoints++; + // move iterator + neighborCurrentScale+=lTranslateOffset; + neighborPreviousScale+=lTranslateOffset; + neighborNextScale+=lTranslateOffset; + } + else + { + changed = false; + } + lChangeSamplePoints++; } - if (changed) + if (changed) { - m_DifferentSamplePoints++; + m_DifferentSamplePoints++; } - // add key point - if (accepted) + // add key point + if (accepted) { - std::vector<PixelType> lOrientations = ComputeKeyPointOrientations(neighborCurrentScale, - lScale, - lTranslation[2]); + std::vector<PixelType> lOrientations = ComputeKeyPointOrientations(neighborCurrentScale, + lScale, + lTranslation[2]); - // for each main orientation - for(typename std::vector<PixelType>::iterator orientationIt = lOrientations.begin(); orientationIt != lOrientations.end();++orientationIt) - { + // for each main orientation + for (typename std::vector<PixelType>::iterator orientationIt = lOrientations.begin(); orientationIt != lOrientations.end();++orientationIt) + { - std::vector<PixelType> lDescriptors = ComputeKeyPointDescriptor(neighborCurrentScale, - lScale, - *orientationIt); + std::vector<PixelType> lDescriptors = ComputeKeyPointDescriptor(neighborCurrentScale, + lScale, + *orientationIt); - OutputPointType keyPoint; + OutputPointType keyPoint; - lIterDoG.Get()->TransformIndexToPhysicalPoint(neighborCurrentScale.GetIndex(), - keyPoint); - keyPoint[0] += spacing[0]*lTranslation[0]; - keyPoint[1] += spacing[1]*lTranslation[1]; + lIterDoG.Get()->TransformIndexToPhysicalPoint(neighborCurrentScale.GetIndex(), + keyPoint); + keyPoint[0] += spacing[0]*lTranslation[0]; + keyPoint[1] += spacing[1]*lTranslation[1]; - outputPointSet->SetPoint(m_ValidatedKeyPoints, keyPoint); + outputPointSet->SetPoint(m_ValidatedKeyPoints, keyPoint); - OutputPixelType data; - data.SetSize(128); - // check this, compute scale - // real scale = octave*scale - typename std::vector<PixelType>::const_iterator lIterDescriptor = - lDescriptors.begin(); + OutputPixelType data; + data.SetSize(128); + // check this, compute scale + // real scale = octave*scale + typename std::vector<PixelType>::const_iterator lIterDescriptor = + lDescriptors.begin(); - unsigned int lIndDesc = 0; - while (lIterDescriptor != lDescriptors.end()) - { - data.SetElement(lIndDesc, *lIterDescriptor); - lIndDesc++; - lIterDescriptor++; - } - outputPointSet->SetPointData(m_ValidatedKeyPoints, data); + unsigned int lIndDesc = 0; + while (lIterDescriptor != lDescriptors.end()) + { + data.SetElement(lIndDesc, *lIterDescriptor); + lIndDesc++; + lIterDescriptor++; + } + outputPointSet->SetPointData(m_ValidatedKeyPoints, data); - m_ValidatedKeyPoints++; - } + m_ValidatedKeyPoints++; + } } - } - - ++lIterCurrent; - ++lIterLowerAdjacent; - ++lIterUpperAdjacent; } + ++lIterCurrent; + ++lIterLowerAdjacent; + ++lIterUpperAdjacent; + } + ++lIterDoG; lScale++; } - } } +} + +/** + * Check local extremum for 26 neighbors + */ +template <class TInputImage, class TOutputPointSet> +bool +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::IsLocalExtremum( const NeighborhoodIteratorType& currentScale, + const NeighborhoodIteratorType& previousScale, + const NeighborhoodIteratorType& nextScale) const +{ + bool isMin = currentScale.GetCenterPixel() < currentScale.GetPixel(m_Offsets[0]); + bool isMax = currentScale.GetCenterPixel() > currentScale.GetPixel(m_Offsets[0]); + bool isExtremum = isMin || isMax; + unsigned int lIterOffset = 0; - /** - * Check local extremum for 26 neighbors - */ - template <class TInputImage, class TOutputPointSet> - bool - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::IsLocalExtremum( const NeighborhoodIteratorType& currentScale, - const NeighborhoodIteratorType& previousScale, - const NeighborhoodIteratorType& nextScale) const + while (isExtremum && lIterOffset != 8) { - bool isMin = currentScale.GetCenterPixel() < currentScale.GetPixel(m_Offsets[0]); - bool isMax = currentScale.GetCenterPixel() > currentScale.GetPixel(m_Offsets[0]); - bool isExtremum = isMin || isMax; - unsigned int lIterOffset = 0; - - while (isExtremum && lIterOffset != 8) - { - OffsetType off = m_Offsets[lIterOffset]; - if (isMin) + OffsetType off = m_Offsets[lIterOffset]; + if (isMin) { isExtremum = currentScale.GetCenterPixel() < currentScale.GetPixel(off) && - currentScale.GetCenterPixel() < previousScale.GetPixel(off) && + currentScale.GetCenterPixel() < previousScale.GetPixel(off) && currentScale.GetCenterPixel() < nextScale.GetPixel(off); } - else if (isMax) + else if (isMax) { isExtremum = currentScale.GetCenterPixel() > currentScale.GetPixel(off) && - currentScale.GetCenterPixel() > previousScale.GetPixel(off) && - currentScale.GetCenterPixel() > nextScale.GetPixel(off); + currentScale.GetCenterPixel() > previousScale.GetPixel(off) && + currentScale.GetCenterPixel() > nextScale.GetPixel(off); } - lIterOffset++; - } - if (isExtremum && isMin) - { - isExtremum = - currentScale.GetCenterPixel() < previousScale.GetCenterPixel() && - currentScale.GetCenterPixel() < nextScale.GetCenterPixel(); - } - else if (isExtremum && isMax) - { - isExtremum = - currentScale.GetCenterPixel() > previousScale.GetCenterPixel() && - currentScale.GetCenterPixel() > nextScale.GetCenterPixel(); - } - return isExtremum; + lIterOffset++; } - - /** - * Refine location key point - */ - template <class TInputImage, class TOutputPointSet> - bool - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::RefineLocationKeyPoint( const NeighborhoodIteratorType& currentScale, - const NeighborhoodIteratorType& previousScale, - const NeighborhoodIteratorType& nextScale, - VectorPointType& solution) + if (isExtremum && isMin) { - bool accepted = true; - solution = VectorPointType(PixelType(0)); + isExtremum = + currentScale.GetCenterPixel() < previousScale.GetCenterPixel() && + currentScale.GetCenterPixel() < nextScale.GetCenterPixel(); + } + else if (isExtremum && isMax) + { + isExtremum = + currentScale.GetCenterPixel() > previousScale.GetCenterPixel() && + currentScale.GetCenterPixel() > nextScale.GetCenterPixel(); + } + return isExtremum; +} + +/** + * Refine location key point + */ +template <class TInputImage, class TOutputPointSet> +bool +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::RefineLocationKeyPoint( const NeighborhoodIteratorType& currentScale, + const NeighborhoodIteratorType& previousScale, + const NeighborhoodIteratorType& nextScale, + VectorPointType& solution) +{ + bool accepted = true; + solution = VectorPointType(PixelType(0)); - PixelType dx = 0.5*(currentScale.GetPixel(m_Offsets[6]) - -currentScale.GetPixel(m_Offsets[1]) ); + PixelType dx = 0.5*(currentScale.GetPixel(m_Offsets[6]) + -currentScale.GetPixel(m_Offsets[1]) ); - PixelType dy = 0.5*(currentScale.GetPixel(m_Offsets[4]) - -currentScale.GetPixel(m_Offsets[3]) ); + PixelType dy = 0.5*(currentScale.GetPixel(m_Offsets[4]) + -currentScale.GetPixel(m_Offsets[3]) ); - PixelType ds = 0.5*(nextScale.GetCenterPixel()- - previousScale.GetCenterPixel()); + PixelType ds = 0.5*(nextScale.GetCenterPixel()- + previousScale.GetCenterPixel()); - PixelType dxx = currentScale.GetPixel(m_Offsets[6]) - -2*currentScale.GetCenterPixel() - +currentScale.GetPixel(m_Offsets[1]); + PixelType dxx = currentScale.GetPixel(m_Offsets[6]) + -2*currentScale.GetCenterPixel() + +currentScale.GetPixel(m_Offsets[1]); - PixelType dyy = currentScale.GetPixel(m_Offsets[3]) - -2*currentScale.GetCenterPixel() - +currentScale.GetPixel(m_Offsets[4]); + PixelType dyy = currentScale.GetPixel(m_Offsets[3]) + -2*currentScale.GetCenterPixel() + +currentScale.GetPixel(m_Offsets[4]); - PixelType dss = previousScale.GetCenterPixel() - -2*currentScale.GetCenterPixel() - +nextScale.GetCenterPixel(); + PixelType dss = previousScale.GetCenterPixel() + -2*currentScale.GetCenterPixel() + +nextScale.GetCenterPixel(); - PixelType dxy = 0.25*(currentScale.GetPixel(m_Offsets[7]) - +currentScale.GetPixel(m_Offsets[0]) - -currentScale.GetPixel(m_Offsets[2]) - -currentScale.GetPixel(m_Offsets[5]) ); + PixelType dxy = 0.25*(currentScale.GetPixel(m_Offsets[7]) + +currentScale.GetPixel(m_Offsets[0]) + -currentScale.GetPixel(m_Offsets[2]) + -currentScale.GetPixel(m_Offsets[5]) ); - PixelType dxs = 0.25*(nextScale.GetPixel(m_Offsets[6]) - +previousScale.GetPixel(m_Offsets[1]) - -nextScale.GetPixel(m_Offsets[1]) - -previousScale.GetPixel(m_Offsets[6]) ); + PixelType dxs = 0.25*(nextScale.GetPixel(m_Offsets[6]) + +previousScale.GetPixel(m_Offsets[1]) + -nextScale.GetPixel(m_Offsets[1]) + -previousScale.GetPixel(m_Offsets[6]) ); - PixelType dys = 0.25*(nextScale.GetPixel(m_Offsets[4]) - +previousScale.GetPixel(m_Offsets[3]) - -nextScale.GetPixel(m_Offsets[3]) - -previousScale.GetPixel(m_Offsets[4]) ); + PixelType dys = 0.25*(nextScale.GetPixel(m_Offsets[4]) + +previousScale.GetPixel(m_Offsets[3]) + -nextScale.GetPixel(m_Offsets[3]) + -previousScale.GetPixel(m_Offsets[4]) ); - // Compute matrice determinant - double det = dxx*(dyy*dss-dys*dys) -dxy*(dxy*dss-dxs*dys)+dxs*(dxy*dys-dxs*dyy); + // Compute matrice determinant + double det = dxx*(dyy*dss-dys*dys) -dxy*(dxy*dss-dxs*dys)+dxs*(dxy*dys-dxs*dyy); - // Solve system, compute key point offset - solution[0] = -dx*(dyy*dss-dys*dys)-dy*(dxs*dys-dxy*dss)-ds*(dxy*dys-dyy*dxs); - solution[1] = -dx*(dys*dxs-dss*dxy)-dy*(dxx*dss-dxs*dxs)-ds*(dxs*dxy-dxx*dys); - solution[2] = -dx*(dxy*dys-dxs*dyy)-dy*(dxy*dxs-dxx*dys)-ds*(dxx*dyy-dxy*dxy); + // Solve system, compute key point offset + solution[0] = -dx*(dyy*dss-dys*dys)-dy*(dxs*dys-dxy*dss)-ds*(dxy*dys-dyy*dxs); + solution[1] = -dx*(dys*dxs-dss*dxy)-dy*(dxx*dss-dxs*dxs)-ds*(dxs*dxy-dxx*dys); + solution[2] = -dx*(dxy*dys-dxs*dyy)-dy*(dxy*dxs-dxx*dys)-ds*(dxx*dyy-dxy*dxy); - // Compute interpolated value DoG for lSolution (determinant factor) - PixelType lDoGInterpolated = det*currentScale.GetCenterPixel() + - 0.5*(dx*solution[0]+ - dy*solution[1]+ - ds*solution[2]); + // Compute interpolated value DoG for lSolution (determinant factor) + PixelType lDoGInterpolated = det*currentScale.GetCenterPixel() + + 0.5*(dx*solution[0]+ + dy*solution[1]+ + ds*solution[2]); - PixelType lHessianTrace2 = (dxx+dyy)*(dxx+dyy); - PixelType lHessianDet = dxx*dyy-dxy*dxy; - // DoG threshold + PixelType lHessianTrace2 = (dxx+dyy)*(dxx+dyy); + PixelType lHessianDet = dxx*dyy-dxy*dxy; + // DoG threshold - accepted = fabs(lDoGInterpolated) >= fabs(det*m_DoGThreshold); + accepted = fabs(lDoGInterpolated) >= fabs(det*m_DoGThreshold); - // Eliminating edge response + // Eliminating edge response - accepted = accepted && - fabs(lHessianTrace2) < fabs(m_RatioEdgeThreshold*lHessianDet); + accepted = accepted && + fabs(lHessianTrace2) < fabs(m_RatioEdgeThreshold*lHessianDet); - if (!accepted) - { - m_DiscardedKeyPoints++; - } - if (det < 1e-10f) - { - solution.Fill(0); - } - else - { - // normalize offset with determinant of derivative matrix - solution/=det; - } - return accepted; + if (!accepted) + { + m_DiscardedKeyPoints++; } - - /** - * Compute key point orientation - */ - template <class TInputImage, class TOutputPointSet> - std::vector<typename ImageToSIFTKeyPointSetFilter<TInputImage, TOutputPointSet>::PixelType> - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::ComputeKeyPointOrientations( const NeighborhoodIteratorType& currentScale, - const unsigned int scale, - const PixelType translation) + if (det < 1e-10f) { - // radius of the neighborhood - unsigned int radius = 4; - double lSigma = scale*3; - unsigned int nbBins = 36; - double binWidth = 360./nbBins; - - // initialize the histogram - std::vector<double> lHistogram(nbBins,0.), lSmoothedHistogram(nbBins,0.); - - // Build the region to examine - typename InputImageType::RegionType region; - typename InputImageType::RegionType::SizeType regionSize; - typename InputImageType::RegionType::IndexType regionIndex; - regionSize.Fill(2*radius+2); - region.SetSize(regionSize); - regionIndex[0] = currentScale.GetIndex()[0]-regionSize[0]/2; - regionIndex[1] = currentScale.GetIndex()[1]-regionSize[1]/2; - region.SetIndex(regionIndex); - - if(!region.Crop(m_OrientationList->GetNthElement(scale)->GetLargestPossibleRegion())) - { - itkExceptionMacro(<<"Region "<<region<<" is strictly outside the largest possible region!"); - } + solution.Fill(0); + } + else + { + // normalize offset with determinant of derivative matrix + solution/=det; + } + return accepted; +} + +/** + * Compute key point orientation + */ +template <class TInputImage, class TOutputPointSet> +std::vector<typename ImageToSIFTKeyPointSetFilter<TInputImage, TOutputPointSet>::PixelType> +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::ComputeKeyPointOrientations( const NeighborhoodIteratorType& currentScale, + const unsigned int scale, + const PixelType translation) +{ + // radius of the neighborhood + unsigned int radius = 4; + double lSigma = scale*3; + unsigned int nbBins = 36; + double binWidth = 360./nbBins; + + // initialize the histogram + std::vector<double> lHistogram(nbBins,0.), lSmoothedHistogram(nbBins,0.); + + // Build the region to examine + typename InputImageType::RegionType region; + typename InputImageType::RegionType::SizeType regionSize; + typename InputImageType::RegionType::IndexType regionIndex; + regionSize.Fill(2*radius+2); + region.SetSize(regionSize); + regionIndex[0] = currentScale.GetIndex()[0]-regionSize[0]/2; + regionIndex[1] = currentScale.GetIndex()[1]-regionSize[1]/2; + region.SetIndex(regionIndex); + + if (!region.Crop(m_OrientationList->GetNthElement(scale)->GetLargestPossibleRegion())) + { + itkExceptionMacro(<<"Region "<<region<<" is strictly outside the largest possible region!"); + } - // iterators on the orientation and the magnitude - RegionIteratorType lIterOrientation(m_OrientationList->GetNthElement(scale),region); - RegionIteratorType lIterMagn(m_MagnitudeList->GetNthElement(scale), region); - lIterOrientation.GoToBegin(); - lIterMagn.GoToBegin(); + // iterators on the orientation and the magnitude + RegionIteratorType lIterOrientation(m_OrientationList->GetNthElement(scale),region); + RegionIteratorType lIterMagn(m_MagnitudeList->GetNthElement(scale), region); + lIterOrientation.GoToBegin(); + lIterMagn.GoToBegin(); - // For each pixel - while (!lIterOrientation.IsAtEnd() && !lIterMagn.IsAtEnd()) - { + // For each pixel + while (!lIterOrientation.IsAtEnd() && !lIterMagn.IsAtEnd()) + { - // check if pixel is inside the circle of radius - float dx = lIterMagn.GetIndex()[0]-currentScale.GetIndex()[0]; - float dy = lIterMagn.GetIndex()[1]-currentScale.GetIndex()[1]; - float dist = vcl_sqrt(dx*dx+dy*dy); + // check if pixel is inside the circle of radius + float dx = lIterMagn.GetIndex()[0]-currentScale.GetIndex()[0]; + float dy = lIterMagn.GetIndex()[1]-currentScale.GetIndex()[1]; + float dist = vcl_sqrt(dx*dx+dy*dy); - // If we are in the circle - if(dist<radius) + // If we are in the circle + if (dist<radius) { //Get the values PixelType lOrientation = lIterOrientation.Get(); @@ -604,84 +607,84 @@ namespace otb // Update the histogram value lHistogram[lHistoIndex] += lMagnitude*lWeightMagnitude; } - ++lIterOrientation; - ++lIterMagn; - } + ++lIterOrientation; + ++lIterMagn; + } - // Computing smoothed histogram and looking for the maximum and a second maximum within 80% of the first - double max = 0; - double secondMax = 0; - double sum = 0; - int maxIndex = 0; - int secondMaxIndex = -1; - int j = 0; - int i = 0; - - // Smoothing histogram - for(i=0;i<static_cast<int>(nbBins);++i) - { - sum = 0; - for(j=i-nbBins;j<i;++j) + // Computing smoothed histogram and looking for the maximum and a second maximum within 80% of the first + double max = 0; + double secondMax = 0; + double sum = 0; + int maxIndex = 0; + int secondMaxIndex = -1; + int j = 0; + int i = 0; + + // Smoothing histogram + for (i=0;i<static_cast<int>(nbBins);++i) + { + sum = 0; + for (j=i-nbBins;j<i;++j) { sum+=lHistogram[i-j-1]*m_HistogramGaussianWeights[j+nbBins]; } - lSmoothedHistogram[i]=sum; - } + lSmoothedHistogram[i]=sum; + } - // looking for maximums - for(i=0;i<static_cast<int>(nbBins);++i) - { - if(lSmoothedHistogram[i]>max) + // looking for maximums + for (i=0;i<static_cast<int>(nbBins);++i) + { + if (lSmoothedHistogram[i]>max) { secondMax = max; secondMaxIndex = maxIndex; max=lSmoothedHistogram[i]; maxIndex = i; } - else if(sum > secondMax) + else if (sum > secondMax) { secondMax = lSmoothedHistogram[i]; secondMaxIndex = i; } - } - // This structure will hold the located maximums - std::vector<PixelType> orientations; - - //interpolate orientation maximum - double x1,x2,x3,y1,y2,y3,a,b,num,denom,orientation; - x1 = (maxIndex-1)*binWidth+binWidth/2; - y1 = lSmoothedHistogram[(maxIndex-1)<0 ? maxIndex-1+nbBins : maxIndex-1]; - x2 = (maxIndex)*binWidth+binWidth/2; - y2 = lSmoothedHistogram[maxIndex]; - x3 = (maxIndex+1)*binWidth+binWidth/2; - y3 = lSmoothedHistogram[maxIndex+1>static_cast<int>(nbBins)-1 ? maxIndex+1-nbBins : maxIndex+1]; - - denom = x1*x1*x2 + x2*x2*x3 + x3*x3*x1 - x1*x1*x3 - x2*x2*x1 - x3*x3*x2; - num = y1 * x2 + y2 * x3 + y3 * x1 - y1 * x3 - y2 * x1 - y3 * x2; - - if(denom == 0 || num == 0) - { - // no main orientation, return an empty orientation vector - return orientations; - } + } + // This structure will hold the located maximums + std::vector<PixelType> orientations; + + //interpolate orientation maximum + double x1,x2,x3,y1,y2,y3,a,b,num,denom,orientation; + x1 = (maxIndex-1)*binWidth+binWidth/2; + y1 = lSmoothedHistogram[(maxIndex-1)<0 ? maxIndex-1+nbBins : maxIndex-1]; + x2 = (maxIndex)*binWidth+binWidth/2; + y2 = lSmoothedHistogram[maxIndex]; + x3 = (maxIndex+1)*binWidth+binWidth/2; + y3 = lSmoothedHistogram[maxIndex+1>static_cast<int>(nbBins)-1 ? maxIndex+1-nbBins : maxIndex+1]; + + denom = x1*x1*x2 + x2*x2*x3 + x3*x3*x1 - x1*x1*x3 - x2*x2*x1 - x3*x3*x2; + num = y1 * x2 + y2 * x3 + y3 * x1 - y1 * x3 - y2 * x1 - y3 * x2; + + if (denom == 0 || num == 0) + { + // no main orientation, return an empty orientation vector + return orientations; + } - a = num/denom; - b = ((y1-y2)-a*(x1*x1-x2*x2))/(x1-x2); + a = num/denom; + b = ((y1-y2)-a*(x1*x1-x2*x2))/(x1-x2); - orientation = -b/(2*a); - if(orientation<0) - { - orientation+=360; - } - else if(orientation>=360) - { - orientation-=360; - } + orientation = -b/(2*a); + if (orientation<0) + { + orientation+=360; + } + else if (orientation>=360) + { + orientation-=360; + } // orientations.push_back( static_cast<PixelType>(maxIndex*binWidth + binWidth/2)); - orientations.push_back(static_cast<PixelType>(orientation)); + orientations.push_back(static_cast<PixelType>(orientation)); - // Second peak is disabled, since it seems to confuse the matching procedure. + // Second peak is disabled, since it seems to confuse the matching procedure. // if(secondMaxIndex>=0 && secondMax > 0.8 * max) // { @@ -717,69 +720,69 @@ namespace otb // orientations.push_back(static_cast<PixelType>(orientation)); // } - return orientations; - } - - /** - * Compute key point descriptor - */ - template <class TInputImage, class TOutputPointSet> - std::vector< typename ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::PixelType > - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::ComputeKeyPointDescriptor( const NeighborhoodIteratorType& currentScale, - const unsigned int scale, - const PixelType& orientation) - { - std::vector<PixelType> lHistogram(128, 0.); + return orientations; +} + +/** + * Compute key point descriptor + */ +template <class TInputImage, class TOutputPointSet> +std::vector< typename ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet>::PixelType > +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::ComputeKeyPointDescriptor( const NeighborhoodIteratorType& currentScale, + const unsigned int scale, + const PixelType& orientation) +{ + std::vector<PixelType> lHistogram(128, 0.); - typename InputImageType::RegionType region; - typename InputImageType::RegionType::SizeType regionSize; - typename InputImageType::RegionType::IndexType regionIndex; + typename InputImageType::RegionType region; + typename InputImageType::RegionType::SizeType regionSize; + typename InputImageType::RegionType::IndexType regionIndex; - unsigned int nbHistograms = 4; - unsigned int nbPixelsPerHistogram = 4; - unsigned int nbBinsPerHistogram = 8; + unsigned int nbHistograms = 4; + unsigned int nbPixelsPerHistogram = 4; + unsigned int nbBinsPerHistogram = 8; - float radius = static_cast<float>(nbHistograms/2*nbPixelsPerHistogram); + float radius = static_cast<float>(nbHistograms/2*nbPixelsPerHistogram); // std::cout<<"Radius: "<<radius<<std::endl; - // 4 region of 4 pixels plus 2 pixels of margin - regionSize[0] = nbHistograms*nbPixelsPerHistogram+2; - regionSize[1] = nbHistograms*nbPixelsPerHistogram+2; + // 4 region of 4 pixels plus 2 pixels of margin + regionSize[0] = nbHistograms*nbPixelsPerHistogram+2; + regionSize[1] = nbHistograms*nbPixelsPerHistogram+2; - // sigma set to one half the width of descriptor window - // TODO check this - double lSigma = radius; + // sigma set to one half the width of descriptor window + // TODO check this + double lSigma = radius; - // index - regionSize/2 - regionIndex[0]=currentScale.GetIndex()[0]-regionSize[0]/2; - regionIndex[1]=currentScale.GetIndex()[1]-regionSize[1]/2; + // index - regionSize/2 + regionIndex[0]=currentScale.GetIndex()[0]-regionSize[0]/2; + regionIndex[1]=currentScale.GetIndex()[1]-regionSize[1]/2; - region.SetIndex(regionIndex); - region.SetSize(regionSize); + region.SetIndex(regionIndex); + region.SetSize(regionSize); - // Crop with largest region - if (!region.Crop(m_OrientationList->GetNthElement(scale)->GetLargestPossibleRegion())) - { - itkExceptionMacro(<<"Region "<<region<<" is outside of the largest possible region!"); - } - RegionIteratorType lIterMagnitude(m_MagnitudeList->GetNthElement(scale),region); - RegionIteratorType lIterOrientation(m_OrientationList->GetNthElement(scale),region); - lIterMagnitude.GoToBegin(); - lIterOrientation.GoToBegin(); + // Crop with largest region + if (!region.Crop(m_OrientationList->GetNthElement(scale)->GetLargestPossibleRegion())) + { + itkExceptionMacro(<<"Region "<<region<<" is outside of the largest possible region!"); + } + RegionIteratorType lIterMagnitude(m_MagnitudeList->GetNthElement(scale),region); + RegionIteratorType lIterOrientation(m_OrientationList->GetNthElement(scale),region); + lIterMagnitude.GoToBegin(); + lIterOrientation.GoToBegin(); - // For each pixel in the region - while(!lIterMagnitude.IsAtEnd() && !lIterOrientation.IsAtEnd()) - { - // check if pixel is inside the circle of radius - float dx = lIterMagnitude.GetIndex()[0]-currentScale.GetIndex()[0]; - float dy = lIterMagnitude.GetIndex()[1]-currentScale.GetIndex()[1]; - float dist = vcl_sqrt(dx*dx+dy*dy); + // For each pixel in the region + while (!lIterMagnitude.IsAtEnd() && !lIterOrientation.IsAtEnd()) + { + // check if pixel is inside the circle of radius + float dx = lIterMagnitude.GetIndex()[0]-currentScale.GetIndex()[0]; + float dy = lIterMagnitude.GetIndex()[1]-currentScale.GetIndex()[1]; + float dist = vcl_sqrt(dx*dx+dy*dy); - // If we are in the circle - if(dist<radius) + // If we are in the circle + if (dist<radius) { // rotate the pixel location to compensate sift orientation float angle = orientation*M_PI/180.; @@ -793,14 +796,14 @@ namespace otb // decide to which bin of the histogram the pixel contributes float compensatedOrientation = lIterOrientation.Get()-angle; - if(compensatedOrientation<0) - { - compensatedOrientation+=2*M_PI; - } - if(compensatedOrientation>=2*M_PI) - { - compensatedOrientation-=2*M_PI; - } + if (compensatedOrientation<0) + { + compensatedOrientation+=2*M_PI; + } + if (compensatedOrientation>=2*M_PI) + { + compensatedOrientation-=2*M_PI; + } unsigned int histogramBin = static_cast<unsigned int>(vcl_floor(compensatedOrientation*nbBinsPerHistogram/(2*M_PI))); // Compute the wheight of the pixel in the histogram @@ -808,85 +811,85 @@ namespace otb // Compute the global descriptor index unsigned int descriptorIndex = yHistogramIndex * nbBinsPerHistogram * nbHistograms - + xHistogramIndex * nbBinsPerHistogram + histogramBin; + + xHistogramIndex * nbBinsPerHistogram + histogramBin; lHistogram[descriptorIndex]+=lIterMagnitude.Get()*lWeightMagnitude; } - ++lIterOrientation; - ++lIterMagnitude; - } + ++lIterOrientation; + ++lIterMagnitude; + } - // normalize histogram to unit lenght - typename std::vector<PixelType>::iterator lIterHisto = lHistogram.begin(); - float lNorm = 0.0; + // normalize histogram to unit lenght + typename std::vector<PixelType>::iterator lIterHisto = lHistogram.begin(); + float lNorm = 0.0; - while (lIterHisto != lHistogram.end()) - { - lNorm = lNorm + (*lIterHisto)*(*lIterHisto); - ++lIterHisto; - } - lNorm = vcl_sqrt(lNorm); + while (lIterHisto != lHistogram.end()) + { + lNorm = lNorm + (*lIterHisto)*(*lIterHisto); + ++lIterHisto; + } + lNorm = vcl_sqrt(lNorm); - lIterHisto = lHistogram.begin(); - while(lIterHisto != lHistogram.end()) - { - if (lNorm>0) + lIterHisto = lHistogram.begin(); + while (lIterHisto != lHistogram.end()) + { + if (lNorm>0) { *lIterHisto = (*lIterHisto)/lNorm; } - else + else { *lIterHisto = m_GradientMagnitudeThreshold; } - // threshold gradient magnitude - if (*lIterHisto > m_GradientMagnitudeThreshold) + // threshold gradient magnitude + if (*lIterHisto > m_GradientMagnitudeThreshold) { *lIterHisto = m_GradientMagnitudeThreshold; } - ++lIterHisto; - } - - // renormalize histogram to unit length - lIterHisto = lHistogram.begin(); - lNorm = 0.0; - - while (lIterHisto != lHistogram.end()) - { - lNorm = lNorm + (*lIterHisto)*(*lIterHisto); - ++lIterHisto; - } - lNorm = vcl_sqrt(lNorm); + ++lIterHisto; + } - lIterHisto = lHistogram.begin(); - while(lIterHisto != lHistogram.end()) - { - *lIterHisto = (*lIterHisto)/lNorm; - ++lIterHisto; - } + // renormalize histogram to unit length + lIterHisto = lHistogram.begin(); + lNorm = 0.0; - return lHistogram; + while (lIterHisto != lHistogram.end()) + { + lNorm = lNorm + (*lIterHisto)*(*lIterHisto); + ++lIterHisto; } + lNorm = vcl_sqrt(lNorm); - /** - * PrintSelf Method - */ - template <class TInputImage, class TOutputPointSet> - void - ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + lIterHisto = lHistogram.begin(); + while (lIterHisto != lHistogram.end()) { - typedef typename TOutputPointSet::PointsContainerConstIterator PointsIteratorType; - typedef typename TOutputPointSet::PointDataContainerIterator PointsDataIteratorType; - typedef itk::ProcessObject ProcessObjectType; - const OutputPointSetType* output = dynamic_cast<const OutputPointSetType*>(this->ProcessObjectType::GetOutput(0)); + *lIterHisto = (*lIterHisto)/lNorm; + ++lIterHisto; + } - Superclass::PrintSelf(os, indent); - os<<indent<<"Number of octaves: "<<m_OctavesNumber<<std::endl; - os<<indent<<"Number of scales: "<<m_ScalesNumber<<std::endl; + return lHistogram; +} - os<<indent<<"Number of SIFT key points: " << output->GetNumberOfPoints() << std::endl; - } +/** + * PrintSelf Method + */ +template <class TInputImage, class TOutputPointSet> +void +ImageToSIFTKeyPointSetFilter<TInputImage,TOutputPointSet> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + typedef typename TOutputPointSet::PointsContainerConstIterator PointsIteratorType; + typedef typename TOutputPointSet::PointDataContainerIterator PointsDataIteratorType; + typedef itk::ProcessObject ProcessObjectType; + const OutputPointSetType* output = dynamic_cast<const OutputPointSetType*>(this->ProcessObjectType::GetOutput(0)); + + Superclass::PrintSelf(os, indent); + os<<indent<<"Number of octaves: "<<m_OctavesNumber<<std::endl; + os<<indent<<"Number of scales: "<<m_ScalesNumber<<std::endl; + + os<<indent<<"Number of SIFT key points: " << output->GetNumberOfPoints() << std::endl; +} } // End namespace otb diff --git a/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.h b/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.h index 6e037ab903085ae7217ad95cc2addddad75ca520..018dcfeefa13e641b13ae8971be8ebc6b8b43d7a 100644 --- a/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.h +++ b/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.h @@ -56,168 +56,168 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputImage , class TOutputPointSet> - class ITK_EXPORT ImageToSURFKeyPointSetFilter - : public ImageToPointSetFilter<TInputImage, TOutputPointSet> - { - - public: - - /** Standard class typedefs. */ - typedef ImageToSURFKeyPointSetFilter Self; - typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(ImageToSURFKeyPointSetFilter,ImageToPointSetFilter); - - - /** Template parameters typedefs*/ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef typename InputImageType::IndexType PixelIndex; - typedef typename InputImageType::IndexType IndexType; - typedef typename InputImageType::PixelType PixelValue; - typedef typename InputImageType::SpacingType SpacingType; - typedef typename InputImageType::SizeType SizeType; - typedef typename InputImageType::PointType PointImageType; - - typedef TOutputPointSet OutputPointSetType; - typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; - typedef typename TOutputPointSet::PixelType OutputPixelType; - typedef typename TOutputPointSet::PointType OutputPointType; - typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; - - /** Set/Get the number of Octaves */ - itkSetMacro(OctavesNumber,int); - itkGetMacro(OctavesNumber,int); - - /** Set/Get the number of scales*/ - itkSetMacro(ScalesNumber,int); - itkGetMacro(ScalesNumber,int); - - /** Get the number of KeyPoints detected*/ - itkGetMacro(NumberOfPoints,int); - - /** Internal filters typedefs */ - typedef itk::ConstNeighborhoodIterator<InputImageType> NeighborhoodIteratorType; - typedef typename NeighborhoodIteratorType::NeighborhoodType NeighborhoodType; - - typedef otb::ImageToHessianDeterminantImageFilter<InputImageType ,InputImageType > ImageToDetHessianImageType; - typedef typename ImageToDetHessianImageType::Pointer DetHessianPointerFilter; - - /** Filter for resampling images for the multi-scale analysis */ - typedef itk::ResampleImageFilter<InputImageType,InputImageType> ResampleFilterType; - typedef typename ResampleFilterType::Pointer ResampleFilterPointerType; - - /** ImageList to store the Hessian determinant image at each scale (sigma width)*/ - typedef otb::ImageList< InputImageType > ImageListType; - typedef typename ImageListType::Pointer ImageListTypePointer; - - /** */ - typedef std::vector<double> VectorType; - - protected: - - /** - * Constructor. - */ - ImageToSURFKeyPointSetFilter(); - /** - * Destructor. - */ - virtual ~ImageToSURFKeyPointSetFilter(); - /** - * Standard PrintSelf method. - */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Main computation method. - */ - virtual void GenerateData(); - - - - /** Check local extremum for 8 neighbors (current) - * - * \param currentScale - * - * \return true if the Central pixel is extremum - */ - virtual bool IsLocalExtremum(const NeighborhoodType& neigh); - - - - /** Check local extremum for 8 neighbors (Previous or Scale) - * - * \param neigh - * \paramCenterValue - * - * \return true if the Central pixel is extremum - */ - virtual bool IsLocalExtremumAround(const NeighborhoodType& neigh, - double CenterValue); - - - /** AssignOrientation - * - * \param currentScale neighborhood - * \param scale affected to the keypoint - * - * \return key point orientation - */ - virtual double AssignOrientation(const NeighborhoodType& neigh, - double S); - - /** ComputeDescriptor - * - * \param currentScale Neighboorhood - * \param orientation assigned to the key point - * \param scale - * - * \return hsitogram descriptor - */ - virtual VectorType ComputeDescriptor(const NeighborhoodType& neigh, - double O, - double S); - /** - * Compute min a b c - */ - virtual int GetMin( int a , int b , int c); - - private: - - ImageToSURFKeyPointSetFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Number of octaves */ - int m_OctavesNumber; - - /** Number of scale for each octave */ - int m_ScalesNumber; - - /** Number of key points detected */ - int m_NumberOfPoints; - - /** Those images */ - InputImagePointerType m_determinantImage; - InputImagePointerType m_ImageCurrent; - InputImagePointerType m_ImageMovedPrev; - InputImagePointerType m_ImageMovedNext; - - /** ImageToDeterminantHessianFilter filter */ - DetHessianPointerFilter m_DetHessianFilter; - - /*Resample Filter*/ - ResampleFilterPointerType m_ResampleFilter; - - /** ImageList*/ - ImageListTypePointer m_ImageList; - }; +template <class TInputImage , class TOutputPointSet> +class ITK_EXPORT ImageToSURFKeyPointSetFilter + : public ImageToPointSetFilter<TInputImage, TOutputPointSet> +{ + +public: + + /** Standard class typedefs. */ + typedef ImageToSURFKeyPointSetFilter Self; + typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageToSURFKeyPointSetFilter,ImageToPointSetFilter); + + + /** Template parameters typedefs*/ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef typename InputImageType::IndexType PixelIndex; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::PixelType PixelValue; + typedef typename InputImageType::SpacingType SpacingType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::PointType PointImageType; + + typedef TOutputPointSet OutputPointSetType; + typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; + typedef typename TOutputPointSet::PixelType OutputPixelType; + typedef typename TOutputPointSet::PointType OutputPointType; + typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; + + /** Set/Get the number of Octaves */ + itkSetMacro(OctavesNumber,int); + itkGetMacro(OctavesNumber,int); + + /** Set/Get the number of scales*/ + itkSetMacro(ScalesNumber,int); + itkGetMacro(ScalesNumber,int); + + /** Get the number of KeyPoints detected*/ + itkGetMacro(NumberOfPoints,int); + + /** Internal filters typedefs */ + typedef itk::ConstNeighborhoodIterator<InputImageType> NeighborhoodIteratorType; + typedef typename NeighborhoodIteratorType::NeighborhoodType NeighborhoodType; + + typedef otb::ImageToHessianDeterminantImageFilter<InputImageType ,InputImageType > ImageToDetHessianImageType; + typedef typename ImageToDetHessianImageType::Pointer DetHessianPointerFilter; + + /** Filter for resampling images for the multi-scale analysis */ + typedef itk::ResampleImageFilter<InputImageType,InputImageType> ResampleFilterType; + typedef typename ResampleFilterType::Pointer ResampleFilterPointerType; + + /** ImageList to store the Hessian determinant image at each scale (sigma width)*/ + typedef otb::ImageList< InputImageType > ImageListType; + typedef typename ImageListType::Pointer ImageListTypePointer; + + /** */ + typedef std::vector<double> VectorType; + +protected: + + /** + * Constructor. + */ + ImageToSURFKeyPointSetFilter(); + /** + * Destructor. + */ + virtual ~ImageToSURFKeyPointSetFilter(); + /** + * Standard PrintSelf method. + */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Main computation method. + */ + virtual void GenerateData(); + + + + /** Check local extremum for 8 neighbors (current) + * + * \param currentScale + * + * \return true if the Central pixel is extremum + */ + virtual bool IsLocalExtremum(const NeighborhoodType& neigh); + + + + /** Check local extremum for 8 neighbors (Previous or Scale) + * + * \param neigh + * \paramCenterValue + * + * \return true if the Central pixel is extremum + */ + virtual bool IsLocalExtremumAround(const NeighborhoodType& neigh, + double CenterValue); + + + /** AssignOrientation + * + * \param currentScale neighborhood + * \param scale affected to the keypoint + * + * \return key point orientation + */ + virtual double AssignOrientation(const NeighborhoodType& neigh, + double S); + + /** ComputeDescriptor + * + * \param currentScale Neighboorhood + * \param orientation assigned to the key point + * \param scale + * + * \return hsitogram descriptor + */ + virtual VectorType ComputeDescriptor(const NeighborhoodType& neigh, + double O, + double S); + /** + * Compute min a b c + */ + virtual int GetMin( int a , int b , int c); + +private: + + ImageToSURFKeyPointSetFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Number of octaves */ + int m_OctavesNumber; + + /** Number of scale for each octave */ + int m_ScalesNumber; + + /** Number of key points detected */ + int m_NumberOfPoints; + + /** Those images */ + InputImagePointerType m_determinantImage; + InputImagePointerType m_ImageCurrent; + InputImagePointerType m_ImageMovedPrev; + InputImagePointerType m_ImageMovedNext; + + /** ImageToDeterminantHessianFilter filter */ + DetHessianPointerFilter m_DetHessianFilter; + + /*Resample Filter*/ + ResampleFilterPointerType m_ResampleFilter; + + /** ImageList*/ + ImageListTypePointer m_ImageList; +}; } #ifndef OTB_MANUAL_INSTANTIATION #include "otbImageToSURFKeyPointSetFilter.txx" diff --git a/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.txx b/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.txx index df02996f28e95bd25b15ec22c6ada22c83504ca7..6d9b45aa205ab858228db126efac565e330925df 100644 --- a/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.txx +++ b/Code/FeatureExtraction/otbImageToSURFKeyPointSetFilter.txx @@ -23,496 +23,519 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /**--------------------------------------------------------- - * Constructor - ----------------------------------------------------------*/ - template < class TInputImage, class TOutputPointSet > - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet > - ::ImageToSURFKeyPointSetFilter() - { - m_OctavesNumber = 1; - m_ScalesNumber = 3; - m_NumberOfPoints = 0; - m_DetHessianFilter = ImageToDetHessianImageType::New(); - } +/**--------------------------------------------------------- + * Constructor + ----------------------------------------------------------*/ +template < class TInputImage, class TOutputPointSet > +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet > +::ImageToSURFKeyPointSetFilter() +{ + m_OctavesNumber = 1; + m_ScalesNumber = 3; + m_NumberOfPoints = 0; + m_DetHessianFilter = ImageToDetHessianImageType::New(); +} - /*--------------------------------------------------------- - * Destructor.c - ----------------------------------------------------------*/ +/*--------------------------------------------------------- + * Destructor.c + ----------------------------------------------------------*/ - template <class TInputImage, class TOutputPointSet> - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::~ImageToSURFKeyPointSetFilter() - {} +template <class TInputImage, class TOutputPointSet> +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::~ImageToSURFKeyPointSetFilter() +{} - /*------------------------------------------------------- - * Generate Data - --------------------------------------------------------*/ - template <class TInputImage, class TOutputPointSet> - void - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::GenerateData(void) - { +/*------------------------------------------------------- + * Generate Data + --------------------------------------------------------*/ +template <class TInputImage, class TOutputPointSet> +void +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::GenerateData(void) +{ - double k; - double sigma_in = 2.; - SizeType radius; + double k; + double sigma_in = 2.; + SizeType radius; - /*Output*/ - OutputPointSetPointerType outputPointSet = this->GetOutput(); + /*Output*/ + OutputPointSetPointerType outputPointSet = this->GetOutput(); - /** Computing the multiplicative factor for scales iteration - * scalar used for the wifth of the gaussian - */ - if(m_ScalesNumber > 1 ) - k = (double)std::pow(2.0,(double)(1/(double)(m_ScalesNumber-1))); - else - k = 3; + /** Computing the multiplicative factor for scales iteration + * scalar used for the wifth of the gaussian + */ + if (m_ScalesNumber > 1 ) + k = (double)std::pow(2.0,(double)(1/(double)(m_ScalesNumber-1))); + else + k = 3; - /* Computation loop over octaves*/ - for (int i = 0; i < m_OctavesNumber; i++ ){ + /* Computation loop over octaves*/ + for (int i = 0; i < m_OctavesNumber; i++ ) + { - sigma_in = 2.; - m_ImageList = ImageListType::New(); + sigma_in = 2.; + m_ImageList = ImageListType::New(); - /*-------------------------------------------------------- - Octave per octave - --------------------------------------------------------*/ - if(i>0) { + /*-------------------------------------------------------- + Octave per octave + --------------------------------------------------------*/ + if (i>0) + { - m_ResampleFilter = ResampleFilterType::New(); - m_ResampleFilter ->SetInput(this->GetInput()); + m_ResampleFilter = ResampleFilterType::New(); + m_ResampleFilter ->SetInput(this->GetInput()); - SizeType size = this->GetInput()->GetLargestPossibleRegion().GetSize(); - for (int k = 0; k < 2; ++k) - size[k] = (unsigned int) floor(size[k]/std::pow(2.0,i) ); - m_ResampleFilter->SetSize( size ); + SizeType size = this->GetInput()->GetLargestPossibleRegion().GetSize(); + for (int k = 0; k < 2; ++k) + size[k] = (unsigned int) floor(size[k]/std::pow(2.0,i) ); + m_ResampleFilter->SetSize( size ); - SpacingType spacing = this->GetInput()->GetSpacing(); - for (int k = 0; k < 2; ++k) - spacing[k] = (spacing[k] * std::pow(2.0,i)); - m_ResampleFilter->SetOutputSpacing( spacing ); + SpacingType spacing = this->GetInput()->GetSpacing(); + for (int k = 0; k < 2; ++k) + spacing[k] = (spacing[k] * std::pow(2.0,i)); + m_ResampleFilter->SetOutputSpacing( spacing ); - m_ResampleFilter->SetDefaultPixelValue( 0 ); - m_ResampleFilter->Update(); - m_determinantImage = m_ResampleFilter->GetOutput(); + m_ResampleFilter->SetDefaultPixelValue( 0 ); + m_ResampleFilter->Update(); + m_determinantImage = m_ResampleFilter->GetOutput(); - otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Size of the image at the octave : " \ - << i << " is " \ - <<m_determinantImage->GetLargestPossibleRegion().GetSize() ); + otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Size of the image at the octave : " \ + << i << " is " \ + <<m_determinantImage->GetLargestPossibleRegion().GetSize() ); - } + } - for (int j = 0; j < m_ScalesNumber; j++ ) - { - /** Incrementation of the gaussian width - * the width of the gaussian have to be doubled for - * each iteration over octaves - */ + for (int j = 0; j < m_ScalesNumber; j++ ) + { + /** Incrementation of the gaussian width + * the width of the gaussian have to be doubled for + * each iteration over octaves + */ - if ((i != 0 && j !=0 ) || (i == 0 && (i+j !=0) ) || ( m_ScalesNumber == 1 && i!=0 )) - sigma_in *= k; + if ((i != 0 && j !=0 ) || (i == 0 && (i+j !=0) ) || ( m_ScalesNumber == 1 && i!=0 )) + sigma_in *= k; - /** - * For each octave, we serach for the key points - */ + /** + * For each octave, we serach for the key points + */ - /** Hessian Determinant Image */ - m_DetHessianFilter = ImageToDetHessianImageType::New(); + /** Hessian Determinant Image */ + m_DetHessianFilter = ImageToDetHessianImageType::New(); - if ( i == 0 )m_DetHessianFilter->SetInput(this->GetInput()); - else m_DetHessianFilter->SetInput(m_determinantImage ); + if ( i == 0 )m_DetHessianFilter->SetInput(this->GetInput()); + else m_DetHessianFilter->SetInput(m_determinantImage ); - m_DetHessianFilter->SetSigma(sigma_in); - m_DetHessianFilter->Update(); - m_determinantImage = m_DetHessianFilter->GetOutput(); + m_DetHessianFilter->SetSigma(sigma_in); + m_DetHessianFilter->Update(); + m_determinantImage = m_DetHessianFilter->GetOutput(); - if(i+j==0) - { - otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Size of the image at the octave : " - << i << " is " - <<m_determinantImage->GetLargestPossibleRegion().GetSize() ); - } + if (i+j==0) + { + otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Size of the image at the octave : " + << i << " is " + <<m_determinantImage->GetLargestPossibleRegion().GetSize() ); + } - /** For each octave, we fill the imageList for the extremum search*/ - m_ImageList->PushBack(m_determinantImage); + /** For each octave, we fill the imageList for the extremum search*/ + m_ImageList->PushBack(m_determinantImage); } - /*----------------------------------------------------*/ - /* extremum Search over octave's scales */ - /*----------------------------------------------------*/ + /*----------------------------------------------------*/ + /* extremum Search over octave's scales */ + /*----------------------------------------------------*/ - for (int jj = 1; jj < (int)(m_ImageList->Size() - 1 ); jj++) - { - m_ImageCurrent = m_ImageList->GetNthElement(jj); - m_ImageMovedPrev = m_ImageList->GetNthElement(jj-1); - m_ImageMovedNext = m_ImageList->GetNthElement(jj+1); + for (int jj = 1; jj < (int)(m_ImageList->Size() - 1 ); jj++) + { + m_ImageCurrent = m_ImageList->GetNthElement(jj); + m_ImageMovedPrev = m_ImageList->GetNthElement(jj-1); + m_ImageMovedNext = m_ImageList->GetNthElement(jj+1); - /** NeighboorhoodIterator parameters*/ - radius.Fill(1); - NeighborhoodIteratorType it(radius, m_ImageCurrent,m_ImageCurrent->GetLargestPossibleRegion()); - it.GoToBegin(); + /** NeighboorhoodIterator parameters*/ + radius.Fill(1); + NeighborhoodIteratorType it(radius, m_ImageCurrent,m_ImageCurrent->GetLargestPossibleRegion()); + it.GoToBegin(); - /* NeighboorhoodIterator Adjacents parameters*/ - NeighborhoodIteratorType itNeighPrev(radius, m_ImageMovedPrev,m_ImageMovedPrev->GetLargestPossibleRegion()); - itNeighPrev.GoToBegin(); + /* NeighboorhoodIterator Adjacents parameters*/ + NeighborhoodIteratorType itNeighPrev(radius, m_ImageMovedPrev,m_ImageMovedPrev->GetLargestPossibleRegion()); + itNeighPrev.GoToBegin(); - NeighborhoodIteratorType itNeighNext(radius, m_ImageMovedNext,m_ImageMovedNext->GetLargestPossibleRegion()); - itNeighNext.GoToBegin(); + NeighborhoodIteratorType itNeighNext(radius, m_ImageMovedNext,m_ImageMovedNext->GetLargestPossibleRegion()); + itNeighNext.GoToBegin(); - while(!it.IsAtEnd()) + while (!it.IsAtEnd()) { - if(IsLocalExtremum(it.GetNeighborhood()) - && IsLocalExtremumAround(itNeighPrev.GetNeighborhood(),m_ImageCurrent->GetPixel(it.GetIndex())) - && IsLocalExtremumAround(itNeighNext.GetNeighborhood(),m_ImageCurrent->GetPixel(it.GetIndex())) ) - { - OutputPointType keyPoint; - itNeighPrev.SetLocation(it.GetIndex()); - itNeighNext.SetLocation(it.GetIndex()); + if (IsLocalExtremum(it.GetNeighborhood()) + && IsLocalExtremumAround(itNeighPrev.GetNeighborhood(),m_ImageCurrent->GetPixel(it.GetIndex())) + && IsLocalExtremumAround(itNeighNext.GetNeighborhood(),m_ImageCurrent->GetPixel(it.GetIndex())) ) + { + OutputPointType keyPoint; + itNeighPrev.SetLocation(it.GetIndex()); + itNeighNext.SetLocation(it.GetIndex()); - keyPoint[0] = it.GetIndex()[0]; - keyPoint[1] = it.GetIndex()[1]; + keyPoint[0] = it.GetIndex()[0]; + keyPoint[1] = it.GetIndex()[1]; - //keyPoint[2] = sigma_in/pow(k,(double)jj)*pow(2.,(double)i); - double sigmaDetected = sigma_in/pow(k,(double)jj)*pow(2.,(double)i); + //keyPoint[2] = sigma_in/pow(k,(double)jj)*pow(2.,(double)i); + double sigmaDetected = sigma_in/pow(k,(double)jj)*pow(2.,(double)i); - radius.Fill(GetMin((int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[0] - keyPoint[0]), - (int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[1] - keyPoint[1]), - (int)(6*sigmaDetected) ) ); // changer le sigma detected par keypoint[2] + radius.Fill(GetMin((int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[0] - keyPoint[0]), + (int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[1] - keyPoint[1]), + (int)(6*sigmaDetected) ) ); // changer le sigma detected par keypoint[2] - /* - Computing the orientation of the key point detected - */ - NeighborhoodIteratorType itNeighOrientation(radius,this->GetInput() , - this->GetInput()->GetLargestPossibleRegion()); + /* + Computing the orientation of the key point detected + */ + NeighborhoodIteratorType itNeighOrientation(radius,this->GetInput() , + this->GetInput()->GetLargestPossibleRegion()); - itNeighOrientation.SetLocation(it.GetIndex()); + itNeighOrientation.SetLocation(it.GetIndex()); - /** TO DO*/ - //keyPoint[3] = AssignOrientation( itNeighOrientation.GetNeighborhood() ,keyPoint[2] ); - double orientationDetected = AssignOrientation( itNeighOrientation.GetNeighborhood() , sigmaDetected ); + /** TO DO*/ + //keyPoint[3] = AssignOrientation( itNeighOrientation.GetNeighborhood() ,keyPoint[2] ); + double orientationDetected = AssignOrientation( itNeighOrientation.GetNeighborhood() , sigmaDetected ); - /*Filling the Point pointSet Part*/ - outputPointSet->SetPoint(m_NumberOfPoints, keyPoint); + /*Filling the Point pointSet Part*/ + outputPointSet->SetPoint(m_NumberOfPoints, keyPoint); - /*----------------------------------------*/ - /* Descriptor Computation */ - /*----------------------------------------*/ + /*----------------------------------------*/ + /* Descriptor Computation */ + /*----------------------------------------*/ - radius.Fill(GetMin((int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[0] - keyPoint[0]), - (int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[1] - keyPoint[1]), - (int)(10*sigmaDetected))); // TODO a changer sigmaDetected par Keypoint[2] + radius.Fill(GetMin((int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[0] - keyPoint[0]), + (int)(this->GetInput()->GetLargestPossibleRegion().GetSize()[1] - keyPoint[1]), + (int)(10*sigmaDetected))); // TODO a changer sigmaDetected par Keypoint[2] - NeighborhoodIteratorType itNeighDescriptor(radius,this->GetInput(), - this->GetInput()->GetLargestPossibleRegion()); - itNeighDescriptor.SetLocation(it.GetIndex()); - VectorType descriptor; - descriptor.resize(64); - //descriptor = ComputeDescriptor(itNeighDescriptor.GetNeighborhood(),keyPoint[3],keyPoint[2]); - descriptor = ComputeDescriptor(itNeighDescriptor.GetNeighborhood(),orientationDetected,sigmaDetected); + NeighborhoodIteratorType itNeighDescriptor(radius,this->GetInput(), + this->GetInput()->GetLargestPossibleRegion()); + itNeighDescriptor.SetLocation(it.GetIndex()); + VectorType descriptor; + descriptor.resize(64); + //descriptor = ComputeDescriptor(itNeighDescriptor.GetNeighborhood(),keyPoint[3],keyPoint[2]); + descriptor = ComputeDescriptor(itNeighDescriptor.GetNeighborhood(),orientationDetected,sigmaDetected); - /*Updating the pointset data with values of the descriptor*/ - OutputPixelType data; - data.SetSize(64); + /*Updating the pointset data with values of the descriptor*/ + OutputPixelType data; + data.SetSize(64); - unsigned int IndDescriptor = 0; + unsigned int IndDescriptor = 0; - typename std::vector<double>::const_iterator itDescriptor = - descriptor.begin(); + typename std::vector<double>::const_iterator itDescriptor = + descriptor.begin(); - while(itDescriptor != descriptor.end()) - { - data.SetElement(IndDescriptor, *itDescriptor); - IndDescriptor++; - itDescriptor++; - } - outputPointSet->SetPointData(m_NumberOfPoints, data); + while (itDescriptor != descriptor.end()) + { + data.SetElement(IndDescriptor, *itDescriptor); + IndDescriptor++; + itDescriptor++; + } + outputPointSet->SetPointData(m_NumberOfPoints, data); - m_NumberOfPoints++; - } + m_NumberOfPoints++; + } ++it; ++itNeighPrev; ++itNeighNext; }/*End while for extremum search*/ - } /*End Iteration over scales */ + } /*End Iteration over scales */ - m_ImageList->Clear(); + m_ImageList->Clear(); - } /* End Key Points search*/ + } /* End Key Points search*/ - otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Total Number of Key points "\ - << m_NumberOfPoints ); + otbGenericMsgDebugMacro( <<"ImageToSURFKeyPointSetFilter:: Total Number of Key points "\ + << m_NumberOfPoints ); - }/** End of GenerateData()*/ +}/** End of GenerateData()*/ - template <class TInputImage, class TOutputPointSet> - int - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::GetMin( int a , int b , int c) - { - return std::min(a,std::min(b,c)); - } +template <class TInputImage, class TOutputPointSet> +int +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::GetMin( int a , int b , int c) +{ + return std::min(a,std::min(b,c)); +} + +/*----------------------------------------------------------- + * Find Local Extremum + -----------------------------------------------------------*/ +template <class TInputImage, class TOutputPointSet> +bool +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::IsLocalExtremum(const NeighborhoodType& neigh) +{ + int centerIndex = neigh.GetCenterNeighborhoodIndex(), i = 0; + double centerValue = neigh[centerIndex]; + bool max = false, min = false; + int flag_min = 0, flag_max = 0; - /*----------------------------------------------------------- - * Find Local Extremum - -----------------------------------------------------------*/ - template <class TInputImage, class TOutputPointSet> - bool - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::IsLocalExtremum(const NeighborhoodType& neigh) + while (i!=(int)neigh.Size()) { - int centerIndex = neigh.GetCenterNeighborhoodIndex(), i = 0; - double centerValue = neigh[centerIndex]; - bool max = false, min = false; - int flag_min = 0, flag_max = 0; - - while (i!=(int)neigh.Size()){ - if(i != centerIndex ){ - if( centerValue> neigh[i] && flag_max == 0) max = true; - else { max = false; flag_max = 1; } - - if(centerValue < neigh[i] && flag_min == 0 && centerValue <0) min = true; - else { min = false; flag_min = 1; } + if (i != centerIndex ) + { + if ( centerValue> neigh[i] && flag_max == 0) max = true; + else + { + max = false; + flag_max = 1; } - ++i; - } - return max || min; + if (centerValue < neigh[i] && flag_min == 0 && centerValue <0) min = true; + else + { + min = false; + flag_min = 1; + } + } + ++i; } - /*----------------------------------------------------------- - *Find Local Extremum Around - -----------------------------------------------------------*/ - template <class TInputImage, class TOutputPointSet> - bool - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::IsLocalExtremumAround(const NeighborhoodType& neigh , double CenterValue) - { + return max || min; +} - int i = 0; - bool max = false, min = false; - int flag_min = 0, flag_max = 0; +/*----------------------------------------------------------- + *Find Local Extremum Around + -----------------------------------------------------------*/ +template <class TInputImage, class TOutputPointSet> +bool +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::IsLocalExtremumAround(const NeighborhoodType& neigh , double CenterValue) +{ - while (i!=(int)neigh.Size()){ + int i = 0; + bool max = false, min = false; + int flag_min = 0, flag_max = 0; - if( CenterValue> neigh[i] && flag_max == 0) max = true; - else { max = false; flag_max = 1; } + while (i!=(int)neigh.Size()) + { - if(CenterValue < neigh[i] && flag_min == 0) min = true; - else { min = false; flag_min = 1; } + if ( CenterValue> neigh[i] && flag_max == 0) max = true; + else + { + max = false; + flag_max = 1; + } - ++i; + if (CenterValue < neigh[i] && flag_min == 0) min = true; + else + { + min = false; + flag_min = 1; } - return max || min; + ++i; } - /*----------------------------------------------------------- - * Compute the orientation of The KeyPoint - -----------------------------------------------------------*/ + return max || min; +} - template <class TInputImage, class TOutputPointSet> - double - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::AssignOrientation(const NeighborhoodType& neigh , double S) - { +/*----------------------------------------------------------- + * Compute the orientation of The KeyPoint + -----------------------------------------------------------*/ - int i= 0; - int pas =( (i+S)-(int)(i+S) > 0.5 )?((int)S+1):(int)S; - int Largeur = 2*neigh.GetRadius()[0]+1; // Width & length of a neighborhood - int rayon = neigh.GetRadius()[0]; // radius of the neigh - int col, raw; - double dist; - double w; // weight of the circular gaussian - - OutputPointType pt; - - // Gradient orientation histogram - double angle; - int bin = 0; - int Pi = 180; - int LengthBin = 60; - int NbBins = (2*Pi/LengthBin); - std::vector<double> tab(NbBins*2 , 0.); - - while (i < (int)neigh.Size()) - { - col = i%Largeur - rayon; - raw = i/Largeur - rayon; - dist = vcl_sqrt(static_cast<double>(col *col + raw * raw) ); - col +=rayon; - raw +=rayon; // Backup to the image coordinate axes +template <class TInputImage, class TOutputPointSet> +double +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::AssignOrientation(const NeighborhoodType& neigh , double S) +{ - if(dist < 6*S) + int i= 0; + int pas =( (i+S)-(int)(i+S) > 0.5 )?((int)S+1):(int)S; + int Largeur = 2*neigh.GetRadius()[0]+1; // Width & length of a neighborhood + int rayon = neigh.GetRadius()[0]; // radius of the neigh + int col, raw; + double dist; + double w; // weight of the circular gaussian + + OutputPointType pt; + + // Gradient orientation histogram + double angle; + int bin = 0; + int Pi = 180; + int LengthBin = 60; + int NbBins = (2*Pi/LengthBin); + std::vector<double> tab(NbBins*2 , 0.); + + while (i < (int)neigh.Size()) { - // Haar Wavelets responses accumulated in an histogram with Pi/3 precison - if (( col > pas && col < Largeur - pas ) && ( raw > pas && raw < Largeur - pas) ) - { - - w = vcl_exp(-((col-rayon)*(col-rayon) + (raw-rayon)*(raw-rayon))/(2*2.5*2.5*S*S) ); - pt[0] = (neigh[(col+pas) + raw * Largeur] - neigh[(col-pas) + raw *Largeur ]) * w; - pt[1] = (neigh[col + (raw+pas)* Largeur ] - neigh[col + (raw-pas)*Largeur]) * w; + col = i%Largeur - rayon; + raw = i/Largeur - rayon; + dist = vcl_sqrt(static_cast<double>(col *col + raw * raw) ); + col +=rayon; + raw +=rayon; // Backup to the image coordinate axes - if (pt[0] + pt[1] != 0) + if (dist < 6*S) + { + // Haar Wavelets responses accumulated in an histogram with Pi/3 precison + if (( col > pas && col < Largeur - pas ) && ( raw > pas && raw < Largeur - pas) ) { - angle = atan( pt[0]/pt[1] )*( Pi/M_PI); - if(angle < 0 ) - angle += 2*Pi; - bin = (int)(angle/LengthBin); + w = vcl_exp(-((col-rayon)*(col-rayon) + (raw-rayon)*(raw-rayon))/(2*2.5*2.5*S*S) ); + pt[0] = (neigh[(col+pas) + raw * Largeur] - neigh[(col-pas) + raw *Largeur ]) * w; + pt[1] = (neigh[col + (raw+pas)* Largeur ] - neigh[col + (raw-pas)*Largeur]) * w; - if( bin <= NbBins-1 || bin >= 0 ) + if (pt[0] + pt[1] != 0) { - tab[2*bin] += pt[0]; - tab[2*bin+1] += pt[1]; + angle = atan( pt[0]/pt[1] )*( Pi/M_PI); + if (angle < 0 ) + angle += 2*Pi; + + bin = (int)(angle/LengthBin); + + if ( bin <= NbBins-1 || bin >= 0 ) + { + tab[2*bin] += pt[0]; + tab[2*bin+1] += pt[1]; + } } } } + i+= pas; } - i+= pas; - } - //Find Orientation - double indice = 0; - double max = 0; - double length = 0; - - //Detection de l'orientation du point courant - for (int i = 0; i < NbBins*2; i = i+2){ - length = vcl_sqrt( tab[i]*tab[i] + tab[i+1]*tab[i+1] ); - if( length > max){ - max = length; - indice = i/2; - } - } + //Find Orientation + double indice = 0; + double max = 0; + double length = 0; - return (indice+0.5)*LengthBin; + //Detection de l'orientation du point courant + for (int i = 0; i < NbBins*2; i = i+2) + { + length = vcl_sqrt( tab[i]*tab[i] + tab[i+1]*tab[i+1] ); + if ( length > max) + { + max = length; + indice = i/2; + } } - /*----------------------------------------------------------- - * Compute the descriptor of The KeyPoint - -----------------------------------------------------------*/ + return (indice+0.5)*LengthBin; +} - template <class TInputImage, class TOutputPointSet> - typename ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::VectorType - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::ComputeDescriptor(const NeighborhoodType& neigh , double O , double S ) - { +/*----------------------------------------------------------- + * Compute the descriptor of The KeyPoint + -----------------------------------------------------------*/ - typedef itk::CenteredRigid2DTransform<double> TransformType; - TransformType::Pointer eulerTransform = TransformType::New(); - TransformType::ParametersType ParamVec(5); - PointImageType pSrc , pDst; - double angle = O * M_PI / 180; +template <class TInputImage, class TOutputPointSet> +typename ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::VectorType +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::ComputeDescriptor(const NeighborhoodType& neigh , double O , double S ) +{ + typedef itk::CenteredRigid2DTransform<double> TransformType; + TransformType::Pointer eulerTransform = TransformType::New(); + TransformType::ParametersType ParamVec(5); + PointImageType pSrc , pDst; + double angle = O * M_PI / 180; - int i = 0, col, raw , Nbin, pas = 1; - double xx = 0, yy = 0; - double dx, dy , w; - int Largeur = 2*neigh.GetRadius()[0]+1; - double rayon = static_cast<double>(Largeur)/4.; - double r = neigh.GetRadius()[0]; - double dist = 0; - double x0 = neigh.GetCenterNeighborhoodIndex()% Largeur; - double y0 = neigh.GetCenterNeighborhoodIndex()/ Largeur; - //std::cout << " x0 " << x0 << " y0 " << y0 << angle << std::endl; + int i = 0, col, raw , Nbin, pas = 1; + double xx = 0, yy = 0; + double dx, dy , w; + int Largeur = 2*neigh.GetRadius()[0]+1; + double rayon = static_cast<double>(Largeur)/4.; + double r = neigh.GetRadius()[0]; + double dist = 0; + double x0 = neigh.GetCenterNeighborhoodIndex()% Largeur; + double y0 = neigh.GetCenterNeighborhoodIndex()/ Largeur; - VectorType descriptorVector; - descriptorVector.resize(64); + //std::cout << " x0 " << x0 << " y0 " << y0 << angle << std::endl; - /** Parameters of the transformation*/ - ParamVec[0] = angle; - ParamVec[1] = x0; - ParamVec[2] = y0; - ParamVec[3] = 0; - ParamVec[4] = 0; - eulerTransform->SetParameters(ParamVec); + VectorType descriptorVector; + descriptorVector.resize(64); - while (i < (int)neigh.Size()) - { - col = i % Largeur; - raw = i / Largeur; + /** Parameters of the transformation*/ + ParamVec[0] = angle; + ParamVec[1] = x0; + ParamVec[2] = y0; + ParamVec[3] = 0; + ParamVec[4] = 0; + eulerTransform->SetParameters(ParamVec); - if (( col > pas && col < Largeur - pas ) && ( raw > pas && raw < Largeur - pas) ) + while (i < (int)neigh.Size()) + { + col = i % Largeur; + raw = i / Largeur; + + if (( col > pas && col < Largeur - pas ) && ( raw > pas && raw < Largeur - pas) ) { double distanceX = (raw-r); double distanceY = (col-r); dist = vcl_sqrt(distanceX*distanceX + distanceY*distanceY); - if(dist <= r ) - { - /* Transform point to compensate the rotation the orientation */ - pDst[0] = col; - pDst[1] = raw; - pSrc = eulerTransform->TransformPoint(pDst); + if (dist <= r ) + { + /* Transform point to compensate the rotation the orientation */ + pDst[0] = col; + pDst[1] = raw; + pSrc = eulerTransform->TransformPoint(pDst); - /** New Coordinates (rotated) */ - col = static_cast<int>(vcl_floor(pSrc[0])); - raw = static_cast<int>(vcl_floor(pSrc[1])); + /** New Coordinates (rotated) */ + col = static_cast<int>(vcl_floor(pSrc[0])); + raw = static_cast<int>(vcl_floor(pSrc[1])); - if(raw==0) raw =+1; - if(col ==0) col +=1; + if (raw==0) raw =+1; + if (col ==0) col +=1; - xx = static_cast<int> (pSrc[1]/rayon); - yy = static_cast<int> (pSrc[0]/rayon); - Nbin = static_cast<int> (xx + 4*yy); + xx = static_cast<int> (pSrc[1]/rayon); + yy = static_cast<int> (pSrc[0]/rayon); + Nbin = static_cast<int> (xx + 4*yy); - if( Nbin < 16) //because 64 descriptor length - { - double distanceXcompensee_2 = (pSrc[0] - r)*(pSrc[0] - r); - double distanceYcompensee_2 = (pSrc[1] - r)*(pSrc[1] - r); + if ( Nbin < 16) //because 64 descriptor length + { + double distanceXcompensee_2 = (pSrc[0] - r)*(pSrc[0] - r); + double distanceYcompensee_2 = (pSrc[1] - r)*(pSrc[1] - r); - w = vcl_exp(-( distanceXcompensee_2 + distanceYcompensee_2 ) / (2*3.3*3.3*S*S) ); + w = vcl_exp(-( distanceXcompensee_2 + distanceYcompensee_2 ) / (2*3.3*3.3*S*S) ); - dx = 0.5 * (neigh[(col+pas) + raw * Largeur] - neigh[(col-pas) + raw *Largeur]) * w; - dy = 0.5 * (neigh[col + (raw+ pas)* Largeur] - neigh[col + (raw-pas)*Largeur]) * w; + dx = 0.5 * (neigh[(col+pas) + raw * Largeur] - neigh[(col-pas) + raw *Largeur]) * w; + dy = 0.5 * (neigh[col + (raw+ pas)* Largeur] - neigh[col + (raw-pas)*Largeur]) * w; - descriptorVector[4*Nbin ] += dx; - descriptorVector[4*Nbin+1] += dy; - descriptorVector[4*Nbin+2] += vcl_abs(dx); - descriptorVector[4*Nbin+3] += vcl_abs(dy); - } + descriptorVector[4*Nbin ] += dx; + descriptorVector[4*Nbin+1] += dy; + descriptorVector[4*Nbin+2] += vcl_abs(dx); + descriptorVector[4*Nbin+3] += vcl_abs(dy); } - } - i++; } + } + i++; + } - double accu = 0; - for (int i = 0; i < 64; i++) - accu += descriptorVector[i]*descriptorVector[i]; + double accu = 0; + for (int i = 0; i < 64; i++) + accu += descriptorVector[i]*descriptorVector[i]; - for (int j = 0; j < 64; j++) - descriptorVector[j] /= vcl_sqrt(accu); + for (int j = 0; j < 64; j++) + descriptorVector[j] /= vcl_sqrt(accu); - return descriptorVector; + return descriptorVector; - } +} - /*---------------------------------------------------------------- - PrintSelf - -----------------------------------------------------------------*/ - template <class TInputImage, class TOutputPointSet > - void - ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "Number of Key Points " << m_NumberOfPoints << std::endl; - } +/*---------------------------------------------------------------- + PrintSelf + -----------------------------------------------------------------*/ +template <class TInputImage, class TOutputPointSet > +void +ImageToSURFKeyPointSetFilter< TInputImage, TOutputPointSet> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Number of Key Points " << m_NumberOfPoints << std::endl; +} } diff --git a/Code/FeatureExtraction/otbImageToTreeFilter.txx b/Code/FeatureExtraction/otbImageToTreeFilter.txx index 71c0bfc2bc911587afbb877986861d65a929155f..3a617c920ee12aee33b0648bef4350f8ff039f66 100644 --- a/Code/FeatureExtraction/otbImageToTreeFilter.txx +++ b/Code/FeatureExtraction/otbImageToTreeFilter.txx @@ -34,7 +34,7 @@ ImageToTreeFilter<TInputImage,TOutputTree> this->itk::ProcessObject::SetNumberOfRequiredInputs(1); OutputTreePointer output - = dynamic_cast<OutputTreeType*>(this->MakeOutput(0).GetPointer()); + = dynamic_cast<OutputTreeType*>(this->MakeOutput(0).GetPointer()); this->itk::ProcessObject::SetNumberOfRequiredOutputs(1); this->itk::ProcessObject::SetNthOutput(0, output.GetPointer()); @@ -77,7 +77,7 @@ ImageToTreeFilter<TInputImage,TOutputTree> // process object is not const-correct, the const_cast // is required here. this->itk::ProcessObject::SetNthInput(0, - const_cast< InputImageType * >(input) ); + const_cast< InputImageType * >(input) ); } @@ -91,7 +91,7 @@ ImageToTreeFilter<TInputImage,TOutputTree> ::GetInput(void) { return dynamic_cast<const InputImageType*> - (this->itk::ProcessObject::GetInput(0)); + (this->itk::ProcessObject::GetInput(0)); } @@ -104,7 +104,7 @@ ImageToTreeFilter<TInputImage,TOutputTree> ::GetOutput(void) { return dynamic_cast<OutputTreeType*> - (this->itk::ProcessObject::GetOutput(0)); + (this->itk::ProcessObject::GetOutput(0)); } diff --git a/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.h b/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.h old mode 100755 new mode 100644 index d210fcfb25a921c7c339675003bfaf4e827fb06a..0e02157280bbde407f6439eef0f4fbd760670cbb --- a/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.h +++ b/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.h @@ -25,106 +25,106 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class KeyPointSetsMatchingFilter - * \brief This class matches two point sets according to their associated data. - * - * The matching criteria is that the ratio between the distance to the first nearest neighbor and the - * second nearest neighbor is lower than the distance threshold. The distance used can be set via the TDistance - * template parameters. It has to implement the Evaluate() method (see \doxygen{EuclideanDistance} for more details). - * - * By default, the algorithm tries to match points from pointset 1 to points from pointset 2. If back matching is activated, - * it will aslo try to match points from pointset 2 to points from pointset 2, and discard matches that do not appear both in - * forward and backward matching. - * - * Matches are stored in a landmark object containing both matched points and point data. The landmark data will hold the distance value - * between the data. - * - * \sa Landmark - * \sa PointSet - * \sa EuclideanDistance - */ +/** \class KeyPointSetsMatchingFilter + * \brief This class matches two point sets according to their associated data. + * + * The matching criteria is that the ratio between the distance to the first nearest neighbor and the + * second nearest neighbor is lower than the distance threshold. The distance used can be set via the TDistance + * template parameters. It has to implement the Evaluate() method (see \doxygen{EuclideanDistance} for more details). + * + * By default, the algorithm tries to match points from pointset 1 to points from pointset 2. If back matching is activated, + * it will aslo try to match points from pointset 2 to points from pointset 2, and discard matches that do not appear both in + * forward and backward matching. + * + * Matches are stored in a landmark object containing both matched points and point data. The landmark data will hold the distance value + * between the data. + * + * \sa Landmark + * \sa PointSet + * \sa EuclideanDistance + */ template < class TPointSet, class TDistance = itk::Statistics::EuclideanDistance< typename TPointSet::PixelType > > class ITK_EXPORT KeyPointSetsMatchingFilter -: public ObjectListSource< ObjectList< Landmark< typename TPointSet::PointType, typename TPointSet::PixelType,double> > > - { - public: - /// standard class typedefs - typedef KeyPointSetsMatchingFilter Self; - typedef ObjectListSource< ObjectList< - Landmark< typename TPointSet::PointType, - typename TPointSet::PixelType,double> > > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /// template typedefs - typedef TPointSet PointSetType; - typedef typename PointSetType::Pointer PointSetPointerType; - typedef typename PointSetType::PointType PointType; - typedef typename PointSetType::PixelType PointDataType; - typedef typename PointSetType::PointsContainer PointsContainerType; - typedef typename PointsContainerType::ConstIterator PointsIteratorType; - typedef typename PointSetType::PointDataContainer PointDataContainerType; - typedef typename PointDataContainerType::ConstIterator PointDataIteratorType; - typedef TDistance DistanceType; - typedef typename DistanceType::Pointer DistancePointerType; - typedef Landmark< typename TPointSet::PointType, - typename TPointSet::PixelType,double> LandmarkType; - typedef typename LandmarkType::Pointer LandmarkPointerType; - typedef ObjectList<LandmarkType> LandmarkListType; - typedef typename LandmarkListType::Pointer LandmarkListPointerType; - typedef std::pair<unsigned int,double> NeighborSearchResultType; - - /// standard macros - itkNewMacro(Self); - itkTypeMacro(KeyPointSetsMatchingFilter,ObjectListSource); - - /// Accessors - itkBooleanMacro(UseBackMatching); - itkSetMacro(UseBackMatching,bool); - itkGetMacro(UseBackMatching,bool); - itkSetMacro(DistanceThreshold,double); - itkGetMacro(DistanceThreshold,double); - - /// Set the first pointset - void SetInput1(const PointSetType * pointset); - /// Get the first pointset - const PointSetType * GetInput1(); - /// Set the second pointset - void SetInput2(const PointSetType * pointset); - /// Get the second pointset - const PointSetType * GetInput2(); - - protected: - /// Constructor - KeyPointSetsMatchingFilter(); - /// Destructor - ~KeyPointSetsMatchingFilter(){}; - /// PrintSelf method - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - /// Generate Data - virtual void GenerateData(); - - /** - * Find the nearest neighbor of data1 in pointset. - * \return a pair of (index,distance). - */ - NeighborSearchResultType NearestNeighbor(const PointDataType& data1, const PointSetType * pointset); - - - private: - KeyPointSetsMatchingFilter(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - - // Find back matches from 2 to 1 to validate them - bool m_UseBackMatching; - - // Distance threshold to decide matching - double m_DistanceThreshold; - - // Distance calculator - DistancePointerType m_DistanceCalculator; - }; + : public ObjectListSource< ObjectList< Landmark< typename TPointSet::PointType, typename TPointSet::PixelType,double> > > +{ +public: + /// standard class typedefs + typedef KeyPointSetsMatchingFilter Self; + typedef ObjectListSource< ObjectList< + Landmark< typename TPointSet::PointType, + typename TPointSet::PixelType,double> > > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /// template typedefs + typedef TPointSet PointSetType; + typedef typename PointSetType::Pointer PointSetPointerType; + typedef typename PointSetType::PointType PointType; + typedef typename PointSetType::PixelType PointDataType; + typedef typename PointSetType::PointsContainer PointsContainerType; + typedef typename PointsContainerType::ConstIterator PointsIteratorType; + typedef typename PointSetType::PointDataContainer PointDataContainerType; + typedef typename PointDataContainerType::ConstIterator PointDataIteratorType; + typedef TDistance DistanceType; + typedef typename DistanceType::Pointer DistancePointerType; + typedef Landmark< typename TPointSet::PointType, + typename TPointSet::PixelType,double> LandmarkType; + typedef typename LandmarkType::Pointer LandmarkPointerType; + typedef ObjectList<LandmarkType> LandmarkListType; + typedef typename LandmarkListType::Pointer LandmarkListPointerType; + typedef std::pair<unsigned int,double> NeighborSearchResultType; + + /// standard macros + itkNewMacro(Self); + itkTypeMacro(KeyPointSetsMatchingFilter,ObjectListSource); + + /// Accessors + itkBooleanMacro(UseBackMatching); + itkSetMacro(UseBackMatching,bool); + itkGetMacro(UseBackMatching,bool); + itkSetMacro(DistanceThreshold,double); + itkGetMacro(DistanceThreshold,double); + + /// Set the first pointset + void SetInput1(const PointSetType * pointset); + /// Get the first pointset + const PointSetType * GetInput1(); + /// Set the second pointset + void SetInput2(const PointSetType * pointset); + /// Get the second pointset + const PointSetType * GetInput2(); + +protected: + /// Constructor + KeyPointSetsMatchingFilter(); + /// Destructor + ~KeyPointSetsMatchingFilter() {}; + /// PrintSelf method + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + + /// Generate Data + virtual void GenerateData(); + + /** + * Find the nearest neighbor of data1 in pointset. + * \return a pair of (index,distance). + */ + NeighborSearchResultType NearestNeighbor(const PointDataType& data1, const PointSetType * pointset); + + +private: + KeyPointSetsMatchingFilter(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + + // Find back matches from 2 to 1 to validate them + bool m_UseBackMatching; + + // Distance threshold to decide matching + double m_DistanceThreshold; + + // Distance calculator + DistancePointerType m_DistanceCalculator; +}; } // end namespace otb diff --git a/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.txx b/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.txx old mode 100755 new mode 100644 index f98618a9746528cff390a8cd4ac67c0d691c5337..70cef9c5cb0c639078c8dbcc7102d10db0c72d47 --- a/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.txx +++ b/Code/FeatureExtraction/otbKeyPointSetsMatchingFilter.txx @@ -80,10 +80,10 @@ KeyPointSetsMatchingFilter<TPointSet,TDistance> const PointSetType * ps2 = this->GetInput2(); // Check if one of the pointsets is empty - if( ps1->GetNumberOfPoints() == 0 || ps2->GetNumberOfPoints() == 0 ) - { - itkExceptionMacro(<<"Empty input pointset !"); - } + if ( ps1->GetNumberOfPoints() == 0 || ps2->GetNumberOfPoints() == 0 ) + { + itkExceptionMacro(<<"Empty input pointset !"); + } // Get the output pointer LandmarkListPointerType landmarks = this->GetOutput(); @@ -91,65 +91,65 @@ KeyPointSetsMatchingFilter<TPointSet,TDistance> // Define iterators on points and point data. PointsIteratorType pIt = ps1->GetPoints()->Begin(); PointDataIteratorType pdIt = ps1->GetPointData()->Begin(); - + // iterate on pointset 1 - while(pdIt!=ps1->GetPointData()->End() - &&pIt!=ps1->GetPoints()->End()) + while (pdIt!=ps1->GetPointData()->End() + &&pIt!=ps1->GetPoints()->End()) + { + // Get point and point data at current location + bool matchFound = false; + unsigned int currentIndex = pIt.Index(); + PointDataType data = pdIt.Value(); + PointType point = pIt.Value(); + + // These variables will hold the matched point and point data + PointDataType dataMatch; + PointType pointMatch; + + // call to the matching routine + NeighborSearchResultType searchResult1 = NearestNeighbor(data,ps2); + + // Check if the neighbor distance is lower than the threshold + if (searchResult1.second < m_DistanceThreshold) { - // Get point and point data at current location - bool matchFound = false; - unsigned int currentIndex = pIt.Index(); - PointDataType data = pdIt.Value(); - PointType point = pIt.Value(); - - // These variables will hold the matched point and point data - PointDataType dataMatch; - PointType pointMatch; - - // call to the matching routine - NeighborSearchResultType searchResult1 = NearestNeighbor(data,ps2); - - // Check if the neighbor distance is lower than the threshold - if(searchResult1.second < m_DistanceThreshold) - { - // Get the matched point and point data - dataMatch = ps2->GetPointData()->GetElement(searchResult1.first); - pointMatch = ps2->GetPoints()->GetElement(searchResult1.first); - - // If the back matching option is on - if(m_UseBackMatching) - { - // Peform the back search - NeighborSearchResultType searchResult2 = NearestNeighbor(dataMatch,ps1); - - // Test if back search finds the same match - if(currentIndex == searchResult2.first) - { - matchFound = true; - } - } - else // else back matching - { - matchFound = true; - } - } - - // If we found a match, add the proper landmark - if(matchFound) - { - LandmarkPointerType landmark = LandmarkType::New(); - landmark->SetPoint1(point); - landmark->SetPointData1(data); - landmark->SetPoint2(pointMatch); - landmark->SetPointData2(dataMatch); - landmark->SetLandmarkData(searchResult1.second); - - // Add the new landmark to the landmark list - landmarks->PushBack(landmark); - } - ++pdIt; - ++pIt; + // Get the matched point and point data + dataMatch = ps2->GetPointData()->GetElement(searchResult1.first); + pointMatch = ps2->GetPoints()->GetElement(searchResult1.first); + + // If the back matching option is on + if (m_UseBackMatching) + { + // Peform the back search + NeighborSearchResultType searchResult2 = NearestNeighbor(dataMatch,ps1); + + // Test if back search finds the same match + if (currentIndex == searchResult2.first) + { + matchFound = true; + } + } + else // else back matching + { + matchFound = true; + } } + + // If we found a match, add the proper landmark + if (matchFound) + { + LandmarkPointerType landmark = LandmarkType::New(); + landmark->SetPoint1(point); + landmark->SetPointData1(data); + landmark->SetPoint2(pointMatch); + landmark->SetPointData2(dataMatch); + landmark->SetLandmarkData(searchResult1.second); + + // Add the new landmark to the landmark list + landmarks->PushBack(landmark); + } + ++pdIt; + ++pIt; + } } template <class TPointSet, class TDistance> @@ -171,49 +171,49 @@ KeyPointSetsMatchingFilter<TPointSet,TDistance> double d2 = m_DistanceCalculator->Evaluate(data1,pdIt.Value()); ++pdIt; - if(d1>d2) - { - nearestIndex = 1; - } + if (d1>d2) + { + nearestIndex = 1; + } // Initialize distances double nearestDistance = std::min(d1,d2); double secondNearestDistance = std::max(d1,d2); double distanceValue; // iterate on the pointset - while( pdIt != pointset->GetPointData()->End() ) - { - // Evaluate the distance - distanceValue = m_DistanceCalculator->Evaluate(data1,pdIt.Value()); + while ( pdIt != pointset->GetPointData()->End() ) + { + // Evaluate the distance + distanceValue = m_DistanceCalculator->Evaluate(data1,pdIt.Value()); // std::cout<<nearestIndex<<" "<<nearestDistance<<" "<<secondNearestDistance<<std::endl; - // Check if this point is the nearest neighbor - if(distanceValue < nearestDistance) - { - secondNearestDistance = nearestDistance; - nearestDistance = distanceValue; - nearestIndex = pdIt.Index(); - - } - // Else check if it is the second nearest neighbor - else if(distanceValue < secondNearestDistance) - { - secondNearestDistance = distanceValue; - } - ++pdIt; + // Check if this point is the nearest neighbor + if (distanceValue < nearestDistance) + { + secondNearestDistance = nearestDistance; + nearestDistance = distanceValue; + nearestIndex = pdIt.Index(); + + } + // Else check if it is the second nearest neighbor + else if (distanceValue < secondNearestDistance) + { + secondNearestDistance = distanceValue; } + ++pdIt; + } // Fill results result.first = nearestIndex; - if(secondNearestDistance == 0) - { - result.second = 1; - } + if (secondNearestDistance == 0) + { + result.second = 1; + } else - { - result.second = nearestDistance/secondNearestDistance; - } + { + result.second = nearestDistance/secondNearestDistance; + } // return the result return result; diff --git a/Code/FeatureExtraction/otbLandmark.h b/Code/FeatureExtraction/otbLandmark.h old mode 100755 new mode 100644 index e7dc099f42440243505247f0834af7787cafa96c..afa852f8b2110efa8fe93870572c8267e7c85dff --- a/Code/FeatureExtraction/otbLandmark.h +++ b/Code/FeatureExtraction/otbLandmark.h @@ -24,71 +24,71 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class Landmark - * \brief This class represent point and point data binary matching. - * - * It is used to represent match between keypoint like SIFT keypoint for instance. - * - * The class TLandmarkData can be used to store any information on the matching. - */ - template <class TPoint, class TPointData, class TLandmarkData=TPointData> - class ITK_EXPORT Landmark - : public itk::DataObject - { - public: - /// standard class typedefs - typedef Landmark Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +/** \class Landmark + * \brief This class represent point and point data binary matching. + * + * It is used to represent match between keypoint like SIFT keypoint for instance. + * + * The class TLandmarkData can be used to store any information on the matching. + */ +template <class TPoint, class TPointData, class TLandmarkData=TPointData> +class ITK_EXPORT Landmark + : public itk::DataObject +{ +public: + /// standard class typedefs + typedef Landmark Self; + typedef itk::DataObject Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /// Standard macros + itkNewMacro(Self); + itkTypeMacro(Landmark,DataObject); + + /// template typedefs + typedef TPoint PointType; + typedef TPointData PointDataType; + typedef TLandmarkData LandmarkDataType; + + /// Accessors + itkSetMacro(Point1,PointType); + itkGetConstReferenceMacro(Point1,PointType); + itkSetMacro(PointData1,PointDataType); + itkGetConstReferenceMacro(PointData1,PointDataType); + itkSetMacro(Point2,PointType); + itkGetConstReferenceMacro(Point2,PointType); + itkSetMacro(PointData2,PointDataType); + itkGetConstReferenceMacro(PointData2,PointDataType); + itkSetMacro(LandmarkData,LandmarkDataType); + itkGetConstReferenceMacro(LandmarkData,LandmarkDataType); - /// Standard macros - itkNewMacro(Self); - itkTypeMacro(Landmark,DataObject); - - /// template typedefs - typedef TPoint PointType; - typedef TPointData PointDataType; - typedef TLandmarkData LandmarkDataType; - - /// Accessors - itkSetMacro(Point1,PointType); - itkGetConstReferenceMacro(Point1,PointType); - itkSetMacro(PointData1,PointDataType); - itkGetConstReferenceMacro(PointData1,PointDataType); - itkSetMacro(Point2,PointType); - itkGetConstReferenceMacro(Point2,PointType); - itkSetMacro(PointData2,PointDataType); - itkGetConstReferenceMacro(PointData2,PointDataType); - itkSetMacro(LandmarkData,LandmarkDataType); - itkGetConstReferenceMacro(LandmarkData,LandmarkDataType); +protected: + /// Constructor + Landmark() {} + /// Destructor + ~Landmark() {} + /// PrintSelf method + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const + { + Superclass::PrintSelf(os,indent); + os<<indent<<"Landmark: P1= "<<m_Point1<<" P2= "<<m_Point2<<std::endl; + } - protected: - /// Constructor - Landmark(){} - /// Destructor - ~Landmark(){} - /// PrintSelf method - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"Landmark: P1= "<<m_Point1<<" P2= "<<m_Point2<<std::endl; - } +private: + Landmark(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - private: - Landmark(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /// First landmark point - PointType m_Point1; - /// Second landmark point - PointType m_Point2; - /// First landmark point data - PointDataType m_PointData1; - /// Second landmark point data - PointDataType m_PointData2; - /// Landmark data - LandmarkDataType m_LandmarkData; - }; + /// First landmark point + PointType m_Point1; + /// Second landmark point + PointType m_Point2; + /// First landmark point data + PointDataType m_PointData1; + /// Second landmark point data + PointDataType m_PointData2; + /// Landmark data + LandmarkDataType m_LandmarkData; +}; } // end namespace otb #endif diff --git a/Code/FeatureExtraction/otbLikelihoodPathListFilter.h b/Code/FeatureExtraction/otbLikelihoodPathListFilter.h index 9714ca8c834a092332fcb9a69f4db1281a7eeec9..7ccef6b4f5ba6022a42bd2eb02185bd75083471b 100644 --- a/Code/FeatureExtraction/otbLikelihoodPathListFilter.h +++ b/Code/FeatureExtraction/otbLikelihoodPathListFilter.h @@ -34,9 +34,9 @@ namespace otb */ template <class TPath, class TImage> class ITK_EXPORT LikelihoodPathListFilter - : public PathListToPathListFilter<TPath> + : public PathListToPathListFilter<TPath> { - public: +public: /** Standard typedefs */ typedef LikelihoodPathListFilter Self; typedef PathListToPathListFilter<TPath> Superclass; diff --git a/Code/FeatureExtraction/otbLikelihoodPathListFilter.txx b/Code/FeatureExtraction/otbLikelihoodPathListFilter.txx index 0de37e84661a293e03417e0e3e4982bd5742431d..7b1a523c783622b181a6b000a963da2866e96470 100644 --- a/Code/FeatureExtraction/otbLikelihoodPathListFilter.txx +++ b/Code/FeatureExtraction/otbLikelihoodPathListFilter.txx @@ -49,10 +49,10 @@ const typename LikelihoodPathListFilter<TPath, TImage> LikelihoodPathListFilter<TPath, TImage> ::GetInputImage(void) { - if(this->GetNumberOfInputs()<1) - { - return 0; - } + if (this->GetNumberOfInputs()<1) + { + return 0; + } return static_cast<const ImageType *>(this->itk::ProcessObject::GetInput(1)); } @@ -68,13 +68,13 @@ LikelihoodPathListFilter<TPath, TImage> typedef otb::PolyLineImageConstIterator<ImageType,PathType> ImageIteratorType; - for(IteratorType it = inputPtr->Begin(); it != inputPtr->End(); ++it) + for (IteratorType it = inputPtr->Begin(); it != inputPtr->End(); ++it) { PathPointerType path = it.Get(); ImageIteratorType imageIt(inputImagePtr,path); double cumulatedValues = 0.0; double nbPoints = 0.0; - for(imageIt.GoToBegin();!imageIt.IsAtEnd();++imageIt,++nbPoints) + for (imageIt.GoToBegin();!imageIt.IsAtEnd();++imageIt,++nbPoints) { cumulatedValues+=static_cast<double>(imageIt.Get()); } diff --git a/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.h b/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.h index 090d0bbcff319cdb456dd1c174e70ed00ac01db0..96d0dbef767617024dd052f272d1a9c4d7989b08 100644 --- a/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.h +++ b/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.h @@ -25,25 +25,25 @@ namespace otb { - /** - *\class LineCorrelationDetectorImageFilter - * \brief To be documented - * - */ +/** + *\class LineCorrelationDetectorImageFilter + * \brief To be documented + * + */ template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage, - class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > +class TOutputImage, +class TOutputImageDirection = TOutputImage, +class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > class ITK_EXPORT LineCorrelationDetectorImageFilter : public LineDetectorImageFilterBase< TInputImage, TOutputImage, TOutputImageDirection, TInterpolator > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ diff --git a/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.txx b/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.txx index f195ee5d6e74325ddc78044029148c3aa480df3a..8c11a8640b1a62f759063412464139e176cc2e49 100644 --- a/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.txx +++ b/Code/FeatureExtraction/otbLineCorrelationDetectorImageFilter.txx @@ -66,8 +66,8 @@ LineCorrelationDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirect std::vector<double>::iterator m3It = m3->begin(); std::vector<double>::iterator m3End = m3->end(); - while( m1It!=m1End && m2It!=m2End && m3It!=m3End ) - { + while ( m1It!=m1End && m2It!=m2End && m3It!=m3End ) + { M1 += (*m1It); ++m1It; @@ -78,7 +78,7 @@ LineCorrelationDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirect M3 += (*m3It); ++m3It; - } + } M1 /= m1->size(); M2 /= m2->size(); @@ -93,8 +93,8 @@ LineCorrelationDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirect m3It = m3->begin(); - while( m1It!=m1End && m2It!=m2End && m3It!=m3End ) - { + while ( m1It!=m1End && m2It!=m2End && m3It!=m3End ) + { sigma1 += vcl_pow((*m1It)-M1,2); ++m1It; @@ -106,17 +106,17 @@ LineCorrelationDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirect ++m3It; - } + } sigma1 /= m1->size(); sigma2 /= m2->size(); sigma3 /= m3->size(); // Actually, we use the variance -/* sigma1 = vcl_sqrt(sigma1); - sigma2 = vcl_sqrt(sigma2); - sigma3 = vcl_sqrt(sigma3); - */ + /* sigma1 = vcl_sqrt(sigma1); + sigma2 = vcl_sqrt(sigma2); + sigma3 = vcl_sqrt(sigma3); + */ // Calculation of the cross correlation coefficient @@ -130,31 +130,31 @@ LineCorrelationDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirect // rho12 if ( M2 != 0. ) - { + { d1 = sigma1/vcl_pow(M2,2)*m1->size(); d2 = sigma2/vcl_pow(M2,2)*m2->size(); d3 = vcl_pow(((M1/M2)-1.),2)*(m1->size()*m2->size()); - if ( ( d3 != 0. ) ) - rho12 = static_cast<double>( 1. / ( 1. + ( (m1->size()+m2->size())*(d1+d2)/d3 ) ) ); - else - rho12 = 0.; + if ( ( d3 != 0. ) ) + rho12 = static_cast<double>( 1. / ( 1. + ( (m1->size()+m2->size())*(d1+d2)/d3 ) ) ); + else + rho12 = 0.; - } + } if ( M3 != 0. ) - { + { d1 = sigma1/vcl_pow(M3,2)*m1->size(); d2 = sigma3/vcl_pow(M3,2)*m2->size(); d3 = vcl_pow(((M1/M3)-1.),2)*(m1->size()*m2->size()); - if ( ( d3 != 0. ) ) - rho13 = static_cast<double>( 1. / ( 1. + ( (m1->size()+m2->size())*(d1+d2)/d3 ) ) ); - else - rho13 = 0.; + if ( ( d3 != 0. ) ) + rho13 = static_cast<double>( 1. / ( 1. + ( (m1->size()+m2->size())*(d1+d2)/d3 ) ) ); + else + rho13 = 0.; - } + } rho12 = vcl_sqrt(rho12); rho13 = vcl_sqrt(rho13); diff --git a/Code/FeatureExtraction/otbLineDetectorImageFilterBase.h b/Code/FeatureExtraction/otbLineDetectorImageFilterBase.h index 22d65827188673e069d8740c5a7073b018ff1383..ee54af275f1c75432a8800c190b7bcc8f4252b4b 100644 --- a/Code/FeatureExtraction/otbLineDetectorImageFilterBase.h +++ b/Code/FeatureExtraction/otbLineDetectorImageFilterBase.h @@ -54,18 +54,18 @@ namespace otb */ template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage, - class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > +class TOutputImage, +class TOutputImageDirection = TOutputImage, +class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > class ITK_EXPORT LineDetectorImageFilterBase : public ImageToModulusAndDirectionImageFilter< TInputImage, TOutputImage, TOutputImageDirection > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ @@ -153,7 +153,7 @@ protected: * * \sa ImageToImageFilter::ThreadedGenerateData() * \sa ImageToImageFilter::GenerateData() -*/ + */ void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); diff --git a/Code/FeatureExtraction/otbLineDetectorImageFilterBase.txx b/Code/FeatureExtraction/otbLineDetectorImageFilterBase.txx index 7f7746d5f6eb22d727838351d2bc825bf7a3610e..0f9c46d29d7ac7399dd01f8f751569779cac9bef 100644 --- a/Code/FeatureExtraction/otbLineDetectorImageFilterBase.txx +++ b/Code/FeatureExtraction/otbLineDetectorImageFilterBase.txx @@ -69,9 +69,9 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -94,12 +94,12 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -110,12 +110,12 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << static_cast<const char *>(this->GetNameOfClass()) - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } /* @@ -138,9 +138,9 @@ template <class TInputImage, class TOutputImage, class TOutputImageDirection, cl void LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, InterpolatorType> ::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - int threadId - ) + const OutputImageRegionType& outputRegionForThread, + int threadId +) { typename InputImageType::ConstPointer input = this->GetInput(); @@ -187,14 +187,14 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In double* Theta = new double[NB_DIR]; // La rotation nulle correspond a un contour horizontal -> 0 !! - for(unsigned int i=0; i<NB_DIR; i++) - { + for (unsigned int i=0; i<NB_DIR; i++) + { Theta[i] = (M_PI*(i/double(NB_DIR))); -/* if(Theta[i]>M_PI) - Theta[i] = Theta[i]-M_PI; - if((i/double(NB_DIR))==0.5) - Theta[i]=0.;*/ - } + /* if(Theta[i]>M_PI) + Theta[i] = Theta[i]-M_PI; + if((i/double(NB_DIR))==0.5) + Theta[i]=0.;*/ + } // Number of the zone unsigned int zone; @@ -228,7 +228,7 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In bool interiorFace = true; for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, input, *fit); cit = itk::ConstNeighborhoodIterator<InputImageType>(m_FaceList, input,*fit); @@ -240,53 +240,53 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In cit.OverrideBoundaryCondition(&nbc); cit.GoToBegin(); - otbMsgDevMacro( << " ------------------- FaceList --------------------------"); + otbMsgDevMacro( << " ------------------- FaceList --------------------------"); while ( (!bit.IsAtEnd())&&(!cit.IsAtEnd()) ) - { - InterpolatorPointer interpolator = InterpolatorType::New(); - // Location of the central pixel of the region - off.Fill(0); - bitIndex = bit.GetIndex(off); - Xc = bitIndex[0]; - Yc = bitIndex[1]; - - // JULIEN : If the processed region is the center face - // the input image can be used for the interpolation - if(interiorFace) - { - interpolator->SetInputImage(input); - } - // else we must feed the interpolator with a partial image corresponding - // to the boundary conditions - else { - typename InputImageType::RegionType tempRegion; - typename InputImageType::SizeType tempSize; - tempSize[0] = 2*m_FaceList[0]+1; - tempSize[1] = 2*m_FaceList[1]+1; - tempRegion.SetSize(tempSize); - typename itk::ConstNeighborhoodIterator<InputImageType>::OffsetType tempIndex; - tempIndex[0]=off[0]-m_FaceList[0]; - tempIndex[1]=off[1]-m_FaceList[1]; - tempRegion.SetIndex(cit.GetIndex(tempIndex)); - typename InputImageType::Pointer tempImage = InputImageType::New(); - tempImage->SetRegions(tempRegion); - tempImage->Allocate(); - - for(unsigned int p = 0; p<=2*m_FaceList[0];p++) - { - for(unsigned int q = 0; q<=2*m_FaceList[1];q++) + InterpolatorPointer interpolator = InterpolatorType::New(); + // Location of the central pixel of the region + off.Fill(0); + bitIndex = bit.GetIndex(off); + Xc = bitIndex[0]; + Yc = bitIndex[1]; + + // JULIEN : If the processed region is the center face + // the input image can be used for the interpolation + if (interiorFace) { - typename itk::ConstNeighborhoodIterator<InputImageType>::OffsetType index; - index[0]=p-m_FaceList[0]; - index[1]=q-m_FaceList[1]; - tempImage->SetPixel(cit.GetIndex(index),cit.GetPixel(index)); + interpolator->SetInputImage(input); } + // else we must feed the interpolator with a partial image corresponding + // to the boundary conditions + else + { + typename InputImageType::RegionType tempRegion; + typename InputImageType::SizeType tempSize; + tempSize[0] = 2*m_FaceList[0]+1; + tempSize[1] = 2*m_FaceList[1]+1; + tempRegion.SetSize(tempSize); + typename itk::ConstNeighborhoodIterator<InputImageType>::OffsetType tempIndex; + tempIndex[0]=off[0]-m_FaceList[0]; + tempIndex[1]=off[1]-m_FaceList[1]; + tempRegion.SetIndex(cit.GetIndex(tempIndex)); + typename InputImageType::Pointer tempImage = InputImageType::New(); + tempImage->SetRegions(tempRegion); + tempImage->Allocate(); + + for (unsigned int p = 0; p<=2*m_FaceList[0];p++) + { + for (unsigned int q = 0; q<=2*m_FaceList[1];q++) + { + typename itk::ConstNeighborhoodIterator<InputImageType>::OffsetType index; + index[0]=p-m_FaceList[0]; + index[1]=q-m_FaceList[1]; + tempImage->SetPixel(cit.GetIndex(index),cit.GetPixel(index)); + } } - interpolator->SetInputImage(tempImage); - } + interpolator->SetInputImage(tempImage); + } // Location of the central pixel between zone 1 and zone 2 @@ -297,51 +297,51 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In // Contains for the 4 directions the the pixels belonging to each zone - //std::vector<double> PixelValues[NB_DIR][NB_ZONE]; - // ROMAIN - std::vector<double>** PixelValues = NULL; - PixelValues = new std::vector<double>*[NB_DIR]; - for (unsigned int i=0; i<NB_DIR; i++) - { - PixelValues[i] = NULL; - PixelValues[i] = new std::vector<double>[NB_ZONE]; - } - //otbMsgDevMacro( << "\tCentre Xc/Yc="<<Xc<<" "<<Yc<<" Yc12/Yc13="<<Yc12<<" "<<Yc13); + //std::vector<double> PixelValues[NB_DIR][NB_ZONE]; + // ROMAIN + std::vector<double>** PixelValues = NULL; + PixelValues = new std::vector<double>*[NB_DIR]; + for (unsigned int i=0; i<NB_DIR; i++) + { + PixelValues[i] = NULL; + PixelValues[i] = new std::vector<double>[NB_ZONE]; + } + //otbMsgDevMacro( << "\tCentre Xc/Yc="<<Xc<<" "<<Yc<<" Yc12/Yc13="<<Yc12<<" "<<Yc13); // Loop on the region for (unsigned int i = 0; i < m_Radius[0]; i++) - for (unsigned int j = 0; j < m_Radius[1]; j++) + for (unsigned int j = 0; j < m_Radius[1]; j++) { - off[0]=i-m_Radius[0]/2; - off[1]=j-m_Radius[1]/2; - - bitIndex = bit.GetIndex(off); - X = bitIndex[0]; - Y = bitIndex[1]; - - // We determine in the horizontal direction with which zone the pixel belongs. - if ( Y < Yc12 ) - zone = 1; - else if ( ( Yc12 < Y ) && ( Y < Yc13 ) ) - zone = 0; - else if ( Y > Yc13 ) - zone = 2; - else - continue; - //otbMsgDevMacro( << "\t\tPoint traite (i,j)=("<<i<<","<<j<<") -> X,Y="<<X<<","<<Y<<" zone="<<zone); - // Loop on the directions - for (unsigned int dir=0; dir<NB_DIR; dir++ ) + off[0]=i-m_Radius[0]/2; + off[1]=j-m_Radius[1]/2; + + bitIndex = bit.GetIndex(off); + X = bitIndex[0]; + Y = bitIndex[1]; + + // We determine in the horizontal direction with which zone the pixel belongs. + if ( Y < Yc12 ) + zone = 1; + else if ( ( Yc12 < Y ) && ( Y < Yc13 ) ) + zone = 0; + else if ( Y > Yc13 ) + zone = 2; + else + continue; + //otbMsgDevMacro( << "\t\tPoint traite (i,j)=("<<i<<","<<j<<") -> X,Y="<<X<<","<<Y<<" zone="<<zone); + // Loop on the directions + for (unsigned int dir=0; dir<NB_DIR; dir++ ) { - //ROTATION( (X-Xc), (Y-Yc), Theta[dir], xout, yout); + //ROTATION( (X-Xc), (Y-Yc), Theta[dir], xout, yout); - xout = (X-Xc)*vcl_cos(Theta[dir]) - (Y-Yc)*vcl_sin(Theta[dir]); - yout = (X-Xc)*vcl_sin(Theta[dir]) + (Y-Yc)*vcl_cos(Theta[dir]); + xout = (X-Xc)*vcl_cos(Theta[dir]) - (Y-Yc)*vcl_sin(Theta[dir]); + yout = (X-Xc)*vcl_sin(Theta[dir]) + (Y-Yc)*vcl_cos(Theta[dir]); - Index[0] = static_cast<CoordRepType>(xout + Xc); - Index[1] = static_cast<CoordRepType>(yout + Yc); + Index[0] = static_cast<CoordRepType>(xout + Xc); + Index[1] = static_cast<CoordRepType>(yout + Yc); - PixelValues[dir][zone].push_back(static_cast<double>(interpolator->EvaluateAtContinuousIndex( Index ))); - } + PixelValues[dir][zone].push_back(static_cast<double>(interpolator->EvaluateAtContinuousIndex( Index ))); + } } // end of the loop on the pixels of the region R = 0.; @@ -350,55 +350,55 @@ LineDetectorImageFilterBase<TInputImage, TOutputImage, TOutputImageDirection, In // Loop on the 4 directions - for (unsigned int dir=0; dir<NB_DIR; dir++ ) - { + for (unsigned int dir=0; dir<NB_DIR; dir++ ) + { - double Rtemp = this->ComputeMeasure(&PixelValues[dir][0], &PixelValues[dir][1], &PixelValues[dir][2]); + double Rtemp = this->ComputeMeasure(&PixelValues[dir][0], &PixelValues[dir][1], &PixelValues[dir][2]); - if( Rtemp > R) - { - R = Rtemp; - Direction = Theta[dir]; - } + if ( Rtemp > R) + { + R = Rtemp; + Direction = Theta[dir]; + } - } // end of the loop on the directions + } // end of the loop on the directions - //otbMsgDevMacro( << "\t\tR,Direction : "<<R<<","<<Direction); - if( R >= this->GetThreshold() ) - { + //otbMsgDevMacro( << "\t\tR,Direction : "<<R<<","<<Direction); + if ( R >= this->GetThreshold() ) + { - // Assignment of this value to the output pixel - it.Set( static_cast<OutputPixelType>(R) ); + // Assignment of this value to the output pixel + it.Set( static_cast<OutputPixelType>(R) ); - // Assignment of this value to the "outputdir" pixel - itdir.Set( static_cast<OutputPixelType>(Direction) ); - } - else - { + // Assignment of this value to the "outputdir" pixel + itdir.Set( static_cast<OutputPixelType>(Direction) ); + } + else + { - it.Set( itk::NumericTraits<OutputPixelType>::Zero ); + it.Set( itk::NumericTraits<OutputPixelType>::Zero ); - itdir.Set( static_cast<OutputPixelType>(0) ); - } - ++bit; - ++cit; - ++it; - ++itdir; - interiorFace=false; - progress.CompletedPixel(); - - // ROMAIN - for (unsigned int i=0; i<NB_DIR; i++) - { - delete[] PixelValues[i]; - PixelValues[i] = NULL; - } - delete[] PixelValues; - PixelValues = NULL; + itdir.Set( static_cast<OutputPixelType>(0) ); + } + ++bit; + ++cit; + ++it; + ++itdir; + interiorFace=false; + progress.CompletedPixel(); + + // ROMAIN + for (unsigned int i=0; i<NB_DIR; i++) + { + delete[] PixelValues[i]; + PixelValues[i] = NULL; + } + delete[] PixelValues; + PixelValues = NULL; } - } + } delete[] Theta; } diff --git a/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.h b/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.h index f8bb10c82ef1da305e2e490b3ec57fefdcf92655..34556774aade85a37ae3161b016b2c4ca169b7e1 100644 --- a/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.h +++ b/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.h @@ -62,18 +62,18 @@ namespace otb * */ template <class TInputImage, - class TOutputImage, - class TOutputImageDirection = TOutputImage, - class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > +class TOutputImage, +class TOutputImageDirection = TOutputImage, +class TInterpolator = itk::LinearInterpolateImageFunction<TInputImage> > class ITK_EXPORT LineRatioDetectorImageFilter : public LineDetectorImageFilterBase< TInputImage, TOutputImage, TOutputImageDirection, TInterpolator > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ diff --git a/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.txx b/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.txx index 6d6feddaa5868db6270b49c9b763a20f3446154c..f72f0ecdce345372db71b1032e067b93471aa621 100644 --- a/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.txx +++ b/Code/FeatureExtraction/otbLineRatioDetectorImageFilter.txx @@ -66,8 +66,8 @@ LineRatioDetectorImageFilter< TInputImage, TOutputImage, TOutputImageDirection, std::vector<double>::iterator m3It = m3->begin(); std::vector<double>::iterator m3End = m3->end(); - while( m1It!=m1End && m2It!=m2End && m3It!=m3End ) - { + while ( m1It!=m1End && m2It!=m2End && m3It!=m3End ) + { M1 += (*m1It); ++m1It; @@ -78,7 +78,7 @@ LineRatioDetectorImageFilter< TInputImage, TOutputImage, TOutputImageDirection, M3 += (*m3It); ++m3It; - } + } M1 /= m1->size(); M2 /= m2->size(); diff --git a/Code/FeatureExtraction/otbLinkPathListFilter.h b/Code/FeatureExtraction/otbLinkPathListFilter.h index 663f0c4766e3e9c6475e30d14d91996c1f5020bd..8a06482726fa6a12de8d50c0fb340d089a53973c 100644 --- a/Code/FeatureExtraction/otbLinkPathListFilter.h +++ b/Code/FeatureExtraction/otbLinkPathListFilter.h @@ -42,9 +42,9 @@ namespace otb */ template <class TPath> class ITK_EXPORT LinkPathListFilter - : public PathListToPathListFilter<TPath> + : public PathListToPathListFilter<TPath> { - public: +public: /** Standard typedefs */ typedef LinkPathListFilter Self; typedef PathListToPathListFilter<TPath> Superclass; diff --git a/Code/FeatureExtraction/otbLinkPathListFilter.txx b/Code/FeatureExtraction/otbLinkPathListFilter.txx index ca44844d20578d59c22268c7e085bb28039325be..ad5c38b511aba02bdcaf13d083cea1b6962fceed 100644 --- a/Code/FeatureExtraction/otbLinkPathListFilter.txx +++ b/Code/FeatureExtraction/otbLinkPathListFilter.txx @@ -50,168 +50,168 @@ LinkPathListFilter<TPath> std::vector<bool> eraseFlagVector; // First we copy all input path to output - while( inputIt != inputPtr->End()) - { - outputPtr->PushBack(inputIt.Get()); - eraseFlagVector.push_back(false); - ++inputIt; - } + while ( inputIt != inputPtr->End()) + { + outputPtr->PushBack(inputIt.Get()); + eraseFlagVector.push_back(false); + ++inputIt; + } IteratorType outputIt1 = outputPtr->Begin(); unsigned int index1 = 0; - while(outputIt1!=outputPtr->End()) - { - if(!eraseFlagVector[index1]) + while (outputIt1!=outputPtr->End()) { - IteratorType outputIt2 = outputIt1; - ++outputIt2; - // indicate if a path was found and wath is its index - unsigned int pathToLinkIndex = 0; - double distance = -1.0; - unsigned int index2 = index1+1; - bool found = false; - bool revert1 = false; - bool revert2 = false; - if(!eraseFlagVector[index1]) - { - while(outputIt2!=outputPtr->End()) + if (!eraseFlagVector[index1]) { - if(!eraseFlagVector[index2]) - { - //otbMsgDevMacro(<<"Examining links between path "<<index1<<" and path "<<index2); - // Examining end of path1 with beginning of path2 - VertexIteratorType vSourceIt = outputIt1.Get()->GetVertexList()->End(); - VertexIteratorType vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); - --vSourceIt; - VertexType v2 = vSourceIt.Value(); - --vSourceIt; - VertexType v1 = vSourceIt.Value(); - VertexType v3 = vTargetIt.Value(); - ++vTargetIt; - VertexType v4 = vTargetIt.Value(); - double tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); - if((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) + IteratorType outputIt2 = outputIt1; + ++outputIt2; + // indicate if a path was found and wath is its index + unsigned int pathToLinkIndex = 0; + double distance = -1.0; + unsigned int index2 = index1+1; + bool found = false; + bool revert1 = false; + bool revert2 = false; + if (!eraseFlagVector[index1]) { - if(VerifyAngularCondition(v1,v2,v3,v4)) - { - // we found a better candidate - //otbMsgDevMacro(<<"Link between end of path "<<index1<<" and beginning of path "<<index2<<" is currently the best choice"); - distance = tmpDistance; - pathToLinkIndex = index2; - revert1 = false; - revert2 = false; - if(!found) + while (outputIt2!=outputPtr->End()) { - found = true; - } - } - } - // Examining end of path1 with end of path2 - vTargetIt = outputIt2.Get()->GetVertexList()->End(); - --vTargetIt; - v3 = vTargetIt.Value(); - --vTargetIt; - v4 = vTargetIt.Value(); - tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); - - if((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) - { - if(VerifyAngularCondition(v1,v2,v3,v4)) + if (!eraseFlagVector[index2]) { - // we found a better candidate - //otbMsgDevMacro(<<"Link between end of path "<<index1<<" and end of path "<<index2<<" is currently the best choice"); - distance = tmpDistance; - pathToLinkIndex = index2; - revert1 = false; - revert2 = true; - if(!found) - { - found = true; - } - } - } - // Examining beginning of path1 with end of path2 - vSourceIt = outputIt1.Get()->GetVertexList()->Begin(); - v2 = vSourceIt.Value(); - ++vSourceIt; - v1 = vSourceIt.Value(); - tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); + //otbMsgDevMacro(<<"Examining links between path "<<index1<<" and path "<<index2); + // Examining end of path1 with beginning of path2 + VertexIteratorType vSourceIt = outputIt1.Get()->GetVertexList()->End(); + VertexIteratorType vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); + --vSourceIt; + VertexType v2 = vSourceIt.Value(); + --vSourceIt; + VertexType v1 = vSourceIt.Value(); + VertexType v3 = vTargetIt.Value(); + ++vTargetIt; + VertexType v4 = vTargetIt.Value(); + double tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); + if ((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) + { + if (VerifyAngularCondition(v1,v2,v3,v4)) + { + // we found a better candidate + //otbMsgDevMacro(<<"Link between end of path "<<index1<<" and beginning of path "<<index2<<" is currently the best choice"); + distance = tmpDistance; + pathToLinkIndex = index2; + revert1 = false; + revert2 = false; + if (!found) + { + found = true; + } + } + } + // Examining end of path1 with end of path2 + vTargetIt = outputIt2.Get()->GetVertexList()->End(); + --vTargetIt; + v3 = vTargetIt.Value(); + --vTargetIt; + v4 = vTargetIt.Value(); + tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); - if((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) - { - if(VerifyAngularCondition(v1,v2,v3,v4)) - { - // we found a better candidate - //otbMsgDevMacro(<<"Link between beginning of path "<<index1<<" and end of path "<<index2<<" is currently the best choice"); - distance = tmpDistance; - pathToLinkIndex = index2; - revert1 = true; - revert2 = true; - if(!found) - { - found = true; - } + if ((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) + { + if (VerifyAngularCondition(v1,v2,v3,v4)) + { + // we found a better candidate + //otbMsgDevMacro(<<"Link between end of path "<<index1<<" and end of path "<<index2<<" is currently the best choice"); + distance = tmpDistance; + pathToLinkIndex = index2; + revert1 = false; + revert2 = true; + if (!found) + { + found = true; + } + } + } + // Examining beginning of path1 with end of path2 + vSourceIt = outputIt1.Get()->GetVertexList()->Begin(); + v2 = vSourceIt.Value(); + ++vSourceIt; + v1 = vSourceIt.Value(); + tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); + + if ((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) + { + if (VerifyAngularCondition(v1,v2,v3,v4)) + { + // we found a better candidate + //otbMsgDevMacro(<<"Link between beginning of path "<<index1<<" and end of path "<<index2<<" is currently the best choice"); + distance = tmpDistance; + pathToLinkIndex = index2; + revert1 = true; + revert2 = true; + if (!found) + { + found = true; + } + } + } + // Examining beginning of path1 with beginning of path2 + vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); + v3 = vTargetIt.Value(); + ++vTargetIt; + v4 = vTargetIt.Value(); + tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); + if ((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) + { + if (VerifyAngularCondition(v1,v2,v3,v4)) + { + // we found a better candidate + //otbMsgDevMacro(<<"Link between beginning of path "<<index1<<" and beginning of path "<<index2<<" is currently the best choice"); + distance = tmpDistance; + pathToLinkIndex = index2; + revert1 = true; + revert2 = false; + if (!found) + { + found = true; + } + } + } } - } - // Examining beginning of path1 with beginning of path2 - vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); - v3 = vTargetIt.Value(); - ++vTargetIt; - v4 = vTargetIt.Value(); - tmpDistance = vcl_sqrt(vcl_pow(v2[0]-v3[0],2)+vcl_pow(v2[1]-v3[1],2)); - if((tmpDistance<static_cast<double>(m_DistanceThreshold)) && ((!found)||(tmpDistance<distance))) - { - if(VerifyAngularCondition(v1,v2,v3,v4)) - { - // we found a better candidate - //otbMsgDevMacro(<<"Link between beginning of path "<<index1<<" and beginning of path "<<index2<<" is currently the best choice"); - distance = tmpDistance; - pathToLinkIndex = index2; - revert1 = true; - revert2 = false; - if(!found) + ++index2; + ++outputIt2; + } + if (found) { - found = true; + //otbMsgDevMacro(<<"Search ended, merging path "<<index1<<" and path "<<pathToLinkIndex); + // an appropriate path was found + outputIt2 = outputPtr->Begin() + pathToLinkIndex; + PathPointerType newPath = this->LinkPath(outputIt1.Get(),revert1,outputIt2.Get(),revert2); + outputPtr->PushBack(newPath); + // add a non erased flag for the new path + eraseFlagVector.push_back(false); + // mark the old path as erased + eraseFlagVector[index1]=true; + eraseFlagVector[pathToLinkIndex]=true; } - } } - } - ++index2; - ++outputIt2; - } - if(found) - { - //otbMsgDevMacro(<<"Search ended, merging path "<<index1<<" and path "<<pathToLinkIndex); - // an appropriate path was found - outputIt2 = outputPtr->Begin() + pathToLinkIndex; - PathPointerType newPath = this->LinkPath(outputIt1.Get(),revert1,outputIt2.Get(),revert2); - outputPtr->PushBack(newPath); - // add a non erased flag for the new path - eraseFlagVector.push_back(false); - // mark the old path as erased - eraseFlagVector[index1]=true; - eraseFlagVector[pathToLinkIndex]=true; } - } + ++index1; + // This replaces ++outputIt1 because the iterators is somehow invalidated by a pushback. + outputIt1 = outputPtr->Begin() + index1; } - ++index1; - // This replaces ++outputIt1 because the iterators is somehow invalidated by a pushback. - outputIt1 = outputPtr->Begin() + index1; - } // search ended, now removing the erased path typename std::vector<bool>::reverse_iterator it = eraseFlagVector.rbegin(); index1 = eraseFlagVector.size()-1; - while(it!=eraseFlagVector.rend()) - { - if(eraseFlagVector[index1]) + while (it!=eraseFlagVector.rend()) { - outputPtr->Erase(index1); - } - --index1; - ++it; + if (eraseFlagVector[index1]) + { + outputPtr->Erase(index1); } + --index1; + ++it; + } } /** * Verify the angular condition to link a path. @@ -230,22 +230,22 @@ LinkPathListFilter<TPath> double alpha2 = vcl_atan2((v4[1]-v3[1]),(v4[0]-v3[0])); double alpha3 = vcl_atan2((v3[1]-v2[1]),(v3[0]-v2[0])); - if(m_ModuloPI) - { + if (m_ModuloPI) + { alpha1 = (alpha1 >= 0)?alpha1:(alpha1+M_PI); alpha2 = (alpha2 >= 0)?alpha2:(alpha2+M_PI); alpha3 = (alpha3 >= 0)?alpha3:(alpha3+M_PI); - } + } else - { + { alpha1 = (alpha1 >= 0)?alpha1:(alpha1+2.*M_PI); alpha2 = (alpha2 >= 0)?alpha2:(alpha2+2.*M_PI); alpha3 = (alpha3 >= 0)?alpha3:(alpha3+2.*M_PI); - } + } bool resp = (vcl_abs(alpha1-alpha2) < static_cast<double>(m_AngularThreshold)) - && (vcl_abs(alpha1-alpha3) < static_cast<double>(m_AngularThreshold)) - &&(vcl_abs(alpha2-alpha3) <static_cast<double>(m_AngularThreshold )); + && (vcl_abs(alpha1-alpha3) < static_cast<double>(m_AngularThreshold)) + &&(vcl_abs(alpha2-alpha3) <static_cast<double>(m_AngularThreshold )); return resp; } /** @@ -267,37 +267,37 @@ LinkPathListFilter<TPath> VertexIteratorType it; - if(revert1) - { - for(it=(p1->GetVertexList()->End());it!=p1->GetVertexList()->Begin();) + if (revert1) { - --it; - resp->AddVertex((it).Value()); - } + for (it=(p1->GetVertexList()->End());it!=p1->GetVertexList()->Begin();) + { + --it; + resp->AddVertex((it).Value()); } + } else - { - for(it=p1->GetVertexList()->Begin();it!=p1->GetVertexList()->End();++it) { - resp->AddVertex((it).Value()); - } + for (it=p1->GetVertexList()->Begin();it!=p1->GetVertexList()->End();++it) + { + resp->AddVertex((it).Value()); } + } - if(revert2) - { - for(it=(p2->GetVertexList()->End());it!=p2->GetVertexList()->Begin();) + if (revert2) { - --it; - resp->AddVertex((it).Value()); - } + for (it=(p2->GetVertexList()->End());it!=p2->GetVertexList()->Begin();) + { + --it; + resp->AddVertex((it).Value()); } + } else - { - for(it=p2->GetVertexList()->Begin();it!=p2->GetVertexList()->End();++it) { - resp->AddVertex(it.Value()); - } + for (it=p2->GetVertexList()->Begin();it!=p2->GetVertexList()->End();++it) + { + resp->AddVertex(it.Value()); } + } return resp; } /** diff --git a/Code/FeatureExtraction/otbLocalHoughFilter.h b/Code/FeatureExtraction/otbLocalHoughFilter.h index d31f2c2526e0af3bbf2ec7e6090d5fb1366ef408..6f169ef724331f9296803c0d204544c057af47a6 100644 --- a/Code/FeatureExtraction/otbLocalHoughFilter.h +++ b/Code/FeatureExtraction/otbLocalHoughFilter.h @@ -59,7 +59,7 @@ public: typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for management of the "object factory". */ + /** Method for management of the "object factory". */ itkNewMacro(Self); /** Return the name of the class. */ @@ -78,16 +78,16 @@ public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); typedef TInputImage InputImageType; //------------------------------------------------------------ - typedef unsigned char OutputPixelType; - typedef otb::Image< OutputPixelType, 2 > OutputImageType; - //----------------------------------------------- + typedef unsigned char OutputPixelType; + typedef otb::Image< OutputPixelType, 2 > OutputImageType; + //----------------------------------------------- /** Definition of the pixel type of the input and output images */ typedef typename InputImageType::PixelType InputPixelType; @@ -172,7 +172,7 @@ private: /** Threshold abouve which a pixel is consedered as valid */ float m_Threshold; - LinePointer LinePointResearch(LineIterator itLines, InputImageType *localImage, IndexType origin); + LinePointer LinePointResearch(LineIterator itLines, InputImageType *localImage, IndexType origin); }; diff --git a/Code/FeatureExtraction/otbLocalHoughFilter.txx b/Code/FeatureExtraction/otbLocalHoughFilter.txx index 84d05d6766309fb3793fe4b63111e413419bc467..9645b1ac7f3a8fc422f45a5f2a83c57de9737376 100644 --- a/Code/FeatureExtraction/otbLocalHoughFilter.txx +++ b/Code/FeatureExtraction/otbLocalHoughFilter.txx @@ -31,13 +31,13 @@ namespace otb */ template <class TInputImage> LocalHoughFilter<TInputImage>::LocalHoughFilter() : ImageToLineSpatialObjectListFilter<TInputImage>(), - m_NumberOfLines(1), - m_Variance(5), - m_DiscRadius(10), - m_Threshold(0) + m_NumberOfLines(1), + m_Variance(5), + m_DiscRadius(10), + m_Threshold(0) { - m_Radius.Fill(20); - m_Overlap.Fill(0); + m_Radius.Fill(20); + m_Overlap.Fill(0); } template <class TInputImage> @@ -46,85 +46,85 @@ LocalHoughFilter<TInputImage>:: LinePointResearch(LineIterator itLines, InputImageType *image, IndexType origin) { - // Get the list of points which consists of two points to represent a - // straight line - PointListType & pointsList = (*itLines)->GetPoints(); - typename PointListType::const_iterator itPoints = pointsList.begin(); + // Get the list of points which consists of two points to represent a + // straight line + PointListType & pointsList = (*itLines)->GetPoints(); + typename PointListType::const_iterator itPoints = pointsList.begin(); - double u[2]; - u[0] = (*itPoints).GetPosition()[0]; - u[1] = (*itPoints).GetPosition()[1]; - itPoints++; - double v[2]; - v[0] = u[0]-(*itPoints).GetPosition()[0]; - v[1] = u[1]-(*itPoints).GetPosition()[1]; + double u[2]; + u[0] = (*itPoints).GetPosition()[0]; + u[1] = (*itPoints).GetPosition()[1]; + itPoints++; + double v[2]; + v[0] = u[0]-(*itPoints).GetPosition()[0]; + v[1] = u[1]-(*itPoints).GetPosition()[1]; - double norm = vcl_sqrt(v[0]*v[0]+v[1]*v[1]); - v[0] /= norm; - v[1] /= norm; + double norm = vcl_sqrt(v[0]*v[0]+v[1]*v[1]); + v[0] /= norm; + v[1] /= norm; - typename InputImageType::RegionType region = image->GetLargestPossibleRegion(); + typename InputImageType::RegionType region = image->GetLargestPossibleRegion(); - PointListType ptList; - LinePointType point; + PointListType ptList; + LinePointType point; - typename InputImageType::IndexType localIndex; - typename InputImageType::IndexType previousIndex; - typename InputImageType::IndexType nextIndex; + typename InputImageType::IndexType localIndex; + typename InputImageType::IndexType previousIndex; + typename InputImageType::IndexType nextIndex; - // The diagonal is the largest distance between two edges of image - itk::Size<2> size = region.GetSize(); - float diag = vcl_sqrt((float)( size[0]*size[0] + size[1]*size[1] )); + // The diagonal is the largest distance between two edges of image + itk::Size<2> size = region.GetSize(); + float diag = vcl_sqrt((float)( size[0]*size[0] + size[1]*size[1] )); - // Loop on the largest distance to be sure to cover all the image - // whatever the position of the origin u - for(int i=static_cast<int>(-diag); i<static_cast<int>(diag); i++) - { + // Loop on the largest distance to be sure to cover all the image + // whatever the position of the origin u + for (int i=static_cast<int>(-diag); i<static_cast<int>(diag); i++) + { - previousIndex[0] = static_cast<long>(u[0]+(i-1)*v[0]); - previousIndex[1] = static_cast<long>(u[1]+(i-1)*v[1]); + previousIndex[0] = static_cast<long>(u[0]+(i-1)*v[0]); + previousIndex[1] = static_cast<long>(u[1]+(i-1)*v[1]); - localIndex[0] = static_cast<long>(u[0]+i*v[0]); - localIndex[1] = static_cast<long>(u[1]+i*v[1]); + localIndex[0] = static_cast<long>(u[0]+i*v[0]); + localIndex[1] = static_cast<long>(u[1]+i*v[1]); - nextIndex[0] = static_cast<long>(u[0]+(i+1)*v[0]); - nextIndex[1] = static_cast<long>(u[1]+(i+1)*v[1]); + nextIndex[0] = static_cast<long>(u[0]+(i+1)*v[0]); + nextIndex[1] = static_cast<long>(u[1]+(i+1)*v[1]); - // Check if the local index is inside the image and the previous - // index is outside or if the local index is inside the image and - // the next index is outside + // Check if the local index is inside the image and the previous + // index is outside or if the local index is inside the image and + // the next index is outside - if( ((region.IsInside( localIndex )) && (!region.IsInside( previousIndex ))) || - ((region.IsInside( localIndex )) && (!region.IsInside( nextIndex ))) ) - { + if ( ((region.IsInside( localIndex )) && (!region.IsInside( previousIndex ))) || + ((region.IsInside( localIndex )) && (!region.IsInside( nextIndex ))) ) + { - point.SetPosition(localIndex[0]+origin[0],localIndex[1]+origin[1]); - ptList.push_back(point); + point.SetPosition(localIndex[0]+origin[0],localIndex[1]+origin[1]); + ptList.push_back(point); - } + } - } + } - // Check if the line is well defined by two points - LinePointer line = LineType::New(); + // Check if the line is well defined by two points + LinePointer line = LineType::New(); - if ( ptList.size() == 2 ) - { - line->SetId(0); - line->SetPoints(ptList); - line->ComputeBoundingBox(); - } + if ( ptList.size() == 2 ) + { + line->SetId(0); + line->SetPoints(ptList); + line->ComputeBoundingBox(); + } - ptList.clear(); + ptList.clear(); - return( line); + return( line); } @@ -136,151 +136,151 @@ LocalHoughFilter<TInputImage> ::GenerateData() { - typename InputImageType::ConstPointer input = this->GetInput(); + typename InputImageType::ConstPointer input = this->GetInput(); - typename LinesListType::Pointer list; - list = this->GetOutput(); + typename LinesListType::Pointer list; + list = this->GetOutput(); - typename ROIFilterType::Pointer ROIfilter = ROIFilterType::New(); + typename ROIFilterType::Pointer ROIfilter = ROIFilterType::New(); - typename HoughFilterType::LinesListType lines; + typename HoughFilterType::LinesListType lines; - typename HoughFilterType::Pointer houghFilter = HoughFilterType::New(); + typename HoughFilterType::Pointer houghFilter = HoughFilterType::New(); - // Get image size - itk::Size<2> size = input->GetLargestPossibleRegion().GetSize(); + // Get image size + itk::Size<2> size = input->GetLargestPossibleRegion().GetSize(); - // Loop on the input image + // Loop on the input image - // Direction X - // x and y must be < size in order to avoid 0-sized regions - for ( unsigned long x=0; x < size[0]-1; x += (m_Radius[0]-m_Overlap[0]) ) - { + // Direction X + // x and y must be < size in order to avoid 0-sized regions + for ( unsigned long x=0; x < size[0]-1; x += (m_Radius[0]-m_Overlap[0]) ) + { - // Initialize the extract ROI filter in the direction X - ROIfilter->SetStartX(x); + // Initialize the extract ROI filter in the direction X + ROIfilter->SetStartX(x); - // Number of pixels of the local region - if ( (x+m_Radius[0]) < size[0] ) - ROIfilter->SetSizeX(m_Radius[0]); - else - ROIfilter->SetSizeX(size[0]-x-1); + // Number of pixels of the local region + if ( (x+m_Radius[0]) < size[0] ) + ROIfilter->SetSizeX(m_Radius[0]); + else + ROIfilter->SetSizeX(size[0]-x-1); - // Direction Y - for ( unsigned long y=0; y < size[1]-1; y += (m_Radius[1]-m_Overlap[1]) ) - { + // Direction Y + for ( unsigned long y=0; y < size[1]-1; y += (m_Radius[1]-m_Overlap[1]) ) + { - // Initialize the extract ROI filter in the direction Y - ROIfilter->SetStartY(y); + // Initialize the extract ROI filter in the direction Y + ROIfilter->SetStartY(y); - if ( (y+m_Radius[1]) < size[1] ) - ROIfilter->SetSizeY(m_Radius[1]); - else - ROIfilter->SetSizeY(size[1]-y-1); + if ( (y+m_Radius[1]) < size[1] ) + ROIfilter->SetSizeY(m_Radius[1]); + else + ROIfilter->SetSizeY(size[1]-y-1); - // Extract the local region of the input image - ROIfilter->SetInput( this->GetInput() ); + // Extract the local region of the input image + ROIfilter->SetInput( this->GetInput() ); - // ---------------------------------------------------- - // Create a copy of the extract ROI filter output image - // ---------------------------------------------------- + // ---------------------------------------------------- + // Create a copy of the extract ROI filter output image + // ---------------------------------------------------- - typename InputImageType::Pointer localImage = InputImageType::New(); - typename InputImageType::Pointer filterImage = InputImageType::New(); + typename InputImageType::Pointer localImage = InputImageType::New(); + typename InputImageType::Pointer filterImage = InputImageType::New(); - ROIfilter->UpdateLargestPossibleRegion(); - ROIfilter->Update(); + ROIfilter->UpdateLargestPossibleRegion(); + ROIfilter->Update(); - filterImage = ROIfilter->GetOutput(); + filterImage = ROIfilter->GetOutput(); - // Create a new image from the extracted region. The starting - // index is the corner of the newly generated image (0,0) + // Create a new image from the extracted region. The starting + // index is the corner of the newly generated image (0,0) - typename InputImageType::RegionType region; + typename InputImageType::RegionType region; - IndexType index; + IndexType index; - index[0] = 0; - index[1] = 0; + index[0] = 0; + index[1] = 0; - region.SetSize(filterImage->GetLargestPossibleRegion().GetSize()); - region.SetIndex(index); - localImage->SetRegions( region ); - localImage->SetOrigin(filterImage->GetOrigin()); - localImage->SetSpacing(filterImage->GetSpacing()); - localImage->Allocate(); + region.SetSize(filterImage->GetLargestPossibleRegion().GetSize()); + region.SetIndex(index); + localImage->SetRegions( region ); + localImage->SetOrigin(filterImage->GetOrigin()); + localImage->SetSpacing(filterImage->GetSpacing()); + localImage->Allocate(); - typedef itk::ImageRegionIteratorWithIndex< InputImageType > LocalIteratorType; - typedef itk::ImageRegionConstIteratorWithIndex< InputImageType > FilterIteratorType; + typedef itk::ImageRegionIteratorWithIndex< InputImageType > LocalIteratorType; + typedef itk::ImageRegionConstIteratorWithIndex< InputImageType > FilterIteratorType; - LocalIteratorType localIt( localImage, localImage->GetRequestedRegion() ); - FilterIteratorType filterIt( filterImage, filterImage->GetRequestedRegion() ); + LocalIteratorType localIt( localImage, localImage->GetRequestedRegion() ); + FilterIteratorType filterIt( filterImage, filterImage->GetRequestedRegion() ); - localIt.GoToBegin(); - filterIt.GoToBegin(); + localIt.GoToBegin(); + filterIt.GoToBegin(); - // Copy the filter image in the new local image - for ( localIt.GoToBegin(); !localIt.IsAtEnd(); ++localIt,++filterIt) - localIt.Set( static_cast<InputPixelType>(filterIt.Get()) ); + // Copy the filter image in the new local image + for ( localIt.GoToBegin(); !localIt.IsAtEnd(); ++localIt,++filterIt) + localIt.Set( static_cast<InputPixelType>(filterIt.Get()) ); - // ------------------------------- - // Application of Hough filter - // ------------------------------- + // ------------------------------- + // Application of Hough filter + // ------------------------------- - houghFilter->SetInput( localImage ); - houghFilter->SetNumberOfLines( m_NumberOfLines ); - houghFilter->SetVariance( m_Variance ); - houghFilter->SetDiscRadius( m_DiscRadius ); - houghFilter->SetThreshold( m_Threshold ); + houghFilter->SetInput( localImage ); + houghFilter->SetNumberOfLines( m_NumberOfLines ); + houghFilter->SetVariance( m_Variance ); + houghFilter->SetDiscRadius( m_DiscRadius ); + houghFilter->SetThreshold( m_Threshold ); - houghFilter->Modified(); + houghFilter->Modified(); - houghFilter->Update(); + houghFilter->Update(); - // --------------------------------------- - // Get the list of LineSpatialObject lines - // --------------------------------------- + // --------------------------------------- + // Get the list of LineSpatialObject lines + // --------------------------------------- - lines = houghFilter->GetLines(m_NumberOfLines); + lines = houghFilter->GetLines(m_NumberOfLines); - LineIterator itLines = lines.begin(); + LineIterator itLines = lines.begin(); - // Loop on the lines of hough filter list - while( itLines != lines.end() ) - { + // Loop on the lines of hough filter list + while ( itLines != lines.end() ) + { - LinePointer line = LineType::New(); + LinePointer line = LineType::New(); - IndexType origin; + IndexType origin; - origin[0] = x; - origin[1] = y; + origin[0] = x; + origin[1] = y; - // Call the private method that researchs the two points - // used to define a line - line = LinePointResearch(itLines, localImage, origin); + // Call the private method that researchs the two points + // used to define a line + line = LinePointResearch(itLines, localImage, origin); - if (line->GetNumberOfPoints() != 0) - list->push_back(line); + if (line->GetNumberOfPoints() != 0) + list->push_back(line); - itLines++; + itLines++; } - lines.clear(); + lines.clear(); - } // end of loop in y direction + } // end of loop in y direction - } // end of loop in x direction + } // end of loop in x direction } diff --git a/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.h b/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.h index 64e1185f804099cdaa6d3d9bf4cf28a73c08b166..9cd5401c9e1009e4791fd471fe4de49f70c291a1 100644 --- a/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.h +++ b/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.h @@ -35,17 +35,17 @@ namespace otb * */ template <class TInputImage, - class TInputImageDirection, - class TOutputImage > +class TInputImageDirection, +class TOutputImage > class ITK_EXPORT ModulusAndDirectionImageToImageFilter : public itk::ImageToImageFilter< TInputImage, TOutputImage > { public: /** Extract dimensions as well of the images of entry of exit. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ diff --git a/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.txx b/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.txx index c64d5f258d3dd02d828e13ea949e611134fb5ea7..25213cb913f3c12df679c8f97eea0591d9963292 100644 --- a/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.txx +++ b/Code/FeatureExtraction/otbModulusAndDirectionImageToImageFilter.txx @@ -47,7 +47,7 @@ SetInput( const InputImageType *input) { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(0, - const_cast< InputImageType * >( input ) ); + const_cast< InputImageType * >( input ) ); } template <class TInputImage, class TInputImageDirection, class TOutputImage > @@ -57,7 +57,7 @@ SetInputDirection( const InputImageDirectionType *direction) { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(1, - const_cast< InputImageDirectionType * >( direction ) ); + const_cast< InputImageDirectionType * >( direction ) ); } /** Return the input image modulus */ @@ -67,12 +67,12 @@ ModulusAndDirectionImageToImageFilter<TInputImage, TInputImageDirection, TOutput GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<const TInputImage * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** Return the intput image direction */ @@ -82,12 +82,12 @@ ModulusAndDirectionImageToImageFilter<TInputImage, TInputImageDirection, TOutput GetInputDirection(void) { if (this->GetNumberOfInputs() < 2) - { + { return 0; - } + } return static_cast<const TInputImageDirection * > - (this->itk::ProcessObject::GetInput(1) ); + (this->itk::ProcessObject::GetInput(1) ); } diff --git a/Code/FeatureExtraction/otbMultiplyByScalarImageFilter.h b/Code/FeatureExtraction/otbMultiplyByScalarImageFilter.h index 295769a50da71d6c4182b90510724ac81403eb17..ef0f4ecb037f96df2448753afe697ed9fd71c35e 100644 --- a/Code/FeatureExtraction/otbMultiplyByScalarImageFilter.h +++ b/Code/FeatureExtraction/otbMultiplyByScalarImageFilter.h @@ -27,13 +27,17 @@ namespace otb * */ -namespace Functor { +namespace Functor +{ template< class TInput, class TOutput > class MultiplyByScalar { public: - MultiplyByScalar() {m_Coef = 1.0;} + MultiplyByScalar() + { + m_Coef = 1.0; + } ~MultiplyByScalar() {}; inline TOutput operator()( const TInput & value ) { @@ -60,21 +64,21 @@ private: template <class TInputImage, class TOutputImage> class ITK_EXPORT MultiplyByScalarImageFilter : - public itk::UnaryFunctorImageFilter< - TInputImage,TOutputImage, - Functor::MultiplyByScalar< - ITK_TYPENAME TInputImage::PixelType, - ITK_TYPENAME TOutputImage::PixelType> > + public itk::UnaryFunctorImageFilter< + TInputImage,TOutputImage, + Functor::MultiplyByScalar< + ITK_TYPENAME TInputImage::PixelType, + ITK_TYPENAME TOutputImage::PixelType> > { public: /** Standard class typedefs. */ typedef MultiplyByScalarImageFilter Self; typedef typename itk::UnaryFunctorImageFilter< - TInputImage, - TOutputImage, - Functor::MultiplyByScalar< - ITK_TYPENAME TInputImage::PixelType, - ITK_TYPENAME TOutputImage::PixelType> > Superclass; + TInputImage, + TOutputImage, + Functor::MultiplyByScalar< + ITK_TYPENAME TInputImage::PixelType, + ITK_TYPENAME TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -83,12 +87,12 @@ public: void SetCoef(double Coef) { - this->GetFunctor().SetCoef( Coef ); - this->Modified(); + this->GetFunctor().SetCoef( Coef ); + this->Modified(); } double GetCoef(void)const { - return( this->GetFunctor().GetCoef() ); + return( this->GetFunctor().GetCoef() ); } protected: MultiplyByScalarImageFilter() {} diff --git a/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.h b/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.h index 8c1732cf07d2d8d6aad922abd878547acc54eb97..6476d26645550f01bd8d3776bb613401c7e8abf6 100644 --- a/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.h +++ b/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.h @@ -47,9 +47,9 @@ namespace otb */ template <class TInputImage, class TOutputModulus, class TOutputDirection> class ITK_EXPORT NeighborhoodScalarProductFilter - : public ImageToModulusAndDirectionImageFilter<TInputImage,TOutputModulus,TOutputDirection> + : public ImageToModulusAndDirectionImageFilter<TInputImage,TOutputModulus,TOutputDirection> { - public: +public: /** Standard typedefs */ typedef NeighborhoodScalarProductFilter Self; typedef ImageToModulusAndDirectionImageFilter<TInputImage,TOutputModulus,TOutputDirection> Superclass; @@ -80,7 +80,7 @@ protected: NeighborhoodScalarProductFilter(); /** Destructor */ virtual ~NeighborhoodScalarProductFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** NeighborhoodScalarProductImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() routine diff --git a/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.txx b/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.txx index 717e401ed1dd766f7cf9b3152001ad878b5f4cfd..28cc99b686363d390c73cc3fcbd317a3f26af524 100644 --- a/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.txx +++ b/Code/FeatureExtraction/otbNeighborhoodScalarProductFilter.txx @@ -72,95 +72,96 @@ NeighborhoodScalarProductFilter<TInputImage,TOutputModulus,TOutputDirection> // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { - NeighborhoodIteratorType neighInputIt(r, inputPtr, *fit); - OutputIteratorType outputIt(outputPtr,*fit); - OutputDirectionIteratorType outputDirIt(outputDirPtr,*fit); - neighInputIt.GoToBegin(); - outputIt.GoToBegin(); - outputDirIt.GoToBegin(); - - while ((!neighInputIt.IsAtEnd()) && (!outputIt.IsAtEnd()) && (!outputDirIt.IsAtEnd()) ) { - // local variable intialisation - int neighborhoodNumberMax = 0; - double scalarMaxValue= 0.0; - int flagPosNegDirection = 0; + NeighborhoodIteratorType neighInputIt(r, inputPtr, *fit); + OutputIteratorType outputIt(outputPtr,*fit); + OutputDirectionIteratorType outputDirIt(outputDirPtr,*fit); + neighInputIt.GoToBegin(); + outputIt.GoToBegin(); + outputDirIt.GoToBegin(); + + while ((!neighInputIt.IsAtEnd()) && (!outputIt.IsAtEnd()) && (!outputDirIt.IsAtEnd()) ) + { + // local variable intialisation + int neighborhoodNumberMax = 0; + double scalarMaxValue= 0.0; + int flagPosNegDirection = 0; - // walk through each case - for (int neighborhoodNumber = 0; neighborhoodNumber<4; ++neighborhoodNumber) + // walk through each case + for (int neighborhoodNumber = 0; neighborhoodNumber<4; ++neighborhoodNumber) { - double scalarCurrentValue = 0.0; - OffsetType offset1; - OffsetType offset2; - switch(neighborhoodNumber){ - case 0: - offset1[0]=1; - offset1[1]=-1; - offset2[0]=-1; - offset2[1]=1; - break; - case 1: - offset1[0]=1; - offset1[1]=0; - offset2[0]=-1; - offset2[1]=0; - break; - case 2: - offset1[0]=1; - offset1[1]=1; - offset2[0]=-1; - offset2[1]=-1; - break; - case 3: - offset1[0]=0; - offset1[1]=1; - offset2[0]=0; - offset2[1]=-1; - break; - } - // Get the gradient values - InputPixelType pixel1 = neighInputIt.GetPixel(offset1); - InputPixelType pixel2 = neighInputIt.GetPixel(offset2); - - // Compute the scalar product - scalarCurrentValue = -(pixel1[0]*pixel2[0]+pixel1[1]*pixel2[1]); - - // If the value is upper than the current max value - if (scalarCurrentValue > scalarMaxValue) + double scalarCurrentValue = 0.0; + OffsetType offset1; + OffsetType offset2; + switch (neighborhoodNumber) { - // keep this configuration - scalarMaxValue = scalarCurrentValue; - neighborhoodNumberMax = neighborhoodNumber; + case 0: + offset1[0]=1; + offset1[1]=-1; + offset2[0]=-1; + offset2[1]=1; + break; + case 1: + offset1[0]=1; + offset1[1]=0; + offset2[0]=-1; + offset2[1]=0; + break; + case 2: + offset1[0]=1; + offset1[1]=1; + offset2[0]=-1; + offset2[1]=-1; + break; + case 3: + offset1[0]=0; + offset1[1]=1; + offset2[0]=0; + offset2[1]=-1; + break; + } + // Get the gradient values + InputPixelType pixel1 = neighInputIt.GetPixel(offset1); + InputPixelType pixel2 = neighInputIt.GetPixel(offset2); - // Also keep the direction - if (pixel1[0] <0) - { - flagPosNegDirection = 1; - } - else - { - flagPosNegDirection = 0; - } + // Compute the scalar product + scalarCurrentValue = -(pixel1[0]*pixel2[0]+pixel1[1]*pixel2[1]); + + // If the value is upper than the current max value + if (scalarCurrentValue > scalarMaxValue) + { + // keep this configuration + scalarMaxValue = scalarCurrentValue; + neighborhoodNumberMax = neighborhoodNumber; + + // Also keep the direction + if (pixel1[0] <0) + { + flagPosNegDirection = 1; + } + else + { + flagPosNegDirection = 0; + } } } - // Compute the direction - double angle = static_cast<double>((1+neighborhoodNumberMax)) * static_cast<double>(M_PI_4); - if (flagPosNegDirection) + // Compute the direction + double angle = static_cast<double>((1+neighborhoodNumberMax)) * static_cast<double>(M_PI_4); + if (flagPosNegDirection) { angle -= M_PI; } - // Set the ouptut values - outputIt.Set(scalarMaxValue); - outputDirIt.Set(angle); - ++neighInputIt; - ++outputIt; - ++outputDirIt; - progress.CompletedPixel(); - } + // Set the ouptut values + outputIt.Set(scalarMaxValue); + outputDirIt.Set(angle); + ++neighInputIt; + ++outputIt; + ++outputDirIt; + progress.CompletedPixel(); } + } } /** * PrintSelf Method diff --git a/Code/FeatureExtraction/otbNonMaxRemovalByDirectionFilter.h b/Code/FeatureExtraction/otbNonMaxRemovalByDirectionFilter.h index f91f12bf6a9e1eea8624694aaf1fd2781dac4ec7..50ebf1719540d740f839482346b28b80528f2b9d 100644 --- a/Code/FeatureExtraction/otbNonMaxRemovalByDirectionFilter.h +++ b/Code/FeatureExtraction/otbNonMaxRemovalByDirectionFilter.h @@ -26,70 +26,70 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class NonMaxRemovalByDirectionFunctor - * \brief This functor is used by the NonMaxRemovalByDirectionFilter - * \sa NonMaxRemovalByDirectionFilter - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class NonMaxRemovalByDirectionFunctor - { - public: +{ +/** \class NonMaxRemovalByDirectionFunctor + * \brief This functor is used by the NonMaxRemovalByDirectionFilter + * \sa NonMaxRemovalByDirectionFilter + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class NonMaxRemovalByDirectionFunctor +{ +public: NonMaxRemovalByDirectionFunctor() {}; ~NonMaxRemovalByDirectionFunctor() {}; inline TOutput operator()(const TInput1 & itA, const TInput2 &itB) + { + TOutput resp = 0; + if (itA.GetCenterPixel() != 0) { - TOutput resp = 0; - if (itA.GetCenterPixel() != 0) - { - typename TInput1::OffsetType offset1,offset2; - int neighborhoodNumber; - if (itB.GetCenterPixel() > 0) + typename TInput1::OffsetType offset1,offset2; + int neighborhoodNumber; + if (itB.GetCenterPixel() > 0) { neighborhoodNumber = static_cast<int>(itB.GetCenterPixel()/(M_PI/4)-1); } - else + else { neighborhoodNumber = static_cast<int>((itB.GetCenterPixel()+M_PI)/(M_PI/4)-1); } - switch( neighborhoodNumber ) + switch ( neighborhoodNumber ) { - case 0: - offset1[0] = 1; - offset1[1] = -1; - offset2[0] = -1; - offset2[1] = 1; - break; - case 1: - offset1[0] = 1; - offset1[1] = 0; - offset2[0] = -1; - offset2[1] = 0; - break; - case 2: - offset1[0] = 1; - offset1[1] = 1; - offset2[0] = -1; - offset2[1] = -1; - break; - case 3: - offset1[0] = 0; - offset1[1] = 1; - offset2[0] = 0; - offset2[1] = -1; - break; - } - if ((itA.GetCenterPixel() > itA.GetPixel(offset1)) - && (itA.GetCenterPixel() > itA.GetPixel(offset2))) + case 0: + offset1[0] = 1; + offset1[1] = -1; + offset2[0] = -1; + offset2[1] = 1; + break; + case 1: + offset1[0] = 1; + offset1[1] = 0; + offset2[0] = -1; + offset2[1] = 0; + break; + case 2: + offset1[0] = 1; + offset1[1] = 1; + offset2[0] = -1; + offset2[1] = -1; + break; + case 3: + offset1[0] = 0; + offset1[1] = 1; + offset2[0] = 0; + offset2[1] = -1; + break; + } + if ((itA.GetCenterPixel() > itA.GetPixel(offset1)) + && (itA.GetCenterPixel() > itA.GetPixel(offset2))) { resp = itA.GetCenterPixel(); } - } - return resp; } - }; + return resp; } +}; +} /** \class NonMaxRemovalByDirectionFilter * \brief This filters removes (sets to null intensity) pixels which are not the maxima of the * scalar product modulus value in the given direction. @@ -99,9 +99,9 @@ namespace Functor */ template <class TInputModulus, class TInputDirection, class TOutputImage> class ITK_EXPORT NonMaxRemovalByDirectionFilter - : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> + : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> { - public: +public: /** Standard typedefs */ typedef NonMaxRemovalByDirectionFilter Self; typedef ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> Superclass; @@ -117,31 +117,31 @@ class ITK_EXPORT NonMaxRemovalByDirectionFilter /** typedef of the computing filter (this allows us to derive from ModulusAndDirectionToImageFilter as well as using the BinaryFunctorNeighBorhoodImageFilter, which is appropriate here */ typedef Functor::NonMaxRemovalByDirectionFunctor< - typename itk::ConstNeighborhoodIterator<TInputModulus>, - typename itk::ConstNeighborhoodIterator<TInputDirection>, - typename TOutputImage::PixelType> FunctorType; + typename itk::ConstNeighborhoodIterator<TInputModulus>, + typename itk::ConstNeighborhoodIterator<TInputDirection>, + typename TOutputImage::PixelType> FunctorType; typedef otb::BinaryFunctorNeighborhoodImageFilter<TInputModulus, TInputDirection,TOutputImage,FunctorType> ComputingFilterType; protected: /** Constructor */ - NonMaxRemovalByDirectionFilter(){}; + NonMaxRemovalByDirectionFilter() {}; /** Destructor */ virtual ~NonMaxRemovalByDirectionFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; /** Main computation method */ virtual void GenerateData(void) - { - typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); - filter->SetInput1(this->GetInput()); - filter->SetInput2(this->GetInputDirection()); - filter->GraftOutput(this->GetOutput()); - filter->Update(); - this->GraftOutput(filter->GetOutput()); - } + { + typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); + filter->SetInput1(this->GetInput()); + filter->SetInput2(this->GetInputDirection()); + filter->GraftOutput(this->GetOutput()); + filter->Update(); + this->GraftOutput(filter->GetOutput()); + } private: NonMaxRemovalByDirectionFilter(const Self&); //purposely not implemented diff --git a/Code/FeatureExtraction/otbOrientationPathFunction.h b/Code/FeatureExtraction/otbOrientationPathFunction.h index 0b7a7f7eef2931df04cfb150141ba6c3c44371a6..3a38b6fea9818311f0ba22af0b6497b2e7e4806d 100644 --- a/Code/FeatureExtraction/otbOrientationPathFunction.h +++ b/Code/FeatureExtraction/otbOrientationPathFunction.h @@ -33,9 +33,9 @@ namespace otb */ template < class TInputPath, - class TOutput = double> +class TOutput = double> class ITK_EXPORT OrientationPathFunction : - public PathFunction< TInputPath, TOutput > + public PathFunction< TInputPath, TOutput > { public: /** Standard class typedefs. */ @@ -66,8 +66,8 @@ public: virtual OutputType Evaluate( ) const; protected: - OrientationPathFunction(){}; - ~OrientationPathFunction(){}; + OrientationPathFunction() {}; + ~OrientationPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/FeatureExtraction/otbOrientationPathFunction.txx b/Code/FeatureExtraction/otbOrientationPathFunction.txx index ef7413e82fb3619d5858654fc421ed1ea162db1b..ac8df2e5d3a9c7635a2e5bb658c65dfa3eb9b166 100644 --- a/Code/FeatureExtraction/otbOrientationPathFunction.txx +++ b/Code/FeatureExtraction/otbOrientationPathFunction.txx @@ -38,7 +38,7 @@ OrientationPathFunction< TInputPath, TOutput > template < class TInputPath, class TOutput> typename OrientationPathFunction<TInputPath, - TOutput>::OutputType +TOutput>::OutputType OrientationPathFunction<TInputPath,TOutput> ::Evaluate(const PathType& path) const { @@ -53,36 +53,36 @@ OrientationPathFunction<TInputPath,TOutput> vertexList = path.GetVertexList(); nbPath = vertexList->Size(); - if(nbPath ==2) - { - cindex = vertexList->GetElement(0); - RealType x1 = cindex[0]; - RealType y1 = cindex[1]; - cindex = vertexList->GetElement(1); - RealType x2 = cindex[0]; - RealType y2 = cindex[1]; - - Theta = vcl_atan2(y2-y1,x2-x1); - } // IF loop - else - { - itkExceptionMacro(<<"OrientationPathFunction::Evaluate() FAILED -- path must have 2 points"); - } + if (nbPath ==2) + { + cindex = vertexList->GetElement(0); + RealType x1 = cindex[0]; + RealType y1 = cindex[1]; + cindex = vertexList->GetElement(1); + RealType x2 = cindex[0]; + RealType y2 = cindex[1]; + + Theta = vcl_atan2(y2-y1,x2-x1); + } // IF loop + else + { + itkExceptionMacro(<<"OrientationPathFunction::Evaluate() FAILED -- path must have 2 points"); + } return (static_cast<OutputType>(Theta) ); } template < class TInputPath, class TOutput> typename OrientationPathFunction<TInputPath, - TOutput>::OutputType +TOutput>::OutputType OrientationPathFunction<TInputPath,TOutput> ::Evaluate() const { - if( !this->GetInputPath() ) - { + if ( !this->GetInputPath() ) + { otbMsgDevMacro( << "Problem with GetInputPath" ); return static_cast<OutputType>(itk::NumericTraits<OutputType>::max() ); - } + } OutputType Result = Evaluate( *(this->GetInputPath()) ); diff --git a/Code/FeatureExtraction/otbParallelLinePathListFilter.h b/Code/FeatureExtraction/otbParallelLinePathListFilter.h index 3e7e82a4a98a401015522ebae705e4ad58e30e8a..443ca853260fbf129f6b9b1541f83ce2f61fbf8d 100644 --- a/Code/FeatureExtraction/otbParallelLinePathListFilter.h +++ b/Code/FeatureExtraction/otbParallelLinePathListFilter.h @@ -47,9 +47,9 @@ namespace otb */ template <class TPath> class ITK_EXPORT ParallelLinePathListFilter - : public PathListToPathListFilter<TPath> + : public PathListToPathListFilter<TPath> { - public: +public: /** Standard typedefs */ typedef ParallelLinePathListFilter Self; typedef PathListToPathListFilter<TPath> Superclass; @@ -92,45 +92,45 @@ protected: virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** - * Verify the angular condition to find parallel lines. - * This function verifies if two lines are parallel by - * computing the angle in relation to the y-axis. - * First line segment: v1 is the first vertex, v2 the second one - * (not necessarily the path ending). - * Second line segment: v3 is the first vertex, v4 the second one - * (not necessarily the path ending). - * Return true if the condition is verified. - * - * This is the first criteria to be fullfilled. - **/ + * Verify the angular condition to find parallel lines. + * This function verifies if two lines are parallel by + * computing the angle in relation to the y-axis. + * First line segment: v1 is the first vertex, v2 the second one + * (not necessarily the path ending). + * Second line segment: v3 is the first vertex, v4 the second one + * (not necessarily the path ending). + * Return true if the condition is verified. + * + * This is the first criteria to be fullfilled. + **/ bool VerifyAngularCondition(VertexType v1, VertexType v2, VertexType v3, VertexType v4); /** - * Verify the maximum distance condition to find parallel lines. - * The orthogonal distance between two parallel lines is calculated. - * First line segment: v1 is the first vertex, v2 the second one - * (not necessarily the path ending). - * Second line segment: v3 is the first vertex, v4 the second one - * (not necessarily the path ending). - * Return true if the condition is verified. - * - * This is the second criteria to be fullfilled. - **/ + * Verify the maximum distance condition to find parallel lines. + * The orthogonal distance between two parallel lines is calculated. + * First line segment: v1 is the first vertex, v2 the second one + * (not necessarily the path ending). + * Second line segment: v3 is the first vertex, v4 the second one + * (not necessarily the path ending). + * Return true if the condition is verified. + * + * This is the second criteria to be fullfilled. + **/ bool VerifyMaxDistanceCondition(VertexType v1, VertexType v2, VertexType v3, VertexType v4); - /** - * Verify the common distance condition to find parallel lines. - * The overlapping part of the parallel lines is computed. In case - * no overlapping part exists or the value is below the specified - * threshold, false is returned. - * First line segment: v1 is the first vertex, v2 the second one - * (not necessarily the path ending). - * Second line segment: v3 is the first vertex, v4 the second one - * (not necessarily the path ending). - * Return true if the condition is verified. - * - * This is the third criteria to be fullfilled. - **/ + /** + * Verify the common distance condition to find parallel lines. + * The overlapping part of the parallel lines is computed. In case + * no overlapping part exists or the value is below the specified + * threshold, false is returned. + * First line segment: v1 is the first vertex, v2 the second one + * (not necessarily the path ending). + * Second line segment: v3 is the first vertex, v4 the second one + * (not necessarily the path ending). + * Return true if the condition is verified. + * + * This is the third criteria to be fullfilled. + **/ bool VerifyCommonDistanceCondition(VertexType v1, VertexType v2, VertexType v3, VertexType v4); /** diff --git a/Code/FeatureExtraction/otbParallelLinePathListFilter.txx b/Code/FeatureExtraction/otbParallelLinePathListFilter.txx index 8605c8ab58590ec6928f42af2ad47d51bf8eaaba..eeed24de685d5bc5a012786b738bb3dd2eb76ef8 100644 --- a/Code/FeatureExtraction/otbParallelLinePathListFilter.txx +++ b/Code/FeatureExtraction/otbParallelLinePathListFilter.txx @@ -51,20 +51,20 @@ ParallelLinePathListFilter<TPath> std::vector<unsigned int> parallelLineIndex; // First we copy all input path to output - while( inputIt != inputPtr->End()) - { - // Write the next input path always to the - // last element of the list. This last element is - // newly created. - outputPtr->PushBack(inputIt.Get()); - - // If a new element is copied to the output vector, - // "false" is written to the corresponding index of - // the vector eraseFlagVector. - eraseFlagVector1.push_back(false); + while ( inputIt != inputPtr->End()) + { + // Write the next input path always to the + // last element of the list. This last element is + // newly created. + outputPtr->PushBack(inputIt.Get()); + + // If a new element is copied to the output vector, + // "false" is written to the corresponding index of + // the vector eraseFlagVector. + eraseFlagVector1.push_back(false); - ++inputIt; - } + ++inputIt; + } unsigned int VectorSize = static_cast<unsigned int>(eraseFlagVector1.size()); //std::cout<<" Number of Lines: "<< VectorSize <<std::endl; @@ -75,63 +75,63 @@ ParallelLinePathListFilter<TPath> unsigned int commonDistCounter = 0, maxDistCounter = 0; // Iterate through all lines of the pathlist -while(firstLineCounter < VectorSize) - { - if(!eraseFlagVector1[index1]) + while (firstLineCounter < VectorSize) + { + if (!eraseFlagVector1[index1]) { IteratorType outputIt2 = outputIt1; ++outputIt2; unsigned int index2 = index1+1; - // Check if any of the following lines are parallel - while(outputIt2!=outputPtr->End()) + // Check if any of the following lines are parallel + while (outputIt2!=outputPtr->End()) { - if(!eraseFlagVector1[index2]) + if (!eraseFlagVector1[index2]) { // Read the first and the last vertex of each line pair that is checked VertexIteratorType vSourceIt = outputIt1.Get()->GetVertexList()->Begin(); - VertexType v1 = vSourceIt.Value(); - vSourceIt = outputIt1.Get()->GetVertexList()->End(); - --vSourceIt; - VertexType v2 = vSourceIt.Value(); + VertexType v1 = vSourceIt.Value(); + vSourceIt = outputIt1.Get()->GetVertexList()->End(); + --vSourceIt; + VertexType v2 = vSourceIt.Value(); - VertexIteratorType vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); - VertexType v3 = vTargetIt.Value(); - vTargetIt = outputIt2.Get()->GetVertexList()->End(); - --vTargetIt; - VertexType v4 = vTargetIt.Value(); + VertexIteratorType vTargetIt = outputIt2.Get()->GetVertexList()->Begin(); + VertexType v3 = vTargetIt.Value(); + vTargetIt = outputIt2.Get()->GetVertexList()->End(); + --vTargetIt; + VertexType v4 = vTargetIt.Value(); // Check for parallel lines - if(VerifyAngularCondition(v1,v2,v3,v4)) - { - ++parallelLineCounter; - if(VerifyMaxDistanceCondition(v1,v2,v3,v4)) + if (VerifyAngularCondition(v1,v2,v3,v4)) + { + ++parallelLineCounter; + if (VerifyMaxDistanceCondition(v1,v2,v3,v4)) { - ++maxDistCounter; - if(VerifyCommonDistanceCondition(v1,v2,v3,v4)) + ++maxDistCounter; + if (VerifyCommonDistanceCondition(v1,v2,v3,v4)) { - ++commonDistCounter; - // Write index of first parallel path - parallelLineIndex.push_back(index1); + ++commonDistCounter; + // Write index of first parallel path + parallelLineIndex.push_back(index1); - // Write index of second parallel path - parallelLineIndex.push_back(index2); + // Write index of second parallel path + parallelLineIndex.push_back(index2); } } - } + } } - ++index2; - ++outputIt2; + ++index2; + ++outputIt2; } } // mark the old path as erased eraseFlagVector1[index1]=true; ++firstLineCounter; - ++index1; - ++outputIt1; - }// end of for loop + ++index1; + ++outputIt1; + }// end of for loop std::cout<< "Number of line pairs that pass the angular condition: " << parallelLineCounter <<std::endl; std::cout<< "Number of line pairs that pass the maximum distance condition: " << maxDistCounter <<std::endl; @@ -140,9 +140,9 @@ while(firstLineCounter < VectorSize) // Write all parallel lines and set the non-erase flagg. typename std::vector<unsigned int>::iterator lineIt1 = parallelLineIndex.begin(); unsigned int sortLineIndex = 0; - while(lineIt1!=parallelLineIndex.end()) - { - IteratorType outputIt3 = outputPtr->Begin() + parallelLineIndex[sortLineIndex]; + while (lineIt1!=parallelLineIndex.end()) + { + IteratorType outputIt3 = outputPtr->Begin() + parallelLineIndex[sortLineIndex]; PathPointerType newPath1 = this->WriteParallelPath(outputIt3.Get()); outputPtr->PushBack(newPath1); @@ -150,22 +150,24 @@ while(firstLineCounter < VectorSize) eraseFlagVector1.push_back(false); ++sortLineIndex; std::cout<<"Number of lines written in the path list: "<< sortLineIndex<<std::endl; - ++lineIt1; - } + ++lineIt1; + } // Search ended, now removing the erased path from the first line pointer typename std::vector<bool>::reverse_iterator it1 = eraseFlagVector1.rbegin(); index1 = eraseFlagVector1.size()-1; - while(it1!=eraseFlagVector1.rend()) + while (it1!=eraseFlagVector1.rend()) + { + if (eraseFlagVector1[index1]) { - if(eraseFlagVector1[index1]) - { outputPtr->Erase(index1); } - - --index1; - ++it1; + outputPtr->Erase(index1); } + --index1; + ++it1; + } + } /** * Verify the angular condition to find parallel lines. @@ -252,7 +254,7 @@ bool ParallelLinePathListFilter<TPath> ::VerifyCommonDistanceCondition(VertexType v1, VertexType v2, VertexType v3, VertexType v4) { - // Compute the length of each line +// Compute the length of each line double length12 = 0., length34 = 0.; length12 = sqrt( pow((v2[0]-v1[0]),2) + pow((v2[1]-v1[1]),2) ); length34 = sqrt( pow((v4[0]-v3[0]),2) + pow((v4[1]-v3[1]),2) ); @@ -262,8 +264,8 @@ ParallelLinePathListFilter<TPath> // Compute the coordinates of the first and of the // second line in the new coordinate system. VertexType tempv1, tempv2 , tempv3, tempv4; - - //Initialization + + //Initialization tempv1.Fill(0.); tempv2.Fill(0.); tempv3.Fill(0.); @@ -271,20 +273,20 @@ ParallelLinePathListFilter<TPath> if (v1[1] == v2[1]) { - if (v1[0] < v2[0]) - { - tempv1[0] = 0., tempv1[1] = 0.; - tempv2[0] = 0., tempv2[1] = length12; - tempv3[0] = v3[0]-v1[0], tempv3[1] = v3[1]-v1[1]; - tempv4[0] = v4[0]-v1[0], tempv4[1] = v4[1]-v1[1]; - } - else - { - tempv2[0] = 0., tempv2[1] = 0.; - tempv1[0] = 0., tempv1[1] = length12; - tempv3[0] = v3[0]-v2[0], tempv3[1] = v3[1]-v2[1]; - tempv4[0] = v4[0]-v2[0], tempv4[1] = v4[1]-v2[1]; - } + if (v1[0] < v2[0]) + { + tempv1[0] = 0., tempv1[1] = 0.; + tempv2[0] = 0., tempv2[1] = length12; + tempv3[0] = v3[0]-v1[0], tempv3[1] = v3[1]-v1[1]; + tempv4[0] = v4[0]-v1[0], tempv4[1] = v4[1]-v1[1]; + } + else + { + tempv2[0] = 0., tempv2[1] = 0.; + tempv1[0] = 0., tempv1[1] = length12; + tempv3[0] = v3[0]-v2[0], tempv3[1] = v3[1]-v2[1]; + tempv4[0] = v4[0]-v2[0], tempv4[1] = v4[1]-v2[1]; + } } // Check the direction of the line (vector). // The origin of the new coordinate system is @@ -297,98 +299,106 @@ ParallelLinePathListFilter<TPath> if (v1[1] < v2[1]) { - if (v1[0] == v2[0]) + if (v1[0] == v2[0]) { - tempv1[0] = 0., tempv1[1] = 0.; - tempv2[0] = 0., tempv2[1] = length12; - tempv3[0] = v3[0]-v1[0], tempv3[1] = v3[1]-v1[1]; - tempv4[0] = v4[0]-v1[0], tempv4[1] = v4[1]-v1[1]; + tempv1[0] = 0., tempv1[1] = 0.; + tempv2[0] = 0., tempv2[1] = length12; + tempv3[0] = v3[0]-v1[0], tempv3[1] = v3[1]-v1[1]; + tempv4[0] = v4[0]-v1[0], tempv4[1] = v4[1]-v1[1]; } else - { - // Coordinates of the first line in the new coordinate system - tempv1[0] = 0.; - tempv1[1] = 0.; - tempv2[0] = 0.; - tempv2[1] = length12; + { + // Coordinates of the first line in the new coordinate system + tempv1[0] = 0.; + tempv1[1] = 0.; + tempv2[0] = 0.; + tempv2[1] = length12; - // Rotate the system clockwise + // Rotate the system clockwise double sinealpha; - if (v2[0] > v1[0]) - { sinealpha = (v2[0]-v1[0])/length12; } - else - { sinealpha = (v1[0]-v2[0])/length12; } - double alpha1 = vcl_asin(sinealpha); + if (v2[0] > v1[0]) + { + sinealpha = (v2[0]-v1[0])/length12; + } + else + { + sinealpha = (v1[0]-v2[0])/length12; + } + double alpha1 = vcl_asin(sinealpha); - // Translation - temptransv3[0] = v3[0] - v1[0]; - temptransv3[1] = v3[1] - v1[1]; - temptransv4[0] = v4[0] - v1[0]; - temptransv4[1] = v4[1] - v1[1]; + // Translation + temptransv3[0] = v3[0] - v1[0]; + temptransv3[1] = v3[1] - v1[1]; + temptransv4[0] = v4[0] - v1[0]; + temptransv4[1] = v4[1] - v1[1]; - // Rotation + // Rotation tempv3[0] = temptransv3[0]*cos(alpha1)+temptransv3[1]*sin(alpha1); - tempv3[1] = temptransv3[1]*cos(alpha1)-temptransv3[0]*sin(alpha1); - tempv4[0] = temptransv4[0]*cos(alpha1)+temptransv4[1]*sin(alpha1); - tempv4[1] = temptransv4[1]*cos(alpha1)-temptransv4[0]*sin(alpha1); + tempv3[1] = temptransv3[1]*cos(alpha1)-temptransv3[0]*sin(alpha1); + tempv4[0] = temptransv4[0]*cos(alpha1)+temptransv4[1]*sin(alpha1); + tempv4[1] = temptransv4[1]*cos(alpha1)-temptransv4[0]*sin(alpha1); - std::cout<< "tempv1[0], tempv1[1], tempv2[0], tempv2[1]: "; - std::cout<< tempv1[0] <<", " << tempv1[1] <<", " << tempv2[0] <<", " <<tempv2[1] << std::endl; - std::cout<< "Alpha: "<< alpha1 << std::endl; + std::cout<< "tempv1[0], tempv1[1], tempv2[0], tempv2[1]: "; + std::cout<< tempv1[0] <<", " << tempv1[1] <<", " << tempv2[0] <<", " <<tempv2[1] << std::endl; + std::cout<< "Alpha: "<< alpha1 << std::endl; std::cout<< "tempv3[0], tempv3[1], tempv4[0], tempv4[1]: "; - std::cout<< tempv3[0] <<", " << tempv3[1] <<", " << tempv4[0] <<", " <<tempv4[1] << std::endl; - std::cout<< "Calculated length of the second line: " << sqrt( pow((tempv4[0]-tempv3[0]),2) + pow((tempv4[1]-tempv3[1]),2) ) <<std::endl; - std::cout<< "Original length of line 1: " << length12 <<std::endl; - } + std::cout<< tempv3[0] <<", " << tempv3[1] <<", " << tempv4[0] <<", " <<tempv4[1] << std::endl; + std::cout<< "Calculated length of the second line: " << sqrt( pow((tempv4[0]-tempv3[0]),2) + pow((tempv4[1]-tempv3[1]),2) ) <<std::endl; + std::cout<< "Original length of line 1: " << length12 <<std::endl; + } } if (v2[1] < v1[1]) { - if (v1[0] == v2[0]) + if (v1[0] == v2[0]) { tempv2[0] = 0., tempv2[1] = 0.; - tempv1[0] = 0., tempv1[1] = length12; - tempv3[0] = v3[0]-v2[0], tempv3[1] = v3[1]-v2[1]; - tempv4[0] = v4[0]-v2[0], tempv4[1] = v4[1]-v2[1]; + tempv1[0] = 0., tempv1[1] = length12; + tempv3[0] = v3[0]-v2[0], tempv3[1] = v3[1]-v2[1]; + tempv4[0] = v4[0]-v2[0], tempv4[1] = v4[1]-v2[1]; } else { - tempv1[0] = 0.; - tempv1[1] = 0.; - tempv2[0] = 0.; - tempv2[1] = length12; - - // Rotate the system clockwise - double sinealpha; - if (v2[0] > v1[0]) - { sinealpha = (v2[0]-v1[0])/length12; } - else - { sinealpha = (v1[0]-v2[0])/length12; } + tempv1[0] = 0.; + tempv1[1] = 0.; + tempv2[0] = 0.; + tempv2[1] = length12; - double alpha1 = vcl_asin(sinealpha); + // Rotate the system clockwise + double sinealpha; + if (v2[0] > v1[0]) + { + sinealpha = (v2[0]-v1[0])/length12; + } + else + { + sinealpha = (v1[0]-v2[0])/length12; + } - // Translation - temptransv3[0] = v3[0] - v2[0]; - temptransv3[1] = v3[1] - v2[1]; - temptransv4[0] = v4[0] - v2[0]; - temptransv4[1] = v4[1] - v2[1]; + double alpha1 = vcl_asin(sinealpha); - // Rotation + // Translation + temptransv3[0] = v3[0] - v2[0]; + temptransv3[1] = v3[1] - v2[1]; + temptransv4[0] = v4[0] - v2[0]; + temptransv4[1] = v4[1] - v2[1]; + + // Rotation tempv3[0] = temptransv3[0]*cos(alpha1)+temptransv3[1]*sin(alpha1); - tempv3[1] = temptransv3[1]*cos(alpha1)-temptransv3[0]*sin(alpha1); - tempv4[0] = temptransv4[0]*cos(alpha1)+temptransv4[1]*sin(alpha1); - tempv4[1] = temptransv4[1]*cos(alpha1)-temptransv4[0]*sin(alpha1); + tempv3[1] = temptransv3[1]*cos(alpha1)-temptransv3[0]*sin(alpha1); + tempv4[0] = temptransv4[0]*cos(alpha1)+temptransv4[1]*sin(alpha1); + tempv4[1] = temptransv4[1]*cos(alpha1)-temptransv4[0]*sin(alpha1); - std::cout<< "tempv1[0], tempv1[1], tempv2[0], tempv2[1]: "; - std::cout<< tempv1[0] <<", " << tempv1[1] <<", " << tempv2[0] <<", " <<tempv2[1] << std::endl; - std::cout<< "Alpha: "<< alpha1 << std::endl; + std::cout<< "tempv1[0], tempv1[1], tempv2[0], tempv2[1]: "; + std::cout<< tempv1[0] <<", " << tempv1[1] <<", " << tempv2[0] <<", " <<tempv2[1] << std::endl; + std::cout<< "Alpha: "<< alpha1 << std::endl; std::cout<< "tempv3[0], tempv3[1], tempv4[0], tempv4[1]: "; - std::cout<< tempv3[0] <<", " << tempv3[1] <<", " << tempv4[0] <<", " <<tempv4[1] << std::endl; - std::cout<< "Calculated length of the second line: " << sqrt( pow((tempv4[0]-tempv3[0]),2) + pow((tempv4[1]-tempv3[1]),2) ) <<std::endl; + std::cout<< tempv3[0] <<", " << tempv3[1] <<", " << tempv4[0] <<", " <<tempv4[1] << std::endl; + std::cout<< "Calculated length of the second line: " << sqrt( pow((tempv4[0]-tempv3[0]),2) + pow((tempv4[1]-tempv3[1]),2) ) <<std::endl; std::cout<< "Original length of line 1: " << length12 <<std::endl; - } + } } // Compute the length of the overlapping part @@ -400,64 +410,80 @@ ParallelLinePathListFilter<TPath> if (tempv3[1] >= tempv4[1]) { - if (tempv3[1] >=0 && tempv3[1] <= tempv2[1]) - { - if (tempv4[1] >=0) - {commonDist = vcl_abs(tempv4[1]-tempv3[1]);} + if (tempv3[1] >=0 && tempv3[1] <= tempv2[1]) + { + if (tempv4[1] >=0) + { + commonDist = vcl_abs(tempv4[1]-tempv3[1]); + } - else if (tempv4[1] < 0) - {commonDist = tempv3[1];} - } + else if (tempv4[1] < 0) + { + commonDist = tempv3[1]; + } + } else if (tempv3[1] >= 0 && tempv3[1] >= tempv2[1]) - { - if (tempv4[1] >=0) - {commonDist = tempv2[1]-tempv4[1];} + { + if (tempv4[1] >=0) + { + commonDist = tempv2[1]-tempv4[1]; + } - else if (tempv4[1] < 0) - {commonDist = tempv2[1];} + else if (tempv4[1] < 0) + { + commonDist = tempv2[1]; + } - } - else if (tempv4[1] >= tempv2[1]) - { // No overlapping parts exist. The (negative) distance + } + else if (tempv4[1] >= tempv2[1]) + { // No overlapping parts exist. The (negative) distance // between the two closest endpoints is calculated. - commonDist = -vcl_abs(tempv4[1]-tempv2[1]); - } - else if (tempv3[1] < 0) - { // No overlapping parts exist. The (negative) distance + commonDist = -vcl_abs(tempv4[1]-tempv2[1]); + } + else if (tempv3[1] < 0) + { // No overlapping parts exist. The (negative) distance // between the two closest endpoints is calculated. - commonDist = tempv3[1]; - } + commonDist = tempv3[1]; + } } else { - if (tempv4[1] >=0 && tempv4[1] <= tempv2[1]) - { - if (tempv3[1] >=0) - {commonDist = vcl_abs(tempv3[1]-tempv4[1]);} + if (tempv4[1] >=0 && tempv4[1] <= tempv2[1]) + { + if (tempv3[1] >=0) + { + commonDist = vcl_abs(tempv3[1]-tempv4[1]); + } - else if (tempv3[1] < 0) - {commonDist = tempv4[1];} - } - else if (tempv4[1] >= 0 && tempv4[1] >= tempv2[1]) - { - if (tempv3[1] >=0) - {commonDist = tempv2[1]-tempv3[1];} + else if (tempv3[1] < 0) + { + commonDist = tempv4[1]; + } + } + else if (tempv4[1] >= 0 && tempv4[1] >= tempv2[1]) + { + if (tempv3[1] >=0) + { + commonDist = tempv2[1]-tempv3[1]; + } - else if (tempv3[1] < 0) - {commonDist = tempv2[1];} - - } - else if (tempv3[1] >= tempv2[1]) - { // No overlapping parts exist. The (negative) distance - // between the two closest endpoints is calculated. - commonDist = -vcl_abs(tempv3[1]-tempv2[1]); - } - else if (tempv4[1] < 0) - { // No overlapping parts exist. The (negative) distance + else if (tempv3[1] < 0) + { + commonDist = tempv2[1]; + } + + } + else if (tempv3[1] >= tempv2[1]) + { // No overlapping parts exist. The (negative) distance // between the two closest endpoints is calculated. - commonDist = tempv4[1]; - } + commonDist = -vcl_abs(tempv3[1]-tempv2[1]); + } + else if (tempv4[1] < 0) + { // No overlapping parts exist. The (negative) distance + // between the two closest endpoints is calculated. + commonDist = tempv4[1]; + } } // The common parallel parts of the two lines have to be greater than // the provided threshold. @@ -477,12 +503,14 @@ typename ParallelLinePathListFilter<TPath> ParallelLinePathListFilter<TPath> ::WriteParallelPath(PathPointerType p1) { - PathPointerType resp = PathType::New(); + PathPointerType resp = PathType::New(); VertexIteratorType it; - for(it=p1->GetVertexList()->Begin();it!=p1->GetVertexList()->End();++it) - { resp->AddVertex((it).Value()); } + for (it=p1->GetVertexList()->Begin();it!=p1->GetVertexList()->End();++it) + { + resp->AddVertex((it).Value()); + } return resp; } diff --git a/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.h b/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.h index fa7b87853248d7e5744be9c6ea67f4e39c165dee..85eac513e233eb04ae9dd8cf420735843ad42c57 100644 --- a/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.h +++ b/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.h @@ -53,10 +53,10 @@ class ITK_EXPORT PixelSuppressionByDirectionImageFilter : public itk::ImageToIm public: /** Extract input and output image dimensions */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); @@ -96,12 +96,12 @@ public: /** Get the angular beam. */ itkGetConstReferenceMacro(AngularBeam, InputRealType); - /** Set/Get the image input of this process object. */ + /** Set/Get the image input of this process object. */ void SetInputImage( const InputImageType *image); const InputImageType * GetInputImage(void); - void SetInputImageDirection( const InputImageType *image); - const InputImageType * GetInputImageDirection(void); + void SetInputImageDirection( const InputImageType *image); + const InputImageType * GetInputImageDirection(void); virtual void GenerateInputRequestedRegion() throw(itk::InvalidRequestedRegionError); diff --git a/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.txx b/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.txx index bb2d0947037b8c51b54411f0c9cc4e0fbe9d5a2a..ab622cd8fb7326ac9d7be8b2f6fafb78c908588d 100644 --- a/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.txx +++ b/Code/FeatureExtraction/otbPixelSuppressionByDirectionImageFilter.txx @@ -69,12 +69,12 @@ PixelSuppressionByDirectionImageFilter<TInputImage, TOutputImage> ::GetInputImage(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<const TInputImage * > - (this->GetInput(0) ); + (this->GetInput(0) ); } template <class TInputImage, class TOutputImage> @@ -84,12 +84,12 @@ PixelSuppressionByDirectionImageFilter<TInputImage, TOutputImage> ::GetInputImageDirection(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<const TInputImage * > - (this->GetInput(1) ); + (this->GetInput(1) ); } template <class TInputImage, class TOutputImage> @@ -103,9 +103,9 @@ void PixelSuppressionByDirectionImageFilter<TInputImage, TOutputImage>::Generate typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -117,12 +117,12 @@ void PixelSuppressionByDirectionImageFilter<TInputImage, TOutputImage>::Generate // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -133,20 +133,20 @@ void PixelSuppressionByDirectionImageFilter<TInputImage, TOutputImage>::Generate itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << static_cast<const char *>(this->GetNameOfClass()) - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } template< class TInputImage, class TOutputImage> void PixelSuppressionByDirectionImageFilter< TInputImage, TOutputImage>::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - int threadId - ) + const OutputImageRegionType& outputRegionForThread, + int threadId +) { itk::ConstantBoundaryCondition<InputImageType> cbc; @@ -200,7 +200,7 @@ void PixelSuppressionByDirectionImageFilter< TInputImage, TOutputImage>::Threade // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, inputDirection, *fit); itin = itk::ImageRegionConstIterator<InputImageType>(input, *fit); @@ -211,14 +211,14 @@ void PixelSuppressionByDirectionImageFilter< TInputImage, TOutputImage>::Threade while ( ! bit.IsAtEnd() ) - { + { /*// Location of the central pixel of the region in the input image bitIndex = bit.GetIndex(); Xc = bitIndex[0]; Yc = bitIndex[1]; - */ + */ // Get Pixel Direction from the image of directions ThetaXcYc = static_cast<double>( bit.GetCenterPixel() ); @@ -230,61 +230,61 @@ void PixelSuppressionByDirectionImageFilter< TInputImage, TOutputImage>::Threade typename itk::ConstNeighborhoodIterator<InputImageType>::OffsetType off; // Loop on the region for (unsigned int i = 0; i < 2*m_Radius[0]+1; ++i) - for (unsigned int j = 0; j < 2*m_Radius[1]+1; ++j) + for (unsigned int j = 0; j < 2*m_Radius[1]+1; ++j) { - off[0]=i-m_Radius[0]; - off[1]=j-m_Radius[1]; + off[0]=i-m_Radius[0]; + off[1]=j-m_Radius[1]; - x = off[0]; - y = off[1]; + x = off[0]; + y = off[1]; - // No calculation on the central pixel - if (( x == 0 ) && ( y == 0 )) - continue; + // No calculation on the central pixel + if (( x == 0 ) && ( y == 0 )) + continue; - Thetaxtyt = vcl_atan2( static_cast<double>(y), static_cast<double>(x) ); //result is [-PI,PI] - while(Thetaxtyt < 0) - Thetaxtyt = M_PI + Thetaxtyt; // Theta is now [0,PI] as is + Thetaxtyt = vcl_atan2( static_cast<double>(y), static_cast<double>(x) ); //result is [-PI,PI] + while (Thetaxtyt < 0) + Thetaxtyt = M_PI + Thetaxtyt; // Theta is now [0,PI] as is // the result of detectors - while(Thetaxtyt > M_PI/2.0) - Thetaxtyt = Thetaxtyt-M_PI; // Theta is now [-PI/2,PI/2] - - - if( (vcl_abs(vcl_cos(Thetaxtyt-ThetaXcYc)) >= vcl_cos(m_AngularBeam)) // this - // pixel - // is - // in - // the - // angular beam - && (vcl_abs(vcl_cos(bit.GetPixel(off)-ThetaXcYc)) >= vcl_cos(m_AngularBeam)) ) //and - //its - //direction - //is - //also - //in - //the beam - { - IsLine = true; - continue; - } - - - } + while (Thetaxtyt > M_PI/2.0) + Thetaxtyt = Thetaxtyt-M_PI; // Theta is now [-PI/2,PI/2] + + + if ( (vcl_abs(vcl_cos(Thetaxtyt-ThetaXcYc)) >= vcl_cos(m_AngularBeam)) // this + // pixel + // is + // in + // the + // angular beam + && (vcl_abs(vcl_cos(bit.GetPixel(off)-ThetaXcYc)) >= vcl_cos(m_AngularBeam)) ) //and + //its + //direction + //is + //also + //in + //the beam + { + IsLine = true; + continue; + } + + + } // end of the loop on the pixels of the region // Assignment of this value to the output pixel if (IsLine == true) - { - itout.Set( static_cast<OutputPixelType>(PixelValue) ); - } + { + itout.Set( static_cast<OutputPixelType>(PixelValue) ); + } else - { - itout.Set( static_cast<OutputPixelType>(0.) ); - } + { + itout.Set( static_cast<OutputPixelType>(0.) ); + } ++bit; @@ -292,9 +292,9 @@ void PixelSuppressionByDirectionImageFilter< TInputImage, TOutputImage>::Threade ++itout; progress.CompletedPixel(); - } - } + + } } /** diff --git a/Code/FeatureExtraction/otbRealMomentImageFunction.h b/Code/FeatureExtraction/otbRealMomentImageFunction.h index 9123335a352fe903e2debe89b03429b36d3b5f55..b7609bb06fed84f010544b9f7c1ddbcfbacdbfaa 100644 --- a/Code/FeatureExtraction/otbRealMomentImageFunction.h +++ b/Code/FeatureExtraction/otbRealMomentImageFunction.h @@ -32,11 +32,11 @@ namespace otb */ template < class TInput, - class TOutput = float, - class TPrecision = double, - class TCoordRep = float > +class TOutput = float, +class TPrecision = double, +class TCoordRep = float > class ITK_EXPORT RealMomentImageFunction : - public GeometricMomentImageFunction<TInput, TOutput, TPrecision, TCoordRep > + public GeometricMomentImageFunction<TInput, TOutput, TPrecision, TCoordRep > { public: /** Standard class typedefs. */ @@ -66,11 +66,11 @@ public: protected: RealMomentImageFunction() {}; - ~RealMomentImageFunction(){}; + ~RealMomentImageFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf( os, indent ); - } + { + Superclass::PrintSelf( os, indent ); + } private: RealMomentImageFunction( const Self& ); //purposely not implemented diff --git a/Code/FeatureExtraction/otbRealMomentPathFunction.h b/Code/FeatureExtraction/otbRealMomentPathFunction.h index ef92b78d614a25b75262b339e605bb8082d37685..26502106efd95f00f3fb0f59ebc20bc86bb8eb73 100644 --- a/Code/FeatureExtraction/otbRealMomentPathFunction.h +++ b/Code/FeatureExtraction/otbRealMomentPathFunction.h @@ -33,10 +33,10 @@ namespace otb */ template < class TInputPath, - class TOutput = double, - class TPrecision = double> +class TOutput = double, +class TPrecision = double> class ITK_EXPORT RealMomentPathFunction : - public GeometricMomentPathFunction< TInputPath, TOutput, TPrecision> + public GeometricMomentPathFunction< TInputPath, TOutput, TPrecision> { public: /** Standard class typedefs. */ @@ -66,12 +66,15 @@ public: itkGetConstReferenceMacro(Step, float); protected: - RealMomentPathFunction() {m_Step = 1.0;} - ~RealMomentPathFunction(){}; + RealMomentPathFunction() + { + m_Step = 1.0; + } + ~RealMomentPathFunction() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf( os, indent ); - } + { + Superclass::PrintSelf( os, indent ); + } private: RealMomentPathFunction( const Self& ); //purposely not implemented diff --git a/Code/FeatureExtraction/otbRemoveCarvingPathFilter.txx b/Code/FeatureExtraction/otbRemoveCarvingPathFilter.txx index 6635eff2778693bbc1727de1a9c08c068fa61a06..11a81cb467921117b730310e816aacca2038d93f 100644 --- a/Code/FeatureExtraction/otbRemoveCarvingPathFilter.txx +++ b/Code/FeatureExtraction/otbRemoveCarvingPathFilter.txx @@ -71,7 +71,7 @@ RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> InputIteratorType inputIterator(inputImage, inputImage->GetLargestPossibleRegion()); OutputIteratorType outputIterator(outputImage, - outputImage->GetLargestPossibleRegion()); + outputImage->GetLargestPossibleRegion()); unsigned int dir0; unsigned int dir1; @@ -102,7 +102,7 @@ RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> //go to the end of the path pathIterator = vertexList->Begin(); - while(pathIterator != vertexList->End()) + while (pathIterator != vertexList->End()) { ++pathIterator; } @@ -112,22 +112,22 @@ RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> { while (!inputIterator.IsAtEndOfSlice()) { - while(!inputIterator.IsAtEndOfLine()) + while (!inputIterator.IsAtEndOfLine()) { index = inputIterator.GetIndex(); - if(index[dir1] != line) + if (index[dir1] != line) { line = index[dir1]; typename InputImageType::PointType tmpIndex; inputImage->TransformContinuousIndexToPhysicalPoint(pathIterator.Value(),tmpIndex); inputImage->TransformPhysicalPointToIndex(tmpIndex,indexToRemove); - if(pathIterator!=vertexList->Begin()) + if (pathIterator!=vertexList->Begin()) { --pathIterator; } - if(index[dir1] != indexToRemove[dir1]) + if (index[dir1] != indexToRemove[dir1]) { itkExceptionMacro(<< "Error!!!"); } @@ -163,9 +163,9 @@ RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> } template <class TInputImage, class TInputPath,class TOutputImage> - void - RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> - ::GenerateOutputInformation() +void +RemoveCarvingPathFilter<TInputImage,TInputPath,TOutputImage> +::GenerateOutputInformation() { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); @@ -191,11 +191,11 @@ template <class TInputImage, class TInputPath,class TOutputImage> // we need to compute the output spacing, the output image size, and the // output image start index const typename TInputImage::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename TInputImage::SizeType& inputSize - = inputPtr->GetLargestPossibleRegion().GetSize(); + = inputPtr->GetLargestPossibleRegion().GetSize(); const typename TInputImage::IndexType& inputStartIndex - = inputPtr->GetLargestPossibleRegion().GetIndex(); + = inputPtr->GetLargestPossibleRegion().GetIndex(); typename TOutputImage::SpacingType outputSpacing; typename TOutputImage::SizeType outputSize; diff --git a/Code/FeatureExtraction/otbRemoveIsolatedByDirectionFilter.h b/Code/FeatureExtraction/otbRemoveIsolatedByDirectionFilter.h index 438212db28221da22c14a6bbe37e2ee3be56a67a..7b11a50113608db703872ada19708ee0deae5dfe 100644 --- a/Code/FeatureExtraction/otbRemoveIsolatedByDirectionFilter.h +++ b/Code/FeatureExtraction/otbRemoveIsolatedByDirectionFilter.h @@ -24,42 +24,42 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class RemoveIsolatedByDirectionFunctor - * \brief Binary neighborhood functor to remove isolated pixels by direction. - * Used by the RemoveIsolatedByDirectionFilter. - * \sa RemoveIsolatedByDirectionFilter - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class RemoveIsolatedByDirectionFunctor - { - public: +{ +/** \class RemoveIsolatedByDirectionFunctor + * \brief Binary neighborhood functor to remove isolated pixels by direction. + * Used by the RemoveIsolatedByDirectionFilter. + * \sa RemoveIsolatedByDirectionFilter + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class RemoveIsolatedByDirectionFunctor +{ +public: RemoveIsolatedByDirectionFunctor() {}; ~RemoveIsolatedByDirectionFunctor() {}; inline TOutput operator()(const TInput1 & itA, const TInput2 &itB) + { + double currentDirection = itB.GetCenterPixel(); + int nEqualNeighbors = 0; + for (int neighborhoodIndex=0; neighborhoodIndex < 9; ++neighborhoodIndex) + { + if (itB.GetPixel(neighborhoodIndex) == currentDirection) + { + ++nEqualNeighbors; + } + } + if (nEqualNeighbors <= 1) { - double currentDirection = itB.GetCenterPixel(); - int nEqualNeighbors = 0; - for (int neighborhoodIndex=0; neighborhoodIndex < 9; ++neighborhoodIndex) - { - if (itB.GetPixel(neighborhoodIndex) == currentDirection) - { - ++nEqualNeighbors; - } - } - if (nEqualNeighbors <= 1) - { - //should never be 0 as it is at least equal to itself - return 0; - } - else - { - return static_cast<TOutput>(itA.GetCenterPixel()); - } + //should never be 0 as it is at least equal to itself + return 0; + } + else + { + return static_cast<TOutput>(itA.GetCenterPixel()); } - }; } +}; +} /** \class RemoveIsolatedByDirectionFilter * \brief This filter removes (sets to null intensity) pixels isolated by direction. * @@ -74,9 +74,9 @@ namespace Functor */ template <class TInputModulus, class TInputDirection, class TOutputImage> class ITK_EXPORT RemoveIsolatedByDirectionFilter - : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> + : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> { - public: +public: /** Standard typedefs */ typedef RemoveIsolatedByDirectionFilter Self; typedef ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> Superclass; @@ -92,31 +92,31 @@ class ITK_EXPORT RemoveIsolatedByDirectionFilter /** typedef of the computing filter (this allows us to derive from ModulusAndDirectionToImageFilter as well as using the BinaryFunctorNeighBorhoodImageFilter, which is appropriate here */ typedef Functor::RemoveIsolatedByDirectionFunctor< - typename itk::ConstNeighborhoodIterator<TInputModulus>, - typename itk::ConstNeighborhoodIterator<TInputDirection>, - typename TOutputImage::PixelType> FunctorType; + typename itk::ConstNeighborhoodIterator<TInputModulus>, + typename itk::ConstNeighborhoodIterator<TInputDirection>, + typename TOutputImage::PixelType> FunctorType; typedef otb::BinaryFunctorNeighborhoodImageFilter<TInputModulus, TInputDirection,TOutputImage,FunctorType> ComputingFilterType; protected: /** Constructor */ - RemoveIsolatedByDirectionFilter(){}; + RemoveIsolatedByDirectionFilter() {}; /** Destructor */ virtual ~RemoveIsolatedByDirectionFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; /** Main computation method */ virtual void GenerateData(void) - { - typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); - filter->SetInput1(this->GetInput()); - filter->SetInput2(this->GetInputDirection()); - filter->GraftOutput(this->GetOutput()); - filter->Update(); - this->GraftOutput(filter->GetOutput()); - } + { + typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); + filter->SetInput1(this->GetInput()); + filter->SetInput2(this->GetInputDirection()); + filter->GraftOutput(this->GetOutput()); + filter->Update(); + this->GraftOutput(filter->GetOutput()); + } private: RemoveIsolatedByDirectionFilter(const Self&); //purposely not implemented diff --git a/Code/FeatureExtraction/otbRemoveTortuousPathListFilter.h b/Code/FeatureExtraction/otbRemoveTortuousPathListFilter.h index b36eb5ed9078b7e9cd7744023ba6eeef4837f0f5..9b61c5275a0970f7125be2958e0ab27ddad48130 100644 --- a/Code/FeatureExtraction/otbRemoveTortuousPathListFilter.h +++ b/Code/FeatureExtraction/otbRemoveTortuousPathListFilter.h @@ -49,13 +49,13 @@ namespace otb */ // template <class TPath> - template <class TPath> - class ITK_EXPORT RemoveTortuousPathListFilter : +template <class TPath> +class ITK_EXPORT RemoveTortuousPathListFilter : public UnaryFunctorObjectListBooleanFilter< - ObjectList<TPath>, - ObjectList<TPath>, - PathMeanDistanceFunctor<typename TPath::Pointer> > - {}; + ObjectList<TPath>, + ObjectList<TPath>, + PathMeanDistanceFunctor<typename TPath::Pointer> > + {}; }// End namespace otb diff --git a/Code/FeatureExtraction/otbRemoveWrongDirectionFilter.h b/Code/FeatureExtraction/otbRemoveWrongDirectionFilter.h index b1504ef27c6b2b656230d3c9fd1e466d0e16f3fd..3e4335afe07517d7b33ed27d7787c8451ffeeef7 100644 --- a/Code/FeatureExtraction/otbRemoveWrongDirectionFilter.h +++ b/Code/FeatureExtraction/otbRemoveWrongDirectionFilter.h @@ -25,35 +25,35 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class RemoveWrongDirectionFunctor - * \brief This functor is used by the RemoveWrongDirectionFilter - * - * \sa RemoveWrongDirectionFilter - * \ingroup Functor - * - * \example FeatureExtraction/ExtractRoadByStepsExample.cxx - * - */ - template <class TInput1, class TInput2, class TOutput> - class RemoveWrongDirectionFunctor - { - public: +{ +/** \class RemoveWrongDirectionFunctor + * \brief This functor is used by the RemoveWrongDirectionFilter + * + * \sa RemoveWrongDirectionFilter + * \ingroup Functor + * + * \example FeatureExtraction/ExtractRoadByStepsExample.cxx + * + */ +template <class TInput1, class TInput2, class TOutput> +class RemoveWrongDirectionFunctor +{ +public: RemoveWrongDirectionFunctor() {}; ~RemoveWrongDirectionFunctor() {}; inline TOutput operator()(const TInput1 &A, const TInput2 &B) + { + if (B < M_PI/8) { - if(B < M_PI/8) - { - return 0; - } - else - { - return A; - } + return 0; + } + else + { + return A; } - }; } +}; +} /** \class RemoveWrongDirectionFilter * \brief This filter removes (sets to null intensity) pixels with wrong direction. * @@ -70,9 +70,9 @@ namespace Functor */ template <class TInputModulus, class TInputDirection, class TOutputImage> class ITK_EXPORT RemoveWrongDirectionFilter - : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> + : public ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> { - public: +public: /** Standard typedefs */ typedef RemoveWrongDirectionFilter Self; typedef ModulusAndDirectionImageToImageFilter<TInputModulus, TInputDirection, TOutputImage> Superclass; @@ -88,31 +88,31 @@ class ITK_EXPORT RemoveWrongDirectionFilter /** typedef of the computing filter (this allows us to derive from ModulusAndDirectionToImageFilter as well as using the BinaryFunctorImageFilter, which is appropriate here */ typedef Functor::RemoveWrongDirectionFunctor< - typename TInputModulus::PixelType, - typename TInputDirection::PixelType, - typename TOutputImage::PixelType> FunctorType; + typename TInputModulus::PixelType, + typename TInputDirection::PixelType, + typename TOutputImage::PixelType> FunctorType; typedef itk::BinaryFunctorImageFilter<TInputModulus, TInputDirection,TOutputImage,FunctorType> ComputingFilterType; protected: /** Constructor */ - RemoveWrongDirectionFilter(){}; + RemoveWrongDirectionFilter() {}; /** Destructor */ virtual ~RemoveWrongDirectionFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; /** Main computation method */ virtual void GenerateData(void) - { - typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); - filter->SetInput1(this->GetInput()); - filter->SetInput2(this->GetInputDirection()); - filter->GraftOutput(this->GetOutput()); - filter->Update(); - this->GraftOutput(filter->GetOutput()); - } + { + typename ComputingFilterType::Pointer filter = ComputingFilterType::New(); + filter->SetInput1(this->GetInput()); + filter->SetInput2(this->GetInputDirection()); + filter->GraftOutput(this->GetOutput()); + filter->Update(); + this->GraftOutput(filter->GetOutput()); + } private: RemoveWrongDirectionFilter(const Self&); //purposely not implemented diff --git a/Code/FeatureExtraction/otbRoadExtractionFilter.h b/Code/FeatureExtraction/otbRoadExtractionFilter.h index 14ad9e27aee88fdbdc42816f3c16a2acb41b4efe..ab7b48f542f2a07d69ec58425e6a079febadf48c 100644 --- a/Code/FeatureExtraction/otbRoadExtractionFilter.h +++ b/Code/FeatureExtraction/otbRoadExtractionFilter.h @@ -59,51 +59,51 @@ namespace otb * */ template <class TInputImage, class TOutputPath> - class ITK_EXPORT RoadExtractionFilter - : public ImageToPathListFilter<TInputImage,TOutputPath> - { - public : - /** Standard typedefs */ - typedef RoadExtractionFilter Self; - typedef ImageToPathListFilter<TInputImage,TOutputPath> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory macro */ - itkNewMacro(Self); - /** Type macro */ - itkTypeMacro(RoadExtractionFilter,ImageToPathListFilter); - /** Template parameters typedefs */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::OutputPathType OutputPathType; - typedef typename Superclass::OutputPathListType OutputPathListType; - typedef typename InputImageType::PixelType InputPixelType; - typedef double InternalPixelType; - - typedef otb::VectorImage<InternalPixelType,InputImageType::ImageDimension> VectorImageType; - typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> SpectralAngleType; - typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> ModulusType; - typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> DirectionType; - - typedef itk::CovariantVector<InternalPixelType,InputImageType::ImageDimension> - VectorPixelType; - typedef otb::Image<VectorPixelType,InputImageType::ImageDimension> CovariantVectorImageType; - - /* Template parameters typedefs for composites filters */ - typedef SpectralAngleDistanceImageFilter< - InputImageType, - SpectralAngleType> SpectralAngleDistanceImageFilterType; - - typedef GenericRoadExtractionFilter<SpectralAngleType, OutputPathType> - GenericRoadExtractionFilterType; - - - /** Template parameters typedefs for internals filters */ - typedef typename GenericRoadExtractionFilterType::SigmaType SigmaType; - typedef typename GenericRoadExtractionFilterType::AmplitudeThresholdType AmplitudeThresholdType; - typedef typename GenericRoadExtractionFilterType::ToleranceType ToleranceType; - typedef typename GenericRoadExtractionFilterType::MaxAngleType MaxAngleType; - typedef typename GenericRoadExtractionFilterType::MeanDistanceThresholdType MeanDistanceThresholdType; - typedef typename GenericRoadExtractionFilterType::LinkRealType LinkRealType; +class ITK_EXPORT RoadExtractionFilter + : public ImageToPathListFilter<TInputImage,TOutputPath> +{ +public : + /** Standard typedefs */ + typedef RoadExtractionFilter Self; + typedef ImageToPathListFilter<TInputImage,TOutputPath> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory macro */ + itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(RoadExtractionFilter,ImageToPathListFilter); + /** Template parameters typedefs */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::OutputPathType OutputPathType; + typedef typename Superclass::OutputPathListType OutputPathListType; + typedef typename InputImageType::PixelType InputPixelType; + typedef double InternalPixelType; + + typedef otb::VectorImage<InternalPixelType,InputImageType::ImageDimension> VectorImageType; + typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> SpectralAngleType; + typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> ModulusType; + typedef otb::Image<InternalPixelType,InputImageType::ImageDimension> DirectionType; + + typedef itk::CovariantVector<InternalPixelType,InputImageType::ImageDimension> + VectorPixelType; + typedef otb::Image<VectorPixelType,InputImageType::ImageDimension> CovariantVectorImageType; + + /* Template parameters typedefs for composites filters */ + typedef SpectralAngleDistanceImageFilter< + InputImageType, + SpectralAngleType> SpectralAngleDistanceImageFilterType; + + typedef GenericRoadExtractionFilter<SpectralAngleType, OutputPathType> + GenericRoadExtractionFilterType; + + + /** Template parameters typedefs for internals filters */ + typedef typename GenericRoadExtractionFilterType::SigmaType SigmaType; + typedef typename GenericRoadExtractionFilterType::AmplitudeThresholdType AmplitudeThresholdType; + typedef typename GenericRoadExtractionFilterType::ToleranceType ToleranceType; + typedef typename GenericRoadExtractionFilterType::MaxAngleType MaxAngleType; + typedef typename GenericRoadExtractionFilterType::MeanDistanceThresholdType MeanDistanceThresholdType; + typedef typename GenericRoadExtractionFilterType::LinkRealType LinkRealType; /** Get/Set the reference pixel (use by the SpectralAngleDistanceImageFilter)*/ otbGetObjectMemberConstReferenceMacro(SpectralAngleDistanceImageFilter,ReferencePixel,InputPixelType); @@ -138,32 +138,32 @@ template <class TInputImage, class TOutputPath> otbSetObjectMemberMacro(GenericRoadExtractionFilter,DistanceThreshold,LinkRealType); otbGetObjectMemberMacro(GenericRoadExtractionFilter,DistanceThreshold,LinkRealType); - protected: - /** Constructor */ - RoadExtractionFilter(); - /** Destructor */ - ~RoadExtractionFilter() {}; +protected: + /** Constructor */ + RoadExtractionFilter(); + /** Destructor */ + ~RoadExtractionFilter() {}; - /** Prepare main computation method */ - void BeforeGenerateData(void); + /** Prepare main computation method */ + void BeforeGenerateData(void); - /** Main computation method */ - void GenerateData(void); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Main computation method */ + void GenerateData(void); + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : +private : - RoadExtractionFilter(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented + RoadExtractionFilter(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented - /** SpectralAngleDistanceImageFilter use by the composite filter */ - typename SpectralAngleDistanceImageFilterType::Pointer m_SpectralAngleDistanceImageFilter; - typename GenericRoadExtractionFilterType::Pointer m_GenericRoadExtractionFilter; + /** SpectralAngleDistanceImageFilter use by the composite filter */ + typename SpectralAngleDistanceImageFilterType::Pointer m_SpectralAngleDistanceImageFilter; + typename GenericRoadExtractionFilterType::Pointer m_GenericRoadExtractionFilter; - }; +}; }// End namespace otb diff --git a/Code/FeatureExtraction/otbRoadExtractionFilter.txx b/Code/FeatureExtraction/otbRoadExtractionFilter.txx index 7d93424e2f686ee6510e83887f226f69234b2189..ab31b8243c7f92be0b8a9639a7e96fda5b5318ce 100644 --- a/Code/FeatureExtraction/otbRoadExtractionFilter.txx +++ b/Code/FeatureExtraction/otbRoadExtractionFilter.txx @@ -30,11 +30,11 @@ template <class TInputImage,class TOutputPath> RoadExtractionFilter<TInputImage, TOutputPath> ::RoadExtractionFilter() { - this->SetNumberOfRequiredInputs(1); - this->SetNumberOfRequiredOutputs(1); + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); - m_SpectralAngleDistanceImageFilter = SpectralAngleDistanceImageFilterType::New(); - m_GenericRoadExtractionFilter = GenericRoadExtractionFilterType::New(); + m_SpectralAngleDistanceImageFilter = SpectralAngleDistanceImageFilterType::New(); + m_GenericRoadExtractionFilter = GenericRoadExtractionFilterType::New(); } @@ -48,21 +48,21 @@ RoadExtractionFilter<TInputImage, TOutputPath> ::GenerateData() { // Input images pointers - typename InputImageType::ConstPointer inputImage = this->GetInput(); - typename OutputPathListType::Pointer outputPathList = this->GetOutput(); + typename InputImageType::ConstPointer inputImage = this->GetInput(); + typename OutputPathListType::Pointer outputPathList = this->GetOutput(); m_SpectralAngleDistanceImageFilter->SetInput(inputImage); m_GenericRoadExtractionFilter->SetInput(m_SpectralAngleDistanceImageFilter->GetOutput()); m_GenericRoadExtractionFilter->Update(); - for(typename GenericRoadExtractionFilterType::OutputPathListType::ConstIterator it - = m_GenericRoadExtractionFilter->GetOutput()->Begin(); - it!=m_GenericRoadExtractionFilter->GetOutput()->End(); - ++it) - { - outputPathList->PushBack(it.Get()); - } + for (typename GenericRoadExtractionFilterType::OutputPathListType::ConstIterator it + = m_GenericRoadExtractionFilter->GetOutput()->Begin(); + it!=m_GenericRoadExtractionFilter->GetOutput()->End(); + ++it) + { + outputPathList->PushBack(it.Get()); + } } /** * PrintSelf method diff --git a/Code/FeatureExtraction/otbShape.h b/Code/FeatureExtraction/otbShape.h index 7d83a19596421a04907ac05b12d18c63a00acaec..a6be17e86933f6c4eccc25bfa313bdea2757659e 100644 --- a/Code/FeatureExtraction/otbShape.h +++ b/Code/FeatureExtraction/otbShape.h @@ -45,7 +45,7 @@ public: short y; Point_plane() - { + { x = -1; y = -1; } @@ -83,7 +83,7 @@ public: Shape* mw_get_next_sibling_shape(Shape *sh); Shape() - { + { inferior_type = 0; value = 0.0; open = 0; @@ -93,14 +93,14 @@ public: parent = NULL; next_sibling = NULL; child = NULL; - } + } ~Shape() - { + { if (pixels != NULL) delete[] pixels; pixels = NULL; area = 0; - } + } protected: @@ -138,18 +138,18 @@ public: Shape* mw_get_smallest_shape(int iX,int iY); -/* For each shape, find its number of proper pixels */ + /* For each shape, find its number of proper pixels */ void compute_proper_pixels(int *tabNbOfProperPixels); -/* Allocate the array of pixels of each shape. Thanks to the tree structure, -we allocate only memory for the pixels of the root, and other arrays are -just pointers */ + /* Allocate the array of pixels of each shape. Thanks to the tree structure, + we allocate only memory for the pixels of the root, and other arrays are + just pointers */ void allocate_pixels(int* tabNbOfProperPixels); -/* Associate to each shape its array of pixels. Fills the field PIXELS of -the tree structure. From the command line, this function has no interest, -since that field is not saved to the file. It is meant to be called from -another module, when this field is needed */ + /* Associate to each shape its array of pixels. Fills the field PIXELS of + the tree structure. From the command line, this function has no interest, + since that field is not saved to the file. It is meant to be called from + another module, when this field is needed */ void flst_pixels(); @@ -160,35 +160,35 @@ another module, when this field is needed */ void TURN_LEFT(int *dir); void TURN_RIGHT(int *dir); -/* Is the point in the shape? */ + /* Is the point in the shape? */ char point_in_shape(int x,int y,Shape *pShape); void find_next_dual_point(Point_plane *pDualPoint, int *cDirection, - Shape *pShape); + Shape *pShape); int find_closed_boundary(Shape *pShape,PathPointer pBoundary); -/* Find an initial point (to follow the boundary) at the border of the image */ + /* Find an initial point (to follow the boundary) at the border of the image */ void initial_point_border(Point_plane *pDualPoint, - int *cDirection,Shape *pShape); -/* Find an open boundary */ + int *cDirection,Shape *pShape); + /* Find an open boundary */ void find_open_boundary(Shape *pShape,PathPointer pBoundary); PathPointer flst_shape_boundary(Shape *pShape); Shapes() - { + { the_shapes = NULL; smallest_shape = NULL; nb_shapes = 0; nrow = 0; ncol = 0; interpolation = 0; - } + } ~Shapes() - { - if((the_shapes != NULL) && (nb_shapes > 0)) - delete[] (the_shapes[0].pixels); - if (the_shapes != NULL) delete[] the_shapes; - if (smallest_shape != NULL) delete[] smallest_shape; - } + { + if ((the_shapes != NULL) && (nb_shapes > 0)) + delete[] (the_shapes[0].pixels); + if (the_shapes != NULL) delete[] the_shapes; + if (smallest_shape != NULL) delete[] smallest_shape; + } protected: diff --git a/Code/FeatureExtraction/otbShape.txx b/Code/FeatureExtraction/otbShape.txx index e3166e02bd9865d4e03124030121a9e4cc3803e0..92bbd51279de92fd4d73230b3fdbd11fcb94f23d 100644 --- a/Code/FeatureExtraction/otbShape.txx +++ b/Code/FeatureExtraction/otbShape.txx @@ -43,10 +43,10 @@ Shape* Shape::mw_get_not_removed_shape(Shape *sh) { Shape *NotSup = NULL; - if((sh == NULL) || (!sh->removed)) + if ((sh == NULL) || (!sh->removed)) return(sh); - for(sh = sh->child; sh != NULL; sh = sh->next_sibling) - if((NotSup = mw_get_not_removed_shape(sh)) != NULL) + for (sh = sh->child; sh != NULL; sh = sh->next_sibling) + if ((NotSup = mw_get_not_removed_shape(sh)) != NULL) break; return(NotSup); } @@ -56,21 +56,21 @@ Shape::mw_get_not_removed_shape(Shape *sh) Shape* Shape::mw_get_parent_shape(Shape *sh) { - if(sh == NULL) - { - std::cerr <<"[mw_get_parent_shape] input shape structure is NULL" << std::endl; - return(NULL); - } - if(sh->parent == NULL) /* It is the root of the shape */ + if (sh == NULL) + { + std::cerr <<"[mw_get_parent_shape] input shape structure is NULL" << std::endl; + return(NULL); + } + if (sh->parent == NULL) /* It is the root of the shape */ return(NULL); do - if((sh = sh->parent) == NULL) - { - std::cerr << "[mw_get_parent_shape] the root of the shapes is removed" << std::endl; - return(NULL); - } - while(sh->removed); + if ((sh = sh->parent) == NULL) + { + std::cerr << "[mw_get_parent_shape] the root of the shapes is removed" << std::endl; + return(NULL); + } + while (sh->removed); return(sh); } @@ -80,13 +80,13 @@ Shape* Shape::mw_get_first_child_shape(Shape *sh) { Shape *NotSup = NULL; - if(sh == NULL) - { - std::cerr << "[mw_get_first_child_shape] input shape is NULL" << std::endl; - return(NULL); - } - for(sh = sh->child; sh != NULL; sh = sh->next_sibling) - if((NotSup = mw_get_not_removed_shape(sh)) != NULL) + if (sh == NULL) + { + std::cerr << "[mw_get_first_child_shape] input shape is NULL" << std::endl; + return(NULL); + } + for (sh = sh->child; sh != NULL; sh = sh->next_sibling) + if ((NotSup = mw_get_not_removed_shape(sh)) != NULL) break; return(NotSup); } @@ -99,26 +99,27 @@ Shape::mw_get_next_sibling_shape(Shape *sh) { Shape *sh1 = NULL; Shape *sh2 = NULL; - if(sh == NULL) - { - std::cerr <<"[mw_get_next_sibling_shape] input shape is NULL"; - return(NULL); - } + if (sh == NULL) + { + std::cerr <<"[mw_get_next_sibling_shape] input shape is NULL"; + return(NULL); + } /* First look at the siblings in the original tree */ - for(sh1 = sh->next_sibling; sh1 != NULL; sh1 = sh1->next_sibling) - if((sh2 = mw_get_not_removed_shape(sh1)) != NULL) + for (sh1 = sh->next_sibling; sh1 != NULL; sh1 = sh1->next_sibling) + if ((sh2 = mw_get_not_removed_shape(sh1)) != NULL) return(sh2); - if(sh->parent == NULL || ! sh->parent->removed) + if (sh->parent == NULL || ! sh->parent->removed) return(NULL); /* The parent in the original tree is also the parent in the true tree, nothing more to do */ /* If not found, find the node in the original tree just before the true parent */ do - { - sh = sh->parent; - /* Look at the siblings of this node */ - for(sh1 = sh->next_sibling; sh1 != NULL; sh1 = sh1->next_sibling) - if((sh2 = mw_get_not_removed_shape(sh1)) != NULL) - return(sh2); - } while(sh->parent->removed); + { + sh = sh->parent; + /* Look at the siblings of this node */ + for (sh1 = sh->next_sibling; sh1 != NULL; sh1 = sh1->next_sibling) + if ((sh2 = mw_get_not_removed_shape(sh1)) != NULL) + return(sh2); + } + while (sh->parent->removed); return(NULL); } @@ -138,19 +139,19 @@ Shapes::mw_alloc_shapes( int inrow, int incol, float value) size = inrow*incol; if (size <= 0) - { - std::cerr << "[mw_alloc_shapes] Attempts to alloc shapes with null size" << std::endl; - } + { + std::cerr << "[mw_alloc_shapes] Attempts to alloc shapes with null size" << std::endl; + } if ((the_shapes!=NULL)||(smallest_shape!=NULL)) - { - std::cerr << "[mw_alloc_shapes] Attempts to alloc root which is already allocated" << std::endl; - } + { + std::cerr << "[mw_alloc_shapes] Attempts to alloc root which is already allocated" << std::endl; + } root = the_shapes = new Shape[size+1]; if (root==NULL) - { - std::cerr <<"[mw_alloc_shapes] Not enough memory" <<std::endl; - } + { + std::cerr <<"[mw_alloc_shapes] Not enough memory" <<std::endl; + } root->inferior_type = 1; root->value = value; root->open = 1; @@ -169,10 +170,10 @@ Shapes::mw_alloc_shapes( int inrow, int incol, float value) typedef Shape* ShapePtr; smallest_shape = new ShapePtr[size]; if (smallest_shape==NULL) - { - std::cerr <<"[mw_alloc_shapes] Not enough memory" << std::endl; - delete root; - } + { + std::cerr <<"[mw_alloc_shapes] Not enough memory" << std::endl; + delete root; + } for (i=size-1; i>=0; i--) smallest_shape[i] = root; } @@ -188,10 +189,10 @@ Shapes::mw_change_shapes(int inrow,int incol,float value) otbMsgDevMacro( << "mw_change_shapes () " ); otbMsgDevMacro( << " nb shapes : " <<this->nb_shapes); otbMsgDevMacro( << " the shapes : " <<the_shapes ); - if((the_shapes != NULL) && (nb_shapes > 0)) + if ((the_shapes != NULL) && (nb_shapes > 0)) delete[] the_shapes[0].pixels; if (the_shapes != NULL) delete[] the_shapes; - if (smallest_shape != NULL) delete[] smallest_shape; + if (smallest_shape != NULL) delete[] smallest_shape; mw_alloc_shapes(inrow, incol, value); } @@ -207,11 +208,11 @@ Shapes::mw_get_smallest_shape(int iX,int iY) sh = smallest_shape[iY*ncol+iX]; if (sh == NULL) - { - std::cerr << "[mw_get_smallest_shape] smallest shape is NULL" << std::endl; - return(NULL); - } - if(sh->removed) + { + std::cerr << "[mw_get_smallest_shape] smallest shape is NULL" << std::endl; + return(NULL); + } + if (sh->removed) sh = sh->mw_get_parent_shape(sh); return(sh); } @@ -226,11 +227,11 @@ Shapes::compute_proper_pixels(int *tabNbOfProperPixels) /* 1) Initialize by the area */ pShape = the_shapes + nb_shapes-1; pNbOfProperPixels = tabNbOfProperPixels + nb_shapes-1; - for(i = nb_shapes-1; i >= 0; i--) + for (i = nb_shapes-1; i >= 0; i--) *pNbOfProperPixels-- = (pShape--)->area; /* 2) For each shape, substract its area to its parent */ pShape = the_shapes + nb_shapes-1; - for(i = nb_shapes-1; i > 0; i--, pShape--) + for (i = nb_shapes-1; i > 0; i--, pShape--) tabNbOfProperPixels[pShape->parent - the_shapes] -= pShape->area; } @@ -247,27 +248,30 @@ Shapes::allocate_pixels(int* tabNbOfProperPixels) /* 1) Memory allocation */ tabPixelsOfRoot = the_shapes[0].pixels = new Point_plane[nrow*ncol]; - if(tabPixelsOfRoot == NULL) + if (tabPixelsOfRoot == NULL) std::cerr << "allocate_pixels --> Allocation of pixels"<<std::endl; tabpShapesOfStack = new Shape*[nb_shapes]; - if(tabpShapesOfStack == NULL) + if (tabpShapesOfStack == NULL) std::cerr << "allocate_pixels --> Allocation of stack"<< std::endl; /* 2) Enumeration of the tree in preorder, using the stack */ pShape = &the_shapes[0]; iSizeOfStack = 0; i = 0; - while(1) - if(pShape != NULL) { + while (1) + if (pShape != NULL) + { /* Write pixels of pShape */ pShape->pixels = &tabPixelsOfRoot[i]; iIndex = pShape - the_shapes; i += tabNbOfProperPixels[iIndex]; tabpShapesOfStack[iSizeOfStack++] = pShape; /* Push */ pShape = pShape->child; - } else { - if(iSizeOfStack == 0) - break; + } + else + { + if (iSizeOfStack == 0) + break; pShape = tabpShapesOfStack[--iSizeOfStack]->next_sibling; /* Pop */ } delete[] tabpShapesOfStack; @@ -287,7 +291,7 @@ Shapes::flst_pixels() /* 1) Compute nb of proper pixels in each shape */ tabNbOfProperPixels = new int[nb_shapes]; - if(tabNbOfProperPixels ==NULL) + if (tabNbOfProperPixels ==NULL) std::cerr << "Allocation of array error" << std::endl; compute_proper_pixels(tabNbOfProperPixels); @@ -297,13 +301,14 @@ Shapes::flst_pixels() /* 3) Fill the array */ ppShape = smallest_shape + ncol*nrow-1; - for(i = nrow-1; i >= 0; i--) - for(j = ncol-1; j >= 0; j--, ppShape--) - { - iIndex = (*ppShape) - the_shapes; - pCurrentPoint = &(*ppShape)->pixels[--tabNbOfProperPixels[iIndex]]; - pCurrentPoint->x = j; pCurrentPoint->y = i; - } + for (i = nrow-1; i >= 0; i--) + for (j = ncol-1; j >= 0; j--, ppShape--) + { + iIndex = (*ppShape) - the_shapes; + pCurrentPoint = &(*ppShape)->pixels[--tabNbOfProperPixels[iIndex]]; + pCurrentPoint->x = j; + pCurrentPoint->y = i; + } delete[] tabNbOfProperPixels; } @@ -319,13 +324,13 @@ const int Shapes::SOUTH = 3; void Shapes::TURN_LEFT(int *dir) { - *dir = (*dir==NORTH ? WEST :(*dir==WEST ? SOUTH :(*dir==SOUTH ? EAST : NORTH))); + *dir = (*dir==NORTH ? WEST :(*dir==WEST ? SOUTH :(*dir==SOUTH ? EAST : NORTH))); } void Shapes::TURN_RIGHT(int *dir) { - *dir = (*dir==NORTH ? EAST :(*dir==EAST ? SOUTH :(*dir==SOUTH ? WEST : NORTH))); + *dir = (*dir==NORTH ? EAST :(*dir==EAST ? SOUTH :(*dir==SOUTH ? WEST : NORTH))); } @@ -337,12 +342,12 @@ Shapes::point_in_shape(int x,int y,Shape *pShape) Shape *pShapePoint = smallest_shape[y*ncol+x]; result = (pShape->pixels <= pShapePoint->pixels && - pShapePoint->pixels < pShape->pixels+pShape->area); + pShapePoint->pixels < pShape->pixels+pShape->area); otbMsgDevMacro( << "PointInShape() -->"<<x<<" "<<y<<" " << pShape->value << " Result : "<< int(result)); return (pShape->pixels <= pShapePoint->pixels && - pShapePoint->pixels < pShape->pixels+pShape->area); + pShapePoint->pixels < pShape->pixels+pShape->area); } /* Find the dual point following pDualPoint as we follow the shape boundary */ @@ -353,16 +358,20 @@ Shapes::find_next_dual_point(Point_plane *pDualPoint,int *cDirection,Shape *pSha otbMsgDevMacro( << "Shapes::find_next_dual_point()" ); otbMsgDevMacro( << " pDualPoint : ( "<<pDualPoint->x << " , " << pDualPoint->y << " Direction :" << cDirection ); - switch(*cDirection) { + switch (*cDirection) + { case NORTH: bLeftIn = point_in_shape(pDualPoint->x-1, pDualPoint->y-1, pShape); bRightIn = point_in_shape(pDualPoint->x, pDualPoint->y-1, pShape); - if(bLeftIn && ! bRightIn) + if (bLeftIn && ! bRightIn) -- pDualPoint->y; - else if(! bLeftIn && (! bRightIn || pShape->inferior_type)) { + else if (! bLeftIn && (! bRightIn || pShape->inferior_type)) + { -- pDualPoint->x; TURN_LEFT(cDirection); - } else { + } + else + { ++ pDualPoint->x; TURN_RIGHT(cDirection); } @@ -370,12 +379,15 @@ Shapes::find_next_dual_point(Point_plane *pDualPoint,int *cDirection,Shape *pSha case WEST: bLeftIn = point_in_shape(pDualPoint->x-1, pDualPoint->y, pShape); bRightIn = point_in_shape(pDualPoint->x-1, pDualPoint->y-1, pShape); - if(bLeftIn && ! bRightIn) + if (bLeftIn && ! bRightIn) -- pDualPoint->x; - else if(! bLeftIn && (! bRightIn || pShape->inferior_type)) { + else if (! bLeftIn && (! bRightIn || pShape->inferior_type)) + { ++ pDualPoint->y; TURN_LEFT(cDirection); - } else { + } + else + { -- pDualPoint->y; TURN_RIGHT(cDirection); } @@ -383,12 +395,15 @@ Shapes::find_next_dual_point(Point_plane *pDualPoint,int *cDirection,Shape *pSha case SOUTH: bLeftIn = point_in_shape(pDualPoint->x, pDualPoint->y, pShape); bRightIn = point_in_shape(pDualPoint->x-1, pDualPoint->y, pShape); - if(bLeftIn && ! bRightIn) + if (bLeftIn && ! bRightIn) ++ pDualPoint->y; - else if(! bLeftIn && (! bRightIn || pShape->inferior_type)) { + else if (! bLeftIn && (! bRightIn || pShape->inferior_type)) + { ++ pDualPoint->x; TURN_LEFT(cDirection); - } else { + } + else + { -- pDualPoint->x; TURN_RIGHT(cDirection); } @@ -396,12 +411,15 @@ Shapes::find_next_dual_point(Point_plane *pDualPoint,int *cDirection,Shape *pSha case EAST: bLeftIn = point_in_shape(pDualPoint->x, pDualPoint->y-1, pShape); bRightIn = point_in_shape(pDualPoint->x, pDualPoint->y, pShape); - if(bLeftIn && ! bRightIn) + if (bLeftIn && ! bRightIn) ++ pDualPoint->x; - else if(! bLeftIn && (! bRightIn || pShape->inferior_type)) { + else if (! bLeftIn && (! bRightIn || pShape->inferior_type)) + { -- pDualPoint->y; TURN_LEFT(cDirection); - } else { + } + else + { ++ pDualPoint->y; TURN_RIGHT(cDirection); } @@ -431,22 +449,24 @@ Shapes::find_closed_boundary(Shape *pShape,PathPointer pBoundary) otbMsgDevMacro( << " find_closed_boundary 1" ); do ++ dualPoint.x; - while(point_in_shape(dualPoint.x, dualPoint.y, pShape)); + while (point_in_shape(dualPoint.x, dualPoint.y, pShape)); otbMsgDevMacro( << " find_closed_boundary 2" ); /* 2) Follow the boundary */ x0 = dualPoint.x; y0 = dualPoint.y; - do { - otbMsgDevMacro( << " find_closed_boundary 3" ); - cindex[0] = dualPoint.x; - cindex[1] = dualPoint.y; + do + { + otbMsgDevMacro( << " find_closed_boundary 3" ); + cindex[0] = dualPoint.x; + cindex[1] = dualPoint.y; - pBoundary->AddVertex(cindex); + pBoundary->AddVertex(cindex); - find_next_dual_point(&dualPoint,&cDirection, pShape); - } while(dualPoint.x != x0 || dualPoint.y != y0 || cDirection != NORTH); + find_next_dual_point(&dualPoint,&cDirection, pShape); + } + while (dualPoint.x != x0 || dualPoint.y != y0 || cDirection != NORTH); /* Close the boundary */ cindex[0] = dualPoint.x; @@ -475,11 +495,12 @@ Shapes::initial_point_border(Point_plane *pDualPoint,int *cDirection,Shape *pSha otbMsgDevMacro( << " Direction (WEST) :" << int(*cDirection) ); x = iWidth-1; y = 0; - if(point_in_shape(x, y++, pShape)) - while(y < iHeight && point_in_shape(x, y++, pShape)); - while(y < iHeight && ! point_in_shape(x, y, pShape)) + if (point_in_shape(x, y++, pShape)) + while (y < iHeight && point_in_shape(x, y++, pShape)); + while (y < iHeight && ! point_in_shape(x, y, pShape)) ++ y; - if(y < iHeight) { + if (y < iHeight) + { pDualPoint->x = iWidth; pDualPoint->y = y; return; @@ -488,11 +509,12 @@ Shapes::initial_point_border(Point_plane *pDualPoint,int *cDirection,Shape *pSha *cDirection = SOUTH; x = 0; y = 0; - if(point_in_shape(x++, y, pShape)) - while(x < iWidth && point_in_shape(x++, y, pShape)); - while(x < iWidth && ! point_in_shape(x, y, pShape)) + if (point_in_shape(x++, y, pShape)) + while (x < iWidth && point_in_shape(x++, y, pShape)); + while (x < iWidth && ! point_in_shape(x, y, pShape)) ++ x; - if(x < iWidth) { + if (x < iWidth) + { pDualPoint->x = x; pDualPoint->y = 0; return; @@ -501,11 +523,12 @@ Shapes::initial_point_border(Point_plane *pDualPoint,int *cDirection,Shape *pSha *cDirection = EAST; x = 0; y = iHeight-1; - if(point_in_shape(x, y--, pShape)) - while(y >= 0 && point_in_shape(x, y--, pShape)); - while(y >= 0 && ! point_in_shape(x, y, pShape)) + if (point_in_shape(x, y--, pShape)) + while (y >= 0 && point_in_shape(x, y--, pShape)); + while (y >= 0 && ! point_in_shape(x, y, pShape)) -- y; - if(y >= 0) { + if (y >= 0) + { pDualPoint->x = 0; pDualPoint->y = y+1; return; @@ -514,11 +537,12 @@ Shapes::initial_point_border(Point_plane *pDualPoint,int *cDirection,Shape *pSha *cDirection = NORTH; x = iWidth-1; y = iHeight-1; - if(point_in_shape(x--, y, pShape)) - while(x >= 0 && point_in_shape(x--, y, pShape)); - while(x >= 0 && ! point_in_shape(x, y, pShape)) + if (point_in_shape(x--, y, pShape)) + while (x >= 0 && point_in_shape(x--, y, pShape)); + while (x >= 0 && ! point_in_shape(x, y, pShape)) -- x; - if(x >= 0) { + if (x >= 0) + { pDualPoint->x = x+1; pDualPoint->y = iHeight; return; @@ -539,18 +563,20 @@ Shapes::find_open_boundary(Shape *pShape,PathPointer pBoundary) otbMsgDevMacro( << "Shapes::find_open_boundary()" ); initial_point_border(&dualPoint,&cDirection, pShape); - do { - cindex[0] = dualPoint.x; - cindex[1] = dualPoint.y; + do + { + cindex[0] = dualPoint.x; + cindex[1] = dualPoint.y; - pBoundary->AddVertex(cindex); + pBoundary->AddVertex(cindex); otbMsgDevMacro( << "Shapes::find_open_boundary() DO WHILE" ); find_next_dual_point(&dualPoint, &cDirection,pShape); - } while(0 < dualPoint.x && dualPoint.x < iWidth && - 0 < dualPoint.y && dualPoint.y < iHeight); + } + while (0 < dualPoint.x && dualPoint.x < iWidth && + 0 < dualPoint.y && dualPoint.y < iHeight); - /* We store the exit */ + /* We store the exit */ cindex[0] = dualPoint.x; cindex[1] = dualPoint.y; @@ -573,7 +599,7 @@ Shapes::flst_shape_boundary(Shape *pShape) otbMsgDevMacro( << " FLST Shape Boundary ....New" ); - if(the_shapes[0].pixels == NULL) + if (the_shapes[0].pixels == NULL) flst_pixels(); otbMsgDevMacro( << " FLST Shape Boundary ....Pixel" ); @@ -581,7 +607,7 @@ Shapes::flst_shape_boundary(Shape *pShape) pBoundary->Initialize(); - if(pShape->open) + if (pShape->open) find_open_boundary( pShape, pBoundary); else find_closed_boundary(pShape, pBoundary); diff --git a/Code/FeatureExtraction/otbSiftFastImageFilter.h b/Code/FeatureExtraction/otbSiftFastImageFilter.h old mode 100755 new mode 100644 index f2ecf78e01b2ff108f79afa435cf9a403878e29e..a7d6c12b9a9cd6a4170d5ef6b49757bf4e52b28e --- a/Code/FeatureExtraction/otbSiftFastImageFilter.h +++ b/Code/FeatureExtraction/otbSiftFastImageFilter.h @@ -26,70 +26,70 @@ namespace otb { - /** \class SiftFastImageFilter - * \brief This class extracts key points from an input image through a pyramidal decomposition - * - * This class implements the SIFT key point detector proposed by David G. Lowe in proceedings of International - * Conference on Computer Vision, Corfu, september 1999. - * - * \example FeatureExtraction/SIFTFastExample.cxx - */ - template <class TInputImage, class TOutputPointSet> - class ITK_EXPORT SiftFastImageFilter - : public ImageToPointSetFilter<TInputImage,TOutputPointSet> - { - public: - /** Standard typedefs */ - typedef SiftFastImageFilter Self; - typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Creation through object factory macro */ - itkNewMacro(Self); - - /** Type macro */ - itkTypeMacro(SiftFastImageFilter,ImageToPointSetFilter); - - /** Template parameters typedefs */ - - typedef TInputImage InputImageType; - typedef typename TInputImage::Pointer InputImagePointerType; - typedef typename TInputImage::PixelType PixelType; - - typedef TOutputPointSet OutputPointSetType; - typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; - typedef typename TOutputPointSet::PixelType OutputPixelType; - typedef typename TOutputPointSet::PointType OutputPointType; - typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; - - typedef otb::Image<float,2> FloatImageType; - - // Used to rescale data in the [0,1] range - typedef itk::RescaleIntensityImageFilter<InputImageType,FloatImageType> RescalerType; - - itkSetMacro(NumberOfScales,unsigned int); - itkGetMacro(NumberOfScales,unsigned int); - - protected: - /** Actually process the input */ - virtual void GenerateData(); - - /** Constructor */ - SiftFastImageFilter(); - - /** Destructor */ - virtual ~SiftFastImageFilter() {} - - /** PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - /** The number of scales */ - unsigned int m_NumberOfScales; - - - }; +/** \class SiftFastImageFilter + * \brief This class extracts key points from an input image through a pyramidal decomposition + * + * This class implements the SIFT key point detector proposed by David G. Lowe in proceedings of International + * Conference on Computer Vision, Corfu, september 1999. + * + * \example FeatureExtraction/SIFTFastExample.cxx + */ +template <class TInputImage, class TOutputPointSet> +class ITK_EXPORT SiftFastImageFilter + : public ImageToPointSetFilter<TInputImage,TOutputPointSet> +{ +public: + /** Standard typedefs */ + typedef SiftFastImageFilter Self; + typedef ImageToPointSetFilter<TInputImage,TOutputPointSet> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Creation through object factory macro */ + itkNewMacro(Self); + + /** Type macro */ + itkTypeMacro(SiftFastImageFilter,ImageToPointSetFilter); + + /** Template parameters typedefs */ + + typedef TInputImage InputImageType; + typedef typename TInputImage::Pointer InputImagePointerType; + typedef typename TInputImage::PixelType PixelType; + + typedef TOutputPointSet OutputPointSetType; + typedef typename TOutputPointSet::Pointer OutputPointSetPointerType; + typedef typename TOutputPointSet::PixelType OutputPixelType; + typedef typename TOutputPointSet::PointType OutputPointType; + typedef typename TOutputPointSet::PointIdentifier OutputPointIdentifierType; + + typedef otb::Image<float,2> FloatImageType; + + // Used to rescale data in the [0,1] range + typedef itk::RescaleIntensityImageFilter<InputImageType,FloatImageType> RescalerType; + + itkSetMacro(NumberOfScales,unsigned int); + itkGetMacro(NumberOfScales,unsigned int); + +protected: + /** Actually process the input */ + virtual void GenerateData(); + + /** Constructor */ + SiftFastImageFilter(); + + /** Destructor */ + virtual ~SiftFastImageFilter() {} + + /** PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + /** The number of scales */ + unsigned int m_NumberOfScales; + + +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbSiftFastImageFilter.txx" diff --git a/Code/FeatureExtraction/otbSiftFastImageFilter.txx b/Code/FeatureExtraction/otbSiftFastImageFilter.txx old mode 100755 new mode 100644 index 04f677069f618cc9e075f5f964c19389f6524376..bcda8485768f5df52a2de8067e608c630990a328 --- a/Code/FeatureExtraction/otbSiftFastImageFilter.txx +++ b/Code/FeatureExtraction/otbSiftFastImageFilter.txx @@ -29,89 +29,89 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputPointSet> - SiftFastImageFilter<TInputImage,TOutputPointSet> - ::SiftFastImageFilter() - { } - - - template <class TInputImage, class TOutputPointSet> - void - SiftFastImageFilter<TInputImage,TOutputPointSet> - ::GenerateData() +/** + * Constructor + */ +template <class TInputImage, class TOutputPointSet> +SiftFastImageFilter<TInputImage,TOutputPointSet> +::SiftFastImageFilter() +{ } + + +template <class TInputImage, class TOutputPointSet> +void +SiftFastImageFilter<TInputImage,TOutputPointSet> +::GenerateData() +{ + + // Get the input image pointer + const InputImageType * inputPtr = this->GetInput(); + OutputPointSetPointerType outputPointSet = this->GetOutput(); + + typename InputImageType::SizeType size = inputPtr->GetLargestPossibleRegion().GetSize(); + + // Rescale data in the [0,1] range + typename RescalerType::Pointer rescaler = RescalerType::New(); + rescaler->SetInput(inputPtr); + rescaler->SetOutputMinimum(0); + rescaler->SetOutputMaximum(1); + rescaler->Update(); + + SiftFastImage siftInputImage = CreateImage(size[1],size[0]); + itk::ImageRegionIterator<FloatImageType> inIt(rescaler->GetOutput(),rescaler->GetOutput()->GetLargestPossibleRegion()); + + unsigned int index =0; + + for (inIt.GoToBegin();!inIt.IsAtEnd();++inIt) { - - // Get the input image pointer - const InputImageType * inputPtr = this->GetInput(); - OutputPointSetPointerType outputPointSet = this->GetOutput(); - - typename InputImageType::SizeType size = inputPtr->GetLargestPossibleRegion().GetSize(); - - // Rescale data in the [0,1] range - typename RescalerType::Pointer rescaler = RescalerType::New(); - rescaler->SetInput(inputPtr); - rescaler->SetOutputMinimum(0); - rescaler->SetOutputMaximum(1); - rescaler->Update(); - - SiftFastImage siftInputImage = CreateImage(size[1],size[0]); - itk::ImageRegionIterator<FloatImageType> inIt(rescaler->GetOutput(),rescaler->GetOutput()->GetLargestPossibleRegion()); - - unsigned int index =0; - - for(inIt.GoToBegin();!inIt.IsAtEnd();++inIt) - { - siftInputImage->pixels[index]=inIt.Get(); - ++index; - } - - Keypoint keypts = GetKeypoints(siftInputImage,m_NumberOfScales); - - Keypoint key = keypts; - - unsigned int numkeys = 0; - - while(key) - { - // Get the key location - itk::ContinuousIndex<float,2> keyContIndex; - keyContIndex[0]=key->col; - keyContIndex[1]=key->row; - - OutputPointType point; - inputPtr->TransformContinuousIndexToPhysicalPoint(keyContIndex,point); - - // Get the key descriptor - OutputPixelType data; - data.SetSize(128); - for(int i = 0; i < 128; ++i) - { - data[i]=key->descrip[i]; - - } - outputPointSet->SetPoint(numkeys,point); - outputPointSet->SetPointData(numkeys,data); - - // go to next key - numkeys++; - key = key->next; - } - FreeKeypoints(keypts); - DestroyAllResources(); + siftInputImage->pixels[index]=inIt.Get(); + ++index; } - /* - * PrintSelf Method - */ - template <class TInputImage, class TOutputPointSet> - void - SiftFastImageFilter<TInputImage,TOutputPointSet> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + + Keypoint keypts = GetKeypoints(siftInputImage,m_NumberOfScales); + + Keypoint key = keypts; + + unsigned int numkeys = 0; + + while (key) { - Superclass::PrintSelf(os, indent); + // Get the key location + itk::ContinuousIndex<float,2> keyContIndex; + keyContIndex[0]=key->col; + keyContIndex[1]=key->row; + + OutputPointType point; + inputPtr->TransformContinuousIndexToPhysicalPoint(keyContIndex,point); + + // Get the key descriptor + OutputPixelType data; + data.SetSize(128); + for (int i = 0; i < 128; ++i) + { + data[i]=key->descrip[i]; + + } + outputPointSet->SetPoint(numkeys,point); + outputPointSet->SetPointData(numkeys,data); + + // go to next key + numkeys++; + key = key->next; } + FreeKeypoints(keypts); + DestroyAllResources(); +} +/* + * PrintSelf Method + */ +template <class TInputImage, class TOutputPointSet> +void +SiftFastImageFilter<TInputImage,TOutputPointSet> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } // End namespace otb diff --git a/Code/FeatureExtraction/otbSimplePointCountStrategy.h b/Code/FeatureExtraction/otbSimplePointCountStrategy.h index d5a8953d36db67b95a5b21ec9a07ec42f71fd5a5..7c59a92c0f6a4fb06220fe6dc2d88e0c2d2bc9e5 100644 --- a/Code/FeatureExtraction/otbSimplePointCountStrategy.h +++ b/Code/FeatureExtraction/otbSimplePointCountStrategy.h @@ -16,62 +16,62 @@ =========================================================================*/ #ifndef __otbSimplePointCountStrategy_h -#define __otbSimplePointCountStrategy_h +#define __otbSimplePointCountStrategy_h #include "otbMath.h" namespace otb { - + /** \class Count * \brief Compute the density of a neighboorhood centerred in a pixel * * This filter is templated over the pixel type of the input image - * and the pixel type of the output image. + * and the pixel type of the output image. * * The filter will walk over all the pixels in the input image, and for - * each one of them it will do the following: + * each one of them it will do the following: */ - + template< class TPointSet, class TRadiusType , class TIndexType> class Count { public: Count() {}; ~Count() {}; - + inline float operator()( const TPointSet * pointSet , const TRadiusType & size , const TIndexType & index ) + { + + int accu = 0; + double surface = M_PI*size*size; + + if (pointSet->GetNumberOfPoints() != 0) { - - int accu = 0; - double surface = M_PI*size*size; - - if(pointSet->GetNumberOfPoints() != 0) - { - typedef typename TPointSet::PointsContainer::ConstIterator iteratorType; - iteratorType it = pointSet->GetPoints()->Begin(); - - while( it != pointSet->GetPoints()->End()) - { - float distX2 =( index[0]-it.Value()[0])*( index[0]-it.Value()[0]); - float distY2 =( index[1]-it.Value()[1])*( index[1]-it.Value()[1]); - float dist = vcl_sqrt(distX2 + distY2); - - if(dist <= size) - accu++; - - ++it; - } - } - else - return 0.; - - return static_cast<float>(accu/surface); + typedef typename TPointSet::PointsContainer::ConstIterator iteratorType; + iteratorType it = pointSet->GetPoints()->Begin(); + + while ( it != pointSet->GetPoints()->End()) + { + float distX2 =( index[0]-it.Value()[0])*( index[0]-it.Value()[0]); + float distY2 =( index[1]-it.Value()[1])*( index[1]-it.Value()[1]); + float dist = vcl_sqrt(distX2 + distY2); + + if (dist <= size) + accu++; + + ++it; + } } -}; + else + return 0.; + + return static_cast<float>(accu/surface); + } +}; } // end namespace otb diff --git a/Code/FeatureExtraction/otbSimplifyPathListFilter.h b/Code/FeatureExtraction/otbSimplifyPathListFilter.h index e0f91b9baf874c6941f9f77902171388cec7a5fb..5da8fb3f9d5fe98ade37bc34bcdb2b0a3aaa3c75 100644 --- a/Code/FeatureExtraction/otbSimplifyPathListFilter.h +++ b/Code/FeatureExtraction/otbSimplifyPathListFilter.h @@ -59,13 +59,13 @@ namespace otb * */ - template <class TPath> - class ITK_EXPORT SimplifyPathListFilter: +template <class TPath> +class ITK_EXPORT SimplifyPathListFilter: public UnaryFunctorObjectListFilter< ObjectList<TPath>, ObjectList<TPath>, SimplifyPathFunctor<typename TPath::Pointer, typename TPath::Pointer> > - {}; + {}; }// End namespace otb diff --git a/Code/FeatureExtraction/otbSpectralAngleFunctor.h b/Code/FeatureExtraction/otbSpectralAngleFunctor.h index a234f6e71086713c0dda35794043fd8d3a1e1538..38c36ef1b63fc268026835641f88f11f51ccbeb9 100644 --- a/Code/FeatureExtraction/otbSpectralAngleFunctor.h +++ b/Code/FeatureExtraction/otbSpectralAngleFunctor.h @@ -22,65 +22,68 @@ namespace otb { - /** \class SpectralAngleFunctor - * \brief This functor computes the spectral angle according to a reference pixel. - */ +/** \class SpectralAngleFunctor + * \brief This functor computes the spectral angle according to a reference pixel. + */ namespace Functor { template<class TInput,class TOutputValue> class SpectralAngleFunctor { - public: +public: SpectralAngleFunctor() - { - m_ReferencePixel.SetSize(4); - m_ReferencePixel.Fill(1); - }; + { + m_ReferencePixel.SetSize(4); + m_ReferencePixel.Fill(1); + }; - ~SpectralAngleFunctor(){}; + ~SpectralAngleFunctor() {}; inline TOutputValue operator()(const TInput& inPix) - { - TOutputValue out; - - double dist=0.0; - double scalarProd=0.0; - double normProd=0.0; - double normProd1=0.0; - double sqrtNormProd = 0.0; - for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) - { - scalarProd += inPix[i]*m_ReferencePixel[i]; - normProd1 += inPix[i]*inPix[i]; - } - normProd = normProd1 * m_RefNorm*m_RefNorm; - sqrtNormProd = vcl_sqrt(normProd); - if ( (sqrtNormProd == 0.0) || ( scalarProd / sqrtNormProd > 1) ) - { - dist = 0.0; - } - else - { - dist = vcl_acos(scalarProd/sqrtNormProd); - } - - out = static_cast<TOutputValue>(dist); - return out; + { + TOutputValue out; + double dist=0.0; + double scalarProd=0.0; + double normProd=0.0; + double normProd1=0.0; + double sqrtNormProd = 0.0; + for (unsigned int i=0; i<std::min(inPix.Size(),m_ReferencePixel.Size()); i++) + { + scalarProd += inPix[i]*m_ReferencePixel[i]; + normProd1 += inPix[i]*inPix[i]; + } + normProd = normProd1 * m_RefNorm*m_RefNorm; + sqrtNormProd = vcl_sqrt(normProd); + if ( (sqrtNormProd == 0.0) || ( scalarProd / sqrtNormProd > 1) ) + { + dist = 0.0; + } + else + { + dist = vcl_acos(scalarProd/sqrtNormProd); } - + + out = static_cast<TOutputValue>(dist); + return out; + + } + void SetReferencePixel( TInput ref ) - { - m_ReferencePixel = ref; - m_RefNorm = 0.0; - for(unsigned int i = 0; i<ref.Size(); i++) + { + m_ReferencePixel = ref; + m_RefNorm = 0.0; + for (unsigned int i = 0; i<ref.Size(); i++) { m_RefNorm += ref[i]*ref[i]; } - m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); - }; - TInput GetReferencePixel(){ return m_ReferencePixel; }; - - protected: + m_RefNorm = vcl_sqrt(static_cast<double>(m_RefNorm)); + }; + TInput GetReferencePixel() + { + return m_ReferencePixel; + }; + +protected: TInput m_ReferencePixel; double m_RefNorm; }; diff --git a/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.h b/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.h index 0a19a9ed3101671c58b12192fb09ba468f81691f..4408dae2213cdc42e6076088301e9d1c3f95bb43 100644 --- a/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.h +++ b/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.h @@ -30,14 +30,14 @@ namespace otb template <class TInputImage, // class TOutputPointSet> - class TOutputPointSet = itk::PointSet<ITK_TYPENAME TInputImage::PixelType,2> > +class TOutputPointSet = itk::PointSet<ITK_TYPENAME TInputImage::PixelType,2> > class ITK_EXPORT ThresholdImageToPointSetFilter : - public ImageToPointSetFilter< TInputImage,TOutputPointSet > + public ImageToPointSetFilter< TInputImage,TOutputPointSet > { public: itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); typedef TInputImage InputImageType; diff --git a/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.txx b/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.txx index ad91bb3734ad25fb0d9482780a4dbdbd6e494439..b81ca6e85b96fa6f3d604175b7ed187c66f1159f 100644 --- a/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.txx +++ b/Code/FeatureExtraction/otbThresholdImageToPointSetFilter.txx @@ -51,24 +51,24 @@ ThresholdImageToPointSetFilter<TInputImage, TOutputPointSet> InputIterator inIt(inputPtr, inputPtr->GetRequestedRegion() ); // walk the regions, threshold each pixel - while( !inIt.IsAtEnd() ) - { + while ( !inIt.IsAtEnd() ) + { const InputPixelType value = inIt.Get(); const IndexType index = inIt.GetIndex(); if ((value >= m_LowerThreshold) && (value <= m_UpperThreshold)) - { - position[0] = index[0]; - position[1] = index[1]; + { + position[0] = index[0]; + position[1] = index[1]; - outputPtr->SetPoint(pointId,position); + outputPtr->SetPoint(pointId,position); - pointId++; + pointId++; - } - ++inIt; } + ++inIt; + } } /** diff --git a/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.h b/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.h index 3bac64fde25ebb519453d71f094d332006d4568d..12d5ad23969fb2a568077f6758335313bed27834 100644 --- a/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.h +++ b/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.h @@ -62,10 +62,10 @@ class ITK_EXPORT TouziEdgeDetectorImageFilter : public ImageToModulusAndDirect public: /** Extract input and output images sizes. */ itkStaticConstMacro( InputImageDimension, - unsigned int, + unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, - unsigned int, + unsigned int, TOutputImage::ImageDimension); /** typedef for the classes standards. */ diff --git a/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.txx b/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.txx index 35c098aa075d83a846278b287fcafda96bb27a56..286ba07cb58f36c82680872d8277bb7b56ff6529 100644 --- a/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.txx +++ b/Code/FeatureExtraction/otbTouziEdgeDetectorImageFilter.txx @@ -54,9 +54,9 @@ void TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirecti typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) - { + { return; - } + } // get a copy of the input requested region (should equal the output // requested region) @@ -68,12 +68,12 @@ void TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirecti // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) - { + { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; - } + } else - { + { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. @@ -84,18 +84,18 @@ void TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirecti itk::InvalidRequestedRegionError e(__FILE__, __LINE__); itk::OStringStream msg; msg << static_cast<const char *>(this->GetNameOfClass()) - << "::GenerateInputRequestedRegion()"; + << "::GenerateInputRequestedRegion()"; e.SetLocation(msg.str().c_str()); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; - } + } } /** * Set up state of filter before multi-threading. * InterpolatorType::SetInputImage is not thread-safe and hence - * has to be set up before ThreadedGenerateData + * has to be set up before ThreadedGenerateData */ template <class TInputImage, class TOutputImage, class TOutputImageDirection > void @@ -120,9 +120,9 @@ template <class TInputImage, class TOutputImage, class TOutputImageDirection > void TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> ::ThreadedGenerateData( - const OutputImageRegionType& outputRegionForThread, - int threadId - ) + const OutputImageRegionType& outputRegionForThread, + int threadId +) { unsigned int i; itk::ZeroFluxNeumannBoundaryCondition<InputImageType> nbc; @@ -187,14 +187,14 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> int xc; int yc; - int cpt=0; + int cpt=0; // Process each of the boundary faces. These are N-d regions which border // the edge of the buffer. for (fit=faceList.begin(); fit != faceList.end(); ++fit) - { + { - cpt += 1; + cpt += 1; bit = itk::ConstNeighborhoodIterator<InputImageType>(m_Radius, input, *fit); unsigned int neighborhoodSize = bit.Size(); @@ -207,7 +207,7 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> while ( ! bit.IsAtEnd() ) - { + { // Location of the pixel central bitIndex = bit.GetIndex(); @@ -217,10 +217,10 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> // Initializations for (int dir=0; dir<NB_DIR; dir++) - { + { for (int m=0; m<NB_REGION; m++) Sum[dir][m] = 0.; - } + } R_contour = -1; Dir_contour = 0.; @@ -229,7 +229,7 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> // Loop on pixels of the filter for (i = 0; i < neighborhoodSize; ++i) - { + { bitIndex = bit.GetIndex(i); x = bitIndex[0]; @@ -237,7 +237,7 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> // We determine for each direction with which region the pixel belongs. - // Horizontal direction + // Horizontal direction if ( y < yc ) Sum[0][0] += static_cast<double>(bit.GetPixel(i)); else if ( y > yc ) @@ -263,12 +263,12 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> - } // end of the loop on pixels of the filter + } // end of the loop on pixels of the filter // Loop on the 4 directions for ( int dir=0; dir<NB_DIR; dir++ ) - { + { // Calculation of the mean of the 2 regions M1 = Sum[dir][0] / static_cast<double>(m_Radius[0]*(2*m_Radius[0]+1)); M2 = Sum[dir][1] / static_cast<double>(m_Radius[0]*(2*m_Radius[0]+1)); @@ -277,9 +277,9 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> if (( M1 != 0 ) && (M2 != 0)) R_theta[dir] = static_cast<double>( 1 - MINI( (M1/M2), (M2/M1) ) ); else - R_theta[dir] = 0.; + R_theta[dir] = 0.; - // Determination of the maximum intensity of the contour + // Determination of the maximum intensity of the contour R_contour = static_cast<double>( MAXI( R_contour, R_theta[dir] ) ); // Determination of the sign of contour @@ -292,10 +292,10 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> Sum_R_theta += R_theta[dir]; - } // end of the loop on the directions + } // end of the loop on the directions - // Assignment of this value to the output pixel + // Assignment of this value to the output pixel it.Set( static_cast<OutputPixelType>(R_contour) ); // Determination of the direction of the contour @@ -311,9 +311,9 @@ TouziEdgeDetectorImageFilter<TInputImage, TOutputImage, TOutputImageDirection> ++it_dir; progress.CompletedPixel(); - } - } + + } } /** diff --git a/Code/FeatureExtraction/otbTreeNeighborhood.h b/Code/FeatureExtraction/otbTreeNeighborhood.h index b6cced85fccd232875b91417570578a49be52062..eeae0d9b734359a8b5f520d1ff580dfece021e7c 100644 --- a/Code/FeatureExtraction/otbTreeNeighborhood.h +++ b/Code/FeatureExtraction/otbTreeNeighborhood.h @@ -66,13 +66,28 @@ public: void print_neighborhood(); - int ORDER_MAX(int k,int l) { return (tabPoints[k].value > tabPoints[l].value); }; - int ORDER_MIN(int k,int l) { return (tabPoints[k].value < tabPoints[l].value); }; - int ORDER_MAX2(int k,int l) { return (tabPoints[k].value >= tabPoints[l].value); }; - int ORDER_MIN2(int k,int l) { return (tabPoints[k].value <= tabPoints[l].value); }; - void SWAP(int k,int l){ tabPoints[0] = tabPoints[k]; - tabPoints[k] = tabPoints[l]; - tabPoints[l] = tabPoints[0]; }; + int ORDER_MAX(int k,int l) + { + return (tabPoints[k].value > tabPoints[l].value); + }; + int ORDER_MIN(int k,int l) + { + return (tabPoints[k].value < tabPoints[l].value); + }; + int ORDER_MAX2(int k,int l) + { + return (tabPoints[k].value >= tabPoints[l].value); + }; + int ORDER_MIN2(int k,int l) + { + return (tabPoints[k].value <= tabPoints[l].value); + }; + void SWAP(int k,int l) + { + tabPoints[0] = tabPoints[k]; + tabPoints[k] = tabPoints[l]; + tabPoints[l] = tabPoints[0]; + }; void fix_up(); void fix_down(); diff --git a/Code/FeatureExtraction/otbTreeNeighborhood.txx b/Code/FeatureExtraction/otbTreeNeighborhood.txx index 1155256ce61fe1e7fd4fa62cadba71dc05b202c4..15fb998f7dfeab0e748265403938ed35e80631a4 100644 --- a/Code/FeatureExtraction/otbTreeNeighborhood.txx +++ b/Code/FeatureExtraction/otbTreeNeighborhood.txx @@ -43,11 +43,11 @@ Neighborhood::init_neighborhood(int iMaxArea, int iWidth,int iHeight) { iMaxArea = 4*(iMaxArea+1); - if(iMaxArea > iWidth*iHeight) + if (iMaxArea > iWidth*iHeight) iMaxArea = iWidth*iHeight; tabPoints = new Neighbor[iMaxArea+1]; - if(tabPoints == NULL) + if (tabPoints == NULL) std::cerr << "init_neighborhood --> neighbors allocation error" << std::endl; reinit_neighborhood( AMBIGUOUS); } @@ -68,18 +68,18 @@ Neighborhood::fix_up() int k = iNbPoints; int l; - if(type == MAX) - while(k > 1 && ORDER_MAX(k, l=k>>1)) - { - SWAP(k, l); - k = l; - } + if (type == MAX) + while (k > 1 && ORDER_MAX(k, l=k>>1)) + { + SWAP(k, l); + k = l; + } else - while(k > 1 && ORDER_MIN(k, l=k>>1)) - { - SWAP(k, l); - k = l; - } + while (k > 1 && ORDER_MIN(k, l=k>>1)) + { + SWAP(k, l); + k = l; + } } /* Put the first neighbor at a position so that we fix the heap */ @@ -91,24 +91,24 @@ Neighborhood::fix_down() int k = 1; int l; - if(type == MAX) - while((l = k << 1) <= N) - { - if(l < N && ORDER_MAX(l+1,l)) ++l; - if(ORDER_MAX2(k,l)) - break; - SWAP(k, l); - k = l; - } + if (type == MAX) + while ((l = k << 1) <= N) + { + if (l < N && ORDER_MAX(l+1,l)) ++l; + if (ORDER_MAX2(k,l)) + break; + SWAP(k, l); + k = l; + } else - while((l = k << 1) <= N) - { - if(l < N && ORDER_MIN(l+1,l)) ++l; - if(ORDER_MIN2(k,l)) - break; - SWAP(k, l); - k = l; - } + while ((l = k << 1) <= N) + { + if (l < N && ORDER_MIN(l+1,l)) ++l; + if (ORDER_MIN2(k,l)) + break; + SWAP(k, l); + k = l; + } } @@ -117,10 +117,10 @@ Neighborhood::print_neighborhood() { otbMsgDevMacro( << "pNeighborhood : " ); otbMsgDevMacro( << " iNbPoints : " << iNbPoints ); - for(int i= 0; i<=iNbPoints; i++) - { + for (int i= 0; i<=iNbPoints; i++) + { otbMsgDevMacro( << "tabPoints["<<i <<"] =" << tabPoints[i].value << " Position: (" << tabPoints[i].point.x << " , " << tabPoints[i].point.y << ")" ); - } + } } diff --git a/Code/FeatureExtraction/otbTreeSource.h b/Code/FeatureExtraction/otbTreeSource.h index e47e323c34b63ee75673b78ac75a6b2c1af082bb..39a026a000746049b8caee8f6d25adfc487d8607 100644 --- a/Code/FeatureExtraction/otbTreeSource.h +++ b/Code/FeatureExtraction/otbTreeSource.h @@ -86,7 +86,7 @@ private: * by the execute method. Set in the GenerateInputRequestedRegion method. */ int m_GenerateDataRegion; int m_GenerateDataNumberOfRegions; - }; +}; } // end namespace otb diff --git a/Code/FeatureExtraction/otbTreeSource.txx b/Code/FeatureExtraction/otbTreeSource.txx index 9a2f14dae9af7e194f6b0a8ed441642eae695111..d19cc5dcd57e28f63c8dac4ae4d9f0f3d13d9d85 100644 --- a/Code/FeatureExtraction/otbTreeSource.txx +++ b/Code/FeatureExtraction/otbTreeSource.txx @@ -33,7 +33,7 @@ TreeSource<TOutputTree> // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputMesh OutputTreePointer output - = static_cast<TOutputTree*>(this->MakeOutput(0).GetPointer()); + = static_cast<TOutputTree*>(this->MakeOutput(0).GetPointer()); this->itk::ProcessObject::SetNumberOfRequiredOutputs(1); this->itk::ProcessObject::SetNthOutput( 0, output.GetPointer() ); @@ -62,12 +62,12 @@ TreeSource<TOutputTree> ::GetOutput(void) { if (this->GetNumberOfOutputs() < 1) - { + { return 0; - } + } return static_cast<TOutputTree*> - (this->itk::ProcessObject::GetOutput(0)); + (this->itk::ProcessObject::GetOutput(0)); } @@ -80,7 +80,7 @@ TreeSource<TOutputTree> ::GetOutput(unsigned int idx) { return static_cast<TOutputTree*> - (this->itk::ProcessObject::GetOutput(idx)); + (this->itk::ProcessObject::GetOutput(idx)); } @@ -130,15 +130,15 @@ TreeSource<TOutputTree> ::GraftNthOutput(unsigned int idx, DataObject *graft) { if ( idx >= this->GetNumberOfOutputs() ) - { + { itkExceptionMacro(<<"Requested to graft output " << idx << - " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); - } + " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); + } if ( !graft ) - { + { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); - } + } DataObject * output = this->GetOutput( idx ); diff --git a/Code/FeatureExtraction/otbVectorizationPathListFilter.h b/Code/FeatureExtraction/otbVectorizationPathListFilter.h index 7593a93ad3c89314938a182cc905dff8867381bf..3d368807dbf1a6f8929999921b58a8b9a5fa665d 100644 --- a/Code/FeatureExtraction/otbVectorizationPathListFilter.h +++ b/Code/FeatureExtraction/otbVectorizationPathListFilter.h @@ -41,9 +41,9 @@ namespace otb */ template <class TInputModulus, class TInputDirection, class TOutputPath> class ITK_EXPORT VectorizationPathListFilter - : public PathListSource<TOutputPath> + : public PathListSource<TOutputPath> { - public: +public: /** Standard typedefs */ typedef VectorizationPathListFilter Self; typedef PathListSource<TOutputPath> Superclass; @@ -114,7 +114,7 @@ protected: VectorizationPathListFilter(); /** Destructor */ virtual ~VectorizationPathListFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Main computation method */ virtual void GenerateData(void); diff --git a/Code/FeatureExtraction/otbVectorizationPathListFilter.txx b/Code/FeatureExtraction/otbVectorizationPathListFilter.txx index fc1d9bed50947406fbdedbd4037e74773a2c1265..35ad800fb511ec721051cabdffad8bdf540a724a 100644 --- a/Code/FeatureExtraction/otbVectorizationPathListFilter.txx +++ b/Code/FeatureExtraction/otbVectorizationPathListFilter.txx @@ -24,89 +24,89 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputModulus, class TInputDirection, class TOutputPath> - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::VectorizationPathListFilter() - { - this->SetNumberOfRequiredInputs(2); - this->SetNumberOfInputs(2); - m_AmplitudeThreshold = 1.0; - } - template <class TInputModulus, class TInputDirection, class TOutputPath> - void - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::SetInput(InputModulusType * inputModulus) - { - this->itk::ProcessObject::SetNthInput(0,const_cast<InputModulusType *>(inputModulus)); - } - template <class TInputModulus, class TInputDirection, class TOutputPath> - const typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::InputModulusType * - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::GetInput(void) - { - if (this->GetNumberOfInputs() < 1) - { - return 0; - } - return static_cast<const TInputModulus*>(this->itk::ProcessObject::GetInput(0)); - } - template <class TInputModulus, class TInputDirection, class TOutputPath> - void - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::SetInputDirection(InputDirectionType * inputDirection) +/** + * Constructor + */ +template <class TInputModulus, class TInputDirection, class TOutputPath> +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::VectorizationPathListFilter() +{ + this->SetNumberOfRequiredInputs(2); + this->SetNumberOfInputs(2); + m_AmplitudeThreshold = 1.0; +} +template <class TInputModulus, class TInputDirection, class TOutputPath> +void +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::SetInput(InputModulusType * inputModulus) +{ + this->itk::ProcessObject::SetNthInput(0,const_cast<InputModulusType *>(inputModulus)); +} +template <class TInputModulus, class TInputDirection, class TOutputPath> +const typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::InputModulusType * +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::GetInput(void) +{ + if (this->GetNumberOfInputs() < 1) { - this->itk::ProcessObject::SetNthInput(1,const_cast<InputDirectionType *>(inputDirection)); + return 0; } - template <class TInputModulus, class TInputDirection, class TOutputPath> - const typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::InputDirectionType * - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::GetInputDirection(void) + return static_cast<const TInputModulus*>(this->itk::ProcessObject::GetInput(0)); +} +template <class TInputModulus, class TInputDirection, class TOutputPath> +void +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::SetInputDirection(InputDirectionType * inputDirection) +{ + this->itk::ProcessObject::SetNthInput(1,const_cast<InputDirectionType *>(inputDirection)); +} +template <class TInputModulus, class TInputDirection, class TOutputPath> +const typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::InputDirectionType * +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::GetInputDirection(void) +{ + if (this->GetNumberOfInputs() < 2) { - if (this->GetNumberOfInputs() < 2) - { - return 0; - } - return static_cast<const TInputDirection *>(this->itk::ProcessObject::GetInput(1)); + return 0; } - /** - * Main computation method - */ - template <class TInputModulus, class TInputDirection, class TOutputPath> - void - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::GenerateData(void) + return static_cast<const TInputDirection *>(this->itk::ProcessObject::GetInput(1)); +} +/** + * Main computation method + */ +template <class TInputModulus, class TInputDirection, class TOutputPath> +void +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::GenerateData(void) +{ + InputModulusConstPointerType modPtr = this->GetInput(); + InputDirectionConstPointerType dirPtr = this->GetInputDirection(); + OutputPathListPointerType outPtr = this->GetOutput(); + + typedef typename OffsetVectorType::iterator OffsetIteratorType; + + RadiusType radius; + radius.Fill(2); + OffsetVectorType offsetVector; + + // Creation of the flag image + FlagImagePointerType flagImage = FlagImageType::New(); + flagImage->SetRegions(modPtr->GetLargestPossibleRegion()); + flagImage->Allocate(); + flagImage->FillBuffer(false); + + // Iterators instantiation + ModRegionIteratorType modIt(modPtr,modPtr->GetLargestPossibleRegion()); + DirRegionIteratorType dirIt(dirPtr,dirPtr->GetLargestPossibleRegion()); + FlagRegionIteratorType flagIt(flagImage,flagImage->GetLargestPossibleRegion()); + + for (modIt.GoToBegin(),dirIt.GoToBegin(),flagIt.GoToBegin(); + (!modIt.IsAtEnd()) && (!dirIt.IsAtEnd()) && (!flagIt.IsAtEnd()); + ++modIt,++dirIt,++flagIt) { - InputModulusConstPointerType modPtr = this->GetInput(); - InputDirectionConstPointerType dirPtr = this->GetInputDirection(); - OutputPathListPointerType outPtr = this->GetOutput(); - - typedef typename OffsetVectorType::iterator OffsetIteratorType; - - RadiusType radius; - radius.Fill(2); - OffsetVectorType offsetVector; - - // Creation of the flag image - FlagImagePointerType flagImage = FlagImageType::New(); - flagImage->SetRegions(modPtr->GetLargestPossibleRegion()); - flagImage->Allocate(); - flagImage->FillBuffer(false); - - // Iterators instantiation - ModRegionIteratorType modIt(modPtr,modPtr->GetLargestPossibleRegion()); - DirRegionIteratorType dirIt(dirPtr,dirPtr->GetLargestPossibleRegion()); - FlagRegionIteratorType flagIt(flagImage,flagImage->GetLargestPossibleRegion()); - - for(modIt.GoToBegin(),dirIt.GoToBegin(),flagIt.GoToBegin(); - (!modIt.IsAtEnd()) && (!dirIt.IsAtEnd()) && (!flagIt.IsAtEnd()); - ++modIt,++dirIt,++flagIt) - { - if((modIt.Get() > m_AmplitudeThreshold) && (!flagIt.Get())) + if ((modIt.Get() > m_AmplitudeThreshold) && (!flagIt.Get())) { //this is a begining, to follow in two directions OutputPathPointerType pathTempDirect = OutputPathType::New(); @@ -122,115 +122,118 @@ namespace otb FlagNeighborhoodIteratorType nFlagIt(radius,flagImage,flagImage->GetLargestPossibleRegion()); for (flagReverse=0; flagReverse < 2; ++flagReverse) - { - nModIt.SetLocation(modIt.GetIndex()); - nDirIt.SetLocation(dirIt.GetIndex()); - nFlagIt.SetLocation(flagIt.GetIndex()); - // temporary point - PointType point; - VertexType vertex; - modPtr->TransformIndexToPhysicalPoint(nModIt.GetIndex(),point); - modPtr->TransformPhysicalPointToContinuousIndex(point,vertex); - if(flagReverse==0) - { - flagIt.Set(true); - - // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); - - pathTempDirect->AddVertex(vertex); - } - flagFinish = false; - while(!flagFinish) { - offsetVector =GetThreeNeighborOffsetFromDirection(nDirIt.GetCenterPixel(),flagReverse); - OffsetIteratorType vecIt = offsetVector.begin(); - bool flagFound=false; - while(vecIt!=offsetVector.end()&&!flagFound) - { - flagFound = nModIt.GetPixel(*vecIt) > 0 - && !nFlagIt.GetPixel(*vecIt); - ++vecIt; - } - if(flagFound) - { - point.Fill(0); - PointType tmpPoint; - totalAmplitude = 0; - for(vecIt = offsetVector.begin();vecIt!=offsetVector.end();++vecIt) + nModIt.SetLocation(modIt.GetIndex()); + nDirIt.SetLocation(dirIt.GetIndex()); + nFlagIt.SetLocation(flagIt.GetIndex()); + // temporary point + PointType point; + VertexType vertex; + modPtr->TransformIndexToPhysicalPoint(nModIt.GetIndex(),point); + modPtr->TransformPhysicalPointToContinuousIndex(point,vertex); + if (flagReverse==0) { - totalAmplitude += nModIt.GetPixel(*vecIt); - modPtr->TransformIndexToPhysicalPoint(nModIt.GetIndex(*vecIt),tmpPoint); - point[0] += nModIt.GetPixel(*vecIt) * tmpPoint[0]; - point[1] += nModIt.GetPixel(*vecIt) * tmpPoint[1]; - } - point[0] = point[0] / totalAmplitude + modPtr->GetSpacing()[0]/2; - point[1] = point[1] / totalAmplitude + modPtr->GetSpacing()[1]/2; - modPtr->TransformPhysicalPointToContinuousIndex(point,vertex); - if(flagReverse == 0) - { - // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); + flagIt.Set(true); + + // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); pathTempDirect->AddVertex(vertex); } - else + flagFinish = false; + while (!flagFinish) { + offsetVector =GetThreeNeighborOffsetFromDirection(nDirIt.GetCenterPixel(),flagReverse); + OffsetIteratorType vecIt = offsetVector.begin(); + bool flagFound=false; + while (vecIt!=offsetVector.end()&&!flagFound) + { + flagFound = nModIt.GetPixel(*vecIt) > 0 + && !nFlagIt.GetPixel(*vecIt); + ++vecIt; + } + if (flagFound) + { + point.Fill(0); + PointType tmpPoint; + totalAmplitude = 0; + for (vecIt = offsetVector.begin();vecIt!=offsetVector.end();++vecIt) + { + totalAmplitude += nModIt.GetPixel(*vecIt); + modPtr->TransformIndexToPhysicalPoint(nModIt.GetIndex(*vecIt),tmpPoint); + point[0] += nModIt.GetPixel(*vecIt) * tmpPoint[0]; + point[1] += nModIt.GetPixel(*vecIt) * tmpPoint[1]; + } + point[0] = point[0] / totalAmplitude + modPtr->GetSpacing()[0]/2; + point[1] = point[1] / totalAmplitude + modPtr->GetSpacing()[1]/2; + modPtr->TransformPhysicalPointToContinuousIndex(point,vertex); + if (flagReverse == 0) + { + // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); - // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); + pathTempDirect->AddVertex(vertex); + } + else + { - pathTempReverse->AddVertex(vertex); - } - // flag the pixel use - nFlagIt.SetCenterPixel(true); - //update the neighbor iterators so they are centered on the nearest pixel to the barycenter - IndexType newIndex; - if(modPtr->TransformPhysicalPointToIndex(point,newIndex)) - { - nModIt.SetLocation(newIndex); - nDirIt.SetLocation(newIndex); - nFlagIt.SetLocation(newIndex); + // otbMsgDebugMacro(<<"Adding new vertex: "<<vertex); - if(nModIt.GetCenterPixel()==0) + pathTempReverse->AddVertex(vertex); + } + // flag the pixel use + nFlagIt.SetCenterPixel(true); + //update the neighbor iterators so they are centered on the nearest pixel to the barycenter + IndexType newIndex; + if (modPtr->TransformPhysicalPointToIndex(point,newIndex)) { - //we need to check that in case the barycenter is out... - flagFinish=true; + nModIt.SetLocation(newIndex); + nDirIt.SetLocation(newIndex); + nFlagIt.SetLocation(newIndex); + + if (nModIt.GetCenterPixel()==0) + { + //we need to check that in case the barycenter is out... + flagFinish=true; + } + if (nFlagIt.GetCenterPixel()) + { + //we don't want to go back to the same pixels + flagFinish=true; + } } - if(nFlagIt.GetCenterPixel()) + else { - //we don't want to go back to the same pixels - flagFinish=true; + //new point outside image + flagFinish=true; } - } - else - { - //new point outside image - flagFinish=true; - } } - else + else { - flagFinish=true; + flagFinish=true; } - } } + } VertexListPointerType vertexDirect = pathTempDirect->GetVertexList(); VertexListPointerType vertexReverse = pathTempReverse->GetVertexList(); unsigned int numberVertex = 0; VertexIteratorType vertexReverseIt = vertexReverse->End(); - if (vertexReverseIt != vertexReverse->Begin()){ + if (vertexReverseIt != vertexReverse->Begin()) + { --vertexReverseIt; - while ( vertexReverseIt != vertexReverse->Begin()){ - path->AddVertex(vertexReverseIt.Value()); - ++numberVertex; - --vertexReverseIt; + while ( vertexReverseIt != vertexReverse->Begin()) + { + path->AddVertex(vertexReverseIt.Value()); + ++numberVertex; + --vertexReverseIt; } path->AddVertex(vertexReverseIt.Value()); } VertexIteratorType vertexDirectIt = vertexDirect->Begin(); - while ( vertexDirectIt != vertexDirect->End()){ + while ( vertexDirectIt != vertexDirect->End()) + { path->AddVertex(vertexDirectIt.Value()); ++vertexDirectIt; ++numberVertex; @@ -238,422 +241,423 @@ namespace otb // otbMsgDebugMacro(<<"Path number of vertices: "<<numberVertex); - if (numberVertex > 3) { + if (numberVertex > 3) + { outPtr->PushBack(path); } } - } } - /** - * Compute the 8 neighbors to explore from the direction and the type of search (forward or backward). - * \param direction The direction - * \param flagReverse The type of search - * \return The neighborhood - */ - template <class TInputModulus, class TInputDirection, class TOutputPath> - typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::OffsetVectorType - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::GetEightNeighborOffsetFromDirection(double direction, unsigned int flagReverse) +} +/** + * Compute the 8 neighbors to explore from the direction and the type of search (forward or backward). + * \param direction The direction + * \param flagReverse The type of search + * \return The neighborhood + */ +template <class TInputModulus, class TInputDirection, class TOutputPath> +typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::OffsetVectorType +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::GetEightNeighborOffsetFromDirection(double direction, unsigned int flagReverse) +{ + int neighborhoodNumber=0; + OffsetVectorType offset; + offset.reserve(8); + if (direction > 0) + { + //find the direction in terms of 0,1,2,3 + neighborhoodNumber = (int) (direction/(M_PI/4)-1); + } + else { - int neighborhoodNumber=0; - OffsetVectorType offset; - offset.reserve(8); - if (direction > 0) - { - //find the direction in terms of 0,1,2,3 - neighborhoodNumber = (int) (direction/(M_PI/4)-1); - } - else - { - neighborhoodNumber = (int) ((direction+M_PI)/(M_PI/4)-1); - neighborhoodNumber = (neighborhoodNumber + 4); - //if the direction was <0 need to convert to 4,5,6,7 - } - if (flagReverse) - { - //if the reverse flag is activated we need to look on the other side - neighborhoodNumber = (neighborhoodNumber + 4) % 8; - } - OffsetType tmpOffset; - switch( neighborhoodNumber ) - { - case 0: - tmpOffset[0]=1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - - tmpOffset[0]=2; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=2; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=2; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - - break; - - case 1: - tmpOffset[0]=1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - - tmpOffset[0]=2; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - break; - - case 2: - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - - tmpOffset[0]=0; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - break; - - case 3: - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - tmpOffset[0]=-2; - tmpOffset[1]=2; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - break; - - case 4: - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - tmpOffset[0]=-2; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=-2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - break; - - case 5: - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - tmpOffset[0]=-2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 0; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]=2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - break; - - case 6: - tmpOffset[0]= 0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - - tmpOffset[0]= 0; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - break; - - case 7: - tmpOffset[0]= 1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 1; - offset.push_back(tmpOffset); - - tmpOffset[0]= 2; - tmpOffset[1]=-2; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]= 1; - offset.push_back(tmpOffset); - tmpOffset[0]= 2; - tmpOffset[1]= 2; - offset.push_back(tmpOffset); - break; - } - return offset; - }/** + neighborhoodNumber = (int) ((direction+M_PI)/(M_PI/4)-1); + neighborhoodNumber = (neighborhoodNumber + 4); + //if the direction was <0 need to convert to 4,5,6,7 + } + if (flagReverse) + { + //if the reverse flag is activated we need to look on the other side + neighborhoodNumber = (neighborhoodNumber + 4) % 8; + } + OffsetType tmpOffset; + switch ( neighborhoodNumber ) + { + case 0: + tmpOffset[0]=1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + + tmpOffset[0]=2; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=2; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=2; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + + break; + + case 1: + tmpOffset[0]=1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + + tmpOffset[0]=2; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + break; + + case 2: + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + + tmpOffset[0]=0; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + break; + + case 3: + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + tmpOffset[0]=-2; + tmpOffset[1]=2; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + break; + + case 4: + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + tmpOffset[0]=-2; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=-2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + break; + + case 5: + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + tmpOffset[0]=-2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 0; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]=2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + break; + + case 6: + tmpOffset[0]= 0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + + tmpOffset[0]= 0; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + break; + + case 7: + tmpOffset[0]= 1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 1; + offset.push_back(tmpOffset); + + tmpOffset[0]= 2; + tmpOffset[1]=-2; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]= 1; + offset.push_back(tmpOffset); + tmpOffset[0]= 2; + tmpOffset[1]= 2; + offset.push_back(tmpOffset); + break; + } + return offset; +}/** * Compute the 3 neighbors to explore from the direction and the type of search (forward or backward). * \param direction The direction * \param flagReverse The type of search * \return The neighborhood */ - template <class TInputModulus, class TInputDirection, class TOutputPath> - typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::OffsetVectorType - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::GetThreeNeighborOffsetFromDirection(double direction, unsigned int flagReverse) +template <class TInputModulus, class TInputDirection, class TOutputPath> +typename VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::OffsetVectorType +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::GetThreeNeighborOffsetFromDirection(double direction, unsigned int flagReverse) +{ + int neighborhoodNumber=0; + OffsetVectorType offset; + offset.reserve(3); + if (direction > 0) { - int neighborhoodNumber=0; - OffsetVectorType offset; - offset.reserve(3); - if (direction > 0) - { - //find the direction in terms of 0,1,2,3 - neighborhoodNumber = (int) (direction/(M_PI/4)-1); - } - else - { - neighborhoodNumber = (int) ((direction+M_PI)/(M_PI/4)-1); - neighborhoodNumber = (neighborhoodNumber + 4); - //if the direction was <0 need to convert to 4,5,6,7 - } - if (flagReverse) - { - //if the reverse flag is activated we need to look on the other side - neighborhoodNumber = (neighborhoodNumber + 4) % 8; - } - OffsetType tmpOffset; - switch( neighborhoodNumber ) - { - case 0: - tmpOffset[0]=1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - - break; - - case 1: - tmpOffset[0]=1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - - break; - - case 2: - tmpOffset[0]=0; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - - break; - - case 3: - tmpOffset[0]=-1; - tmpOffset[1]=1; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - break; - - case 4: - tmpOffset[0]=-1; - tmpOffset[1]=0; - offset.push_back(tmpOffset); - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - break; - - case 5: - tmpOffset[0]=-1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]=1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - - break; - - case 6: - tmpOffset[0]= 0; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - - break; - - case 7: - tmpOffset[0]= 1; - tmpOffset[1]=-1; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 0; - offset.push_back(tmpOffset); - tmpOffset[0]= 1; - tmpOffset[1]= 1; - offset.push_back(tmpOffset); - - break; - } - return offset; + //find the direction in terms of 0,1,2,3 + neighborhoodNumber = (int) (direction/(M_PI/4)-1); } - - /** - * PrintSelf Method - */ - template <class TInputModulus, class TInputDirection, class TOutputPath> - void - VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + else { - Superclass::PrintSelf(os, indent); + neighborhoodNumber = (int) ((direction+M_PI)/(M_PI/4)-1); + neighborhoodNumber = (neighborhoodNumber + 4); + //if the direction was <0 need to convert to 4,5,6,7 } + if (flagReverse) + { + //if the reverse flag is activated we need to look on the other side + neighborhoodNumber = (neighborhoodNumber + 4) % 8; + } + OffsetType tmpOffset; + switch ( neighborhoodNumber ) + { + case 0: + tmpOffset[0]=1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + + break; + + case 1: + tmpOffset[0]=1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + + break; + + case 2: + tmpOffset[0]=0; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + + break; + + case 3: + tmpOffset[0]=-1; + tmpOffset[1]=1; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + break; + + case 4: + tmpOffset[0]=-1; + tmpOffset[1]=0; + offset.push_back(tmpOffset); + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + break; + + case 5: + tmpOffset[0]=-1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]=1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + + break; + + case 6: + tmpOffset[0]= 0; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + + break; + + case 7: + tmpOffset[0]= 1; + tmpOffset[1]=-1; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 0; + offset.push_back(tmpOffset); + tmpOffset[0]= 1; + tmpOffset[1]= 1; + offset.push_back(tmpOffset); + + break; + } + return offset; +} + +/** + * PrintSelf Method + */ +template <class TInputModulus, class TInputDirection, class TOutputPath> +void +VectorizationPathListFilter<TInputModulus, TInputDirection, TOutputPath> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } // End namespace otb #endif diff --git a/Code/Fusion/otbBayesianFusionFilter.h b/Code/Fusion/otbBayesianFusionFilter.h index 26f2e28b580c0c75a6fafbf1146af4b597d959ea..09fe1ad3e8ab1d2974fd65ebcae76234c3e70a6d 100644 --- a/Code/Fusion/otbBayesianFusionFilter.h +++ b/Code/Fusion/otbBayesianFusionFilter.h @@ -36,140 +36,176 @@ namespace otb { - namespace Functor - { - /** \class BayesianFunctor - * \brief Functor for the bayesian fusion filter. Please refer to BayesianFusionFilter. - * - */ - template <class TInputMultiSpectral, - class TInputMultiSpectralInterp, - class TInputPanchro, - class TOutput> - class BayesianFunctor +namespace Functor +{ +/** \class BayesianFunctor + * \brief Functor for the bayesian fusion filter. Please refer to BayesianFusionFilter. + * + */ +template <class TInputMultiSpectral, +class TInputMultiSpectralInterp, +class TInputPanchro, +class TOutput> +class BayesianFunctor +{ +public: + BayesianFunctor() {}; + ~BayesianFunctor() {}; + typedef typename TInputMultiSpectral::RealValueType RealType; + typedef typename itk::VariableSizeMatrix<RealType> MatrixType; + + void SetLambda(float lambda) { - public: - BayesianFunctor() {}; - ~BayesianFunctor() {}; - typedef typename TInputMultiSpectral::RealValueType RealType; - typedef typename itk::VariableSizeMatrix<RealType> MatrixType; - - void SetLambda(float lambda){ m_Lambda = lambda;}; - void SetS(float S){ m_S = S;}; - void SetAlpha(float alpha){ m_Alpha = alpha;}; - void SetBeta(MatrixType matrix){ m_Beta = matrix;}; - void SetCovarianceInvMatrix(MatrixType matrix){ m_CovarianceInvMatrix = matrix;}; - void SetVcondopt(MatrixType matrix){ m_Vcondopt = matrix;}; - float GetLambda(){ return m_Lambda;}; - float GetAlpha(){ return m_Alpha;}; - float GetS(){ return m_S;}; - MatrixType GetBeta(){ return m_Beta;}; - MatrixType GetCovarianceInvMatrix(){ return m_CovarianceInvMatrix;}; - MatrixType GetVcondopt(){ return m_Vcondopt;}; - - - - inline TOutput operator() (const TInputMultiSpectral & ms, const TInputMultiSpectralInterp & msi, const TInputPanchro & p) - { - TOutput obs; - obs.SetSize(msi.GetSize()); - MatrixType obsMat, msiVect; - obsMat.SetSize(1, obs.GetSize()); - msiVect.SetSize(1, msi.GetSize()); - for (unsigned int i=0; i<msi.GetSize();i++) + m_Lambda = lambda; + }; + void SetS(float S) + { + m_S = S; + }; + void SetAlpha(float alpha) + { + m_Alpha = alpha; + }; + void SetBeta(MatrixType matrix) + { + m_Beta = matrix; + }; + void SetCovarianceInvMatrix(MatrixType matrix) + { + m_CovarianceInvMatrix = matrix; + }; + void SetVcondopt(MatrixType matrix) + { + m_Vcondopt = matrix; + }; + float GetLambda() + { + return m_Lambda; + }; + float GetAlpha() + { + return m_Alpha; + }; + float GetS() + { + return m_S; + }; + MatrixType GetBeta() + { + return m_Beta; + }; + MatrixType GetCovarianceInvMatrix() + { + return m_CovarianceInvMatrix; + }; + MatrixType GetVcondopt() + { + return m_Vcondopt; + }; + + + + inline TOutput operator() (const TInputMultiSpectral & ms, const TInputMultiSpectralInterp & msi, const TInputPanchro & p) + { + TOutput obs; + obs.SetSize(msi.GetSize()); + MatrixType obsMat, msiVect; + obsMat.SetSize(1, obs.GetSize()); + msiVect.SetSize(1, msi.GetSize()); + for (unsigned int i=0; i<msi.GetSize();i++) { msiVect(0, i) = msi[i]; } - obsMat = msiVect*m_CovarianceInvMatrix; - obsMat *= 2*(1-m_Lambda); - MatrixType PanVect; - PanVect = m_Beta.GetTranspose(); - PanVect *= (p-m_Alpha); - PanVect /= m_S; - PanVect *= 2*m_Lambda; - - /** TODO - * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) - * obsMat += PanVect; - **/ - if( (obsMat.Cols() != PanVect.Cols()) || (obsMat.Rows() != PanVect.Rows()) ) + obsMat = msiVect*m_CovarianceInvMatrix; + obsMat *= 2*(1-m_Lambda); + MatrixType PanVect; + PanVect = m_Beta.GetTranspose(); + PanVect *= (p-m_Alpha); + PanVect /= m_S; + PanVect *= 2*m_Lambda; + + /** TODO + * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) + * obsMat += PanVect; + **/ + if ( (obsMat.Cols() != PanVect.Cols()) || (obsMat.Rows() != PanVect.Rows()) ) { itkGenericExceptionMacro( << "Matrix with size (" << obsMat.Rows() << "," << - obsMat.Cols() << ") cannot be subtracted from matrix with size (" << - PanVect.Rows() << "," << PanVect.Cols() << " )" ); + obsMat.Cols() << ") cannot be subtracted from matrix with size (" << + PanVect.Rows() << "," << PanVect.Cols() << " )" ); } - for( unsigned int r=0; r<obsMat.Rows(); r++) + for ( unsigned int r=0; r<obsMat.Rows(); r++) { - for( unsigned int c=0; c<obsMat.Cols(); c++ ) - { - obsMat(r,c) += PanVect(r,c); - } + for ( unsigned int c=0; c<obsMat.Cols(); c++ ) + { + obsMat(r,c) += PanVect(r,c); + } } - //**** END TODO ****/ - obsMat *= m_Vcondopt; - for (unsigned int i=0; i<obs.GetSize();i++) + //**** END TODO ****/ + obsMat *= m_Vcondopt; + for (unsigned int i=0; i<obs.GetSize();i++) { obs[i] = static_cast<typename TOutput::ValueType>(obsMat(0U,i)); } - return obs; - } - - private: - float m_Lambda; - float m_S; - float m_Alpha; - MatrixType m_CovarianceInvMatrix; - MatrixType m_Beta; - MatrixType m_Vcondopt; - }; - } + return obs; + } - /***** TODO *** - * Complete the description with J. Radoux text - */ - /***** END TODO ***/ - - - /** \class BayesianFusionFilter - * \brief Bayesian fusion filter. Contribution of Julien Radoux - * - * Please refer to D. Fasbender, J. Radoux and P. Bogaert, - * Bayesian Data Fusion for Adaptable Image Pansharpening, - * Transactions on Geoscience and Remote Sensing, - * vol. 46, n. 6, 2007, pp 1847-1857 - * - * \sa FusionImageBase - * \sa MatrixTransposeMatrix - * \sa StreamingStatisticsVectorImageFilter - * \ingroup Streamed - * \ingroup Multithreaded - * \ingroup MathematicalStatisticsImageFilters - * - * \ingroup Fusion - * - * - * \example Fusion/BayesianFusionImageFilter.cxx - * - * - */ +private: + float m_Lambda; + float m_S; + float m_Alpha; + MatrixType m_CovarianceInvMatrix; + MatrixType m_Beta; + MatrixType m_Vcondopt; +}; +} + +/***** TODO *** + * Complete the description with J. Radoux text + */ +/***** END TODO ***/ + + +/** \class BayesianFusionFilter + * \brief Bayesian fusion filter. Contribution of Julien Radoux + * + * Please refer to D. Fasbender, J. Radoux and P. Bogaert, + * Bayesian Data Fusion for Adaptable Image Pansharpening, + * Transactions on Geoscience and Remote Sensing, + * vol. 46, n. 6, 2007, pp 1847-1857 + * + * \sa FusionImageBase + * \sa MatrixTransposeMatrix + * \sa StreamingStatisticsVectorImageFilter + * \ingroup Streamed + * \ingroup Multithreaded + * \ingroup MathematicalStatisticsImageFilters + * + * \ingroup Fusion + * + * + * \example Fusion/BayesianFusionImageFilter.cxx + * + * + */ template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> class ITK_EXPORT BayesianFusionFilter - : public FusionImageBase<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage, - Functor::BayesianFunctor<ITK_TYPENAME TInputMultiSpectralImage::PixelType, - ITK_TYPENAME TInputMultiSpectralInterpImage::PixelType, - ITK_TYPENAME TInputPanchroImage::PixelType, - ITK_TYPENAME TOutputImage::PixelType> > + : public FusionImageBase<TInputMultiSpectralImage, + TInputMultiSpectralInterpImage, + TInputPanchroImage, + TOutputImage, + Functor::BayesianFunctor<ITK_TYPENAME TInputMultiSpectralImage::PixelType, + ITK_TYPENAME TInputMultiSpectralInterpImage::PixelType, + ITK_TYPENAME TInputPanchroImage::PixelType, + ITK_TYPENAME TOutputImage::PixelType> > { public: -/** Extract input and output images dimensions.*/ + /** Extract input and output images dimensions.*/ itkStaticConstMacro( InputImageDimension, unsigned int, TInputMultiSpectralImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); @@ -184,13 +220,13 @@ public: /** "typedef" for standard classes. */ typedef BayesianFusionFilter Self; typedef FusionImageBase< InputMultiSpectralImageType, - InputMultiSpectralInterpImageType, - InputPanchroImageType, - OutputImageType, - Functor::BayesianFunctor<ITK_TYPENAME InputMultiSpectralImageType::PixelType, - ITK_TYPENAME InputMultiSpectralInterpImageType::PixelType, - ITK_TYPENAME InputPanchroImageType::PixelType, - ITK_TYPENAME OutputImageType::PixelType> > Superclass; + InputMultiSpectralInterpImageType, + InputPanchroImageType, + OutputImageType, + Functor::BayesianFunctor<ITK_TYPENAME InputMultiSpectralImageType::PixelType, + ITK_TYPENAME InputMultiSpectralInterpImageType::PixelType, + ITK_TYPENAME InputPanchroImageType::PixelType, + ITK_TYPENAME OutputImageType::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; diff --git a/Code/Fusion/otbBayesianFusionFilter.txx b/Code/Fusion/otbBayesianFusionFilter.txx index fd73f260650386da85cc1c516e9a337fd5ad7626..5b75d41b27c7b3f8f46442bf962ee862db5ef401 100644 --- a/Code/Fusion/otbBayesianFusionFilter.txx +++ b/Code/Fusion/otbBayesianFusionFilter.txx @@ -28,299 +28,299 @@ namespace otb { - template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> - BayesianFusionFilter<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage> - ::BayesianFusionFilter() +template <class TInputMultiSpectralImage, +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> +BayesianFusionFilter<TInputMultiSpectralImage, +TInputMultiSpectralInterpImage, +TInputPanchroImage, +TOutputImage> +::BayesianFusionFilter() +{ + m_Lambda = 0.9999; + m_S = 1; + m_StatisticsHaveBeenGenerated = false; +} + + +template <class TInputMultiSpectralImage, +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> +BayesianFusionFilter<TInputMultiSpectralImage, +TInputMultiSpectralInterpImage, +TInputPanchroImage, +TOutputImage> +::~BayesianFusionFilter() +{ + +} +template <class TInputMultiSpectralImage, +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> +void +BayesianFusionFilter<TInputMultiSpectralImage, +TInputMultiSpectralInterpImage, +TInputPanchroImage, +TOutputImage> +::Modified() +{ + Superclass::Modified(); + m_StatisticsHaveBeenGenerated = false; +} + +template <class TInputMultiSpectralImage, +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> +void +BayesianFusionFilter<TInputMultiSpectralImage, +TInputMultiSpectralInterpImage, +TInputPanchroImage, +TOutputImage> +::BeforeThreadedGenerateData () +{ + if (!m_StatisticsHaveBeenGenerated) { - m_Lambda = 0.9999; - m_S = 1; - m_StatisticsHaveBeenGenerated = false; + this->ComputeInternalStatistics(); + m_StatisticsHaveBeenGenerated = true; } - - - template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> - BayesianFusionFilter<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage> - ::~BayesianFusionFilter() +} + +template <class TInputMultiSpectralImage, +class TInputMultiSpectralInterpImage, +class TInputPanchroImage, +class TOutputImage> +void +BayesianFusionFilter<TInputMultiSpectralImage, +TInputMultiSpectralInterpImage, +TInputPanchroImage, +TOutputImage> +::ComputeInternalStatistics() +{ + OutputImageRegionType msiRequestedRegion = this->GetMultiSpectInterp()->GetRequestedRegion(); + OutputImageRegionType msRequestedRegion = this->GetMultiSpect()->GetRequestedRegion(); + OutputImageRegionType panchroRequestedRegion = this->GetPanchro()->GetRequestedRegion(); + + // Allocate output + typename OutputImageType::Pointer output = this->GetOutput(); + typename InputMultiSpectralImageType::Pointer multiSpec = const_cast<InputMultiSpectralImageType *>(this->GetMultiSpect()); + typename InputMultiSpectralInterpImageType::Pointer multiSpecInterp = const_cast<InputMultiSpectralInterpImageType *>(this->GetMultiSpectInterp()); + typename InputPanchroImageType::Pointer panchro = const_cast<InputPanchroImageType *>(this->GetPanchro()); + + /** Variable Initialisaton */ + m_Beta.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel()+1, 1); + m_Beta.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + + m_CovarianceMatrix.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); + m_CovarianceMatrix.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + + m_CovarianceInvMatrix.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); + m_CovarianceInvMatrix.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + + m_Vcondopt.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); + m_Vcondopt.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + /** Compute the inverse of the multispectral interpolated image covariance matrix */ + typename StreamingStatisticsVectorImageFilterType::Pointer covComputefilter = StreamingStatisticsVectorImageFilterType::New(); + + covComputefilter->SetInput(multiSpecInterp); + covComputefilter->Update(); + + + MatrixType m_CovarianceMatrix = covComputefilter->GetCovariance(); + otbMsgDebugMacro(<<"Covariance: "<<m_CovarianceMatrix); + + m_CovarianceInvMatrix = m_CovarianceMatrix.GetInverse(); + /** Beta computation : Regression model coefficient */ + // MatrixTransform only support vectorimage input + typename CasterType::Pointer caster = CasterType::New(); + caster->SetInput(panchro); + // caster->Update(); + // Compute the transpose multispectral image multiplied by itself + typename MSTransposeMSType::Pointer msTransposeMs = MSTransposeMSType::New(); + // Compute the transpose multispectral image multiplied by the panchromatic one + typename MSTransposeMSType::Pointer msTransposePan = MSTransposeMSType::New(); + // Add a dimension filled with ones to the images + msTransposeMs->SetUsePadFirstInput(true); + msTransposeMs->SetUsePadSecondInput(true); + msTransposePan->SetUsePadFirstInput(true); + + msTransposeMs->SetFirstInput(multiSpec); + msTransposeMs->SetSecondInput(multiSpec); + + msTransposePan->SetFirstInput(multiSpec); + msTransposePan->SetSecondInput( caster->GetOutput() ); + + msTransposeMs->Update(); + otbMsgDebugMacro(<<"MsTMs: "<<msTransposeMs->GetResultOutput()->Get()); + msTransposePan->Update(); + otbMsgDebugMacro(<<"MsTPan: "<<msTransposePan->GetResultOutput()->Get()); + + MatrixType temp; + temp = msTransposeMs->GetResultOutput()->Get().GetInverse(); + m_Beta = temp*msTransposePan->GetResultOutput()->Get(); + + // S computation : quadratique mean of the regression residue + // Compute the transpose panchromatic image multiplied by itself + typename MSTransposeMSType::Pointer panTransposePan = MSTransposeMSType::New(); + panTransposePan->SetFirstInput(caster->GetOutput()); + panTransposePan->SetSecondInput(caster->GetOutput()); + panTransposePan->Update(); + otbMsgDebugMacro(<<"PanTPan: "<<msTransposePan->GetResultOutput()->Get()); + MatrixType S, tempS, tempS2; + S = panTransposePan->GetResultOutput()->Get(); + tempS = msTransposePan->GetResultOutput()->Get().GetTranspose(); + tempS = tempS*m_Beta; + + /** TODO + * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) + * S = S-tempS; + **/ + if ( (S.Rows() != tempS.Rows()) || (S.Cols() != tempS.Cols())) { - + itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << + S.Cols() << ") cannot be subtracted from matrix with size (" << + tempS.Rows() << "," << tempS.Cols() <<" )" ); } - template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> - void - BayesianFusionFilter<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage> - ::Modified() - { - Superclass::Modified(); - m_StatisticsHaveBeenGenerated = false; - } - - template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> - void - BayesianFusionFilter<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage> - ::BeforeThreadedGenerateData () + for ( unsigned int r=0; r<S.Rows(); r++) { - if(!m_StatisticsHaveBeenGenerated) + for ( unsigned int c=0; c<S.Cols(); c++ ) { - this->ComputeInternalStatistics(); - m_StatisticsHaveBeenGenerated = true; + S(r,c) -= tempS(r,c); } } + //**** END TODO ****/ - template <class TInputMultiSpectralImage, - class TInputMultiSpectralInterpImage, - class TInputPanchroImage, - class TOutputImage> - void - BayesianFusionFilter<TInputMultiSpectralImage, - TInputMultiSpectralInterpImage, - TInputPanchroImage, - TOutputImage> - ::ComputeInternalStatistics() - { - OutputImageRegionType msiRequestedRegion = this->GetMultiSpectInterp()->GetRequestedRegion(); - OutputImageRegionType msRequestedRegion = this->GetMultiSpect()->GetRequestedRegion(); - OutputImageRegionType panchroRequestedRegion = this->GetPanchro()->GetRequestedRegion(); - - // Allocate output - typename OutputImageType::Pointer output = this->GetOutput(); - typename InputMultiSpectralImageType::Pointer multiSpec = const_cast<InputMultiSpectralImageType *>(this->GetMultiSpect()); - typename InputMultiSpectralInterpImageType::Pointer multiSpecInterp = const_cast<InputMultiSpectralInterpImageType *>(this->GetMultiSpectInterp()); - typename InputPanchroImageType::Pointer panchro = const_cast<InputPanchroImageType *>(this->GetPanchro()); - - /** Variable Initialisaton */ - m_Beta.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel()+1, 1); - m_Beta.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - - m_CovarianceMatrix.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); - m_CovarianceMatrix.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - - m_CovarianceInvMatrix.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); - m_CovarianceInvMatrix.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - - m_Vcondopt.SetSize( multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel() ); - m_Vcondopt.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - /** Compute the inverse of the multispectral interpolated image covariance matrix */ - typename StreamingStatisticsVectorImageFilterType::Pointer covComputefilter = StreamingStatisticsVectorImageFilterType::New(); - - covComputefilter->SetInput(multiSpecInterp); - covComputefilter->Update(); - - - MatrixType m_CovarianceMatrix = covComputefilter->GetCovariance(); - otbMsgDebugMacro(<<"Covariance: "<<m_CovarianceMatrix); - - m_CovarianceInvMatrix = m_CovarianceMatrix.GetInverse(); - /** Beta computation : Regression model coefficient */ - // MatrixTransform only support vectorimage input - typename CasterType::Pointer caster = CasterType::New(); - caster->SetInput(panchro); - // caster->Update(); - // Compute the transpose multispectral image multiplied by itself - typename MSTransposeMSType::Pointer msTransposeMs = MSTransposeMSType::New(); - // Compute the transpose multispectral image multiplied by the panchromatic one - typename MSTransposeMSType::Pointer msTransposePan = MSTransposeMSType::New(); - // Add a dimension filled with ones to the images - msTransposeMs->SetUsePadFirstInput(true); - msTransposeMs->SetUsePadSecondInput(true); - msTransposePan->SetUsePadFirstInput(true); - - msTransposeMs->SetFirstInput(multiSpec); - msTransposeMs->SetSecondInput(multiSpec); - - msTransposePan->SetFirstInput(multiSpec); - msTransposePan->SetSecondInput( caster->GetOutput() ); - - msTransposeMs->Update(); - otbMsgDebugMacro(<<"MsTMs: "<<msTransposeMs->GetResultOutput()->Get()); - msTransposePan->Update(); - otbMsgDebugMacro(<<"MsTPan: "<<msTransposePan->GetResultOutput()->Get()); - - MatrixType temp; - temp = msTransposeMs->GetResultOutput()->Get().GetInverse(); - m_Beta = temp*msTransposePan->GetResultOutput()->Get(); - - // S computation : quadratique mean of the regression residue - // Compute the transpose panchromatic image multiplied by itself - typename MSTransposeMSType::Pointer panTransposePan = MSTransposeMSType::New(); - panTransposePan->SetFirstInput(caster->GetOutput()); - panTransposePan->SetSecondInput(caster->GetOutput()); - panTransposePan->Update(); - otbMsgDebugMacro(<<"PanTPan: "<<msTransposePan->GetResultOutput()->Get()); - MatrixType S, tempS, tempS2; - S = panTransposePan->GetResultOutput()->Get(); - tempS = msTransposePan->GetResultOutput()->Get().GetTranspose(); - tempS = tempS*m_Beta; - - /** TODO - * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) - * S = S-tempS; - **/ - if( (S.Rows() != tempS.Rows()) || (S.Cols() != tempS.Cols())) - { - itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << - S.Cols() << ") cannot be subtracted from matrix with size (" << - tempS.Rows() << "," << tempS.Cols() <<" )" ); - } - for( unsigned int r=0; r<S.Rows(); r++) - { - for( unsigned int c=0; c<S.Cols(); c++ ) - { - S(r,c) -= tempS(r,c); - } - } - //**** END TODO ****/ - - tempS = m_Beta.GetTranspose(); - tempS2 = msTransposePan->GetResultOutput()->Get(); - tempS = tempS*tempS2; - /** TODO - * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) - * S = S-tempS; - **/ - if( (S.Rows() != tempS.Rows()) || (S.Cols() != tempS.Cols()) ) - { - itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << - S.Cols() << ") cannot be subtracted from matrix with size (" << - tempS.Rows() << "," << tempS.Cols() << " )" ); - - } - for( unsigned int r=0; r<S.Rows(); r++) - { - for( unsigned int c=0; c<S.Cols(); c++ ) + tempS = m_Beta.GetTranspose(); + tempS2 = msTransposePan->GetResultOutput()->Get(); + tempS = tempS*tempS2; + /** TODO + * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) + * S = S-tempS; + **/ + if ( (S.Rows() != tempS.Rows()) || (S.Cols() != tempS.Cols()) ) + { + itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << + S.Cols() << ") cannot be subtracted from matrix with size (" << + tempS.Rows() << "," << tempS.Cols() << " )" ); + + } + for ( unsigned int r=0; r<S.Rows(); r++) + { + for ( unsigned int c=0; c<S.Cols(); c++ ) { S(r,c) -= tempS(r,c); } - } - //**** END TODO ****/ - - - MatrixType xxT, xxTb, xxTbT, xxTbTb; - xxT = msTransposeMs->GetResultOutput()->Get().GetTranspose(); - xxTb = xxT*m_Beta; - xxTbT = xxTb.GetTranspose(); - xxTbTb = xxTbT*m_Beta; - /** TODO - * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) - * S = S-xxTbTb; - **/ - if( (S.Cols() != xxTbTb.Cols()) || (S.Cols() != xxTbTb.Cols()) ) - { - itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << - S.Cols() << ") cannot be subtracted from matrix with size (" << - xxTbTb.Rows() << "," << xxTbTb.Cols() << " )" ); - } - - for( unsigned int r=0; r<S.Rows(); r++) - { - for( unsigned int c=0; c<S.Cols(); c++ ) - { - S(r,c) += xxTbTb(r,c); - } - } - //**** END TODO ****/ - - unsigned int size1 = multiSpec->GetLargestPossibleRegion().GetSize()[0]*multiSpec->GetLargestPossibleRegion().GetSize()[1]; - unsigned int size2 = multiSpec->GetNumberOfComponentsPerPixel()+1; - m_S = S(0,0); - m_S /= static_cast<float>(size1-size2); - - // cutBeta is the N-1 last m_Beta element matrix. - // varPan contains transpose(cutBeta)*cutBeta/S - MatrixType varPan, cutBeta; - varPan.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), 1); - varPan.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - cutBeta.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), 1); - cutBeta.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - // Take the N-1 m_Beta last elements - for( unsigned int r=1; r<m_Beta.Rows(); r++ ) - { - cutBeta(r-1,0) = m_Beta(r,0); - } - varPan = cutBeta; - - MatrixType tempvarPan; - tempvarPan = varPan.GetTranspose(); - varPan *= tempvarPan; - varPan /= m_S; - // Compute the optimization matrix : m_Vcondopt - // eye is the identical matrix which size is the number of components of the multispectral image - MatrixType eye; - eye.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel()); - eye.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); - for( unsigned int r=1; r<eye.Rows(); r++) - { - eye(r,r) = vcl_pow(10., -12.); - } - - /** TODO - * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) - * m_Vcondopt = 2 *m_Lambda*varPan+2*m_CovarianceInvMatrix*(1-m_Lambda)+eye; - **/ - if( (m_Vcondopt.Cols() != varPan.Cols()) || (m_Vcondopt.Cols() != varPan.Cols()) - || (m_Vcondopt.Cols() != m_CovarianceInvMatrix.Cols()) || (m_Vcondopt.Cols() != m_CovarianceInvMatrix.Cols())) - { - itkExceptionMacro( << "Matrix with size (" << m_Vcondopt.Rows() << "," << - m_Vcondopt.Cols() << ") cannot be subtracted from matrix with size (" << - varPan.Rows() << "," << varPan.Cols() << " ) or ( " << - m_CovarianceInvMatrix.Rows() << "," << m_CovarianceInvMatrix.Cols()<<")" ); - } - for( unsigned int r=0; r<m_Vcondopt.Rows(); r++) - { - for( unsigned int c=0; c<m_Vcondopt.Cols(); c++ ) - { - m_Vcondopt(r,c) = 2 *m_Lambda*varPan(r,c) - +2*m_CovarianceInvMatrix(r,c)*(1-m_Lambda) - +eye(r,c); - } - } + } //**** END TODO ****/ - m_Vcondopt = m_Vcondopt.GetInverse(); - // Functor initialisation - this->GetFunctor().SetVcondopt(m_Vcondopt); - this->GetFunctor().SetBeta(cutBeta); - this->GetFunctor().SetAlpha(m_Beta(0,0)); - this->GetFunctor().SetCovarianceInvMatrix(m_CovarianceInvMatrix); - this->GetFunctor().SetLambda(m_Lambda); - this->GetFunctor().SetS(m_S); - // Restore the previous buffered data - multiSpecInterp->SetRequestedRegion(msiRequestedRegion); - multiSpecInterp->PropagateRequestedRegion(); - multiSpecInterp->UpdateOutputData(); + MatrixType xxT, xxTb, xxTbT, xxTbTb; + xxT = msTransposeMs->GetResultOutput()->Get().GetTranspose(); + xxTb = xxT*m_Beta; + xxTbT = xxTb.GetTranspose(); + xxTbTb = xxTbT*m_Beta; + /** TODO + * To modify using - method operator. If we use it now -> exceptionmacro (no GetClassName...) + * S = S-xxTbTb; + **/ + if ( (S.Cols() != xxTbTb.Cols()) || (S.Cols() != xxTbTb.Cols()) ) + { + itkExceptionMacro( << "Matrix with size (" << S.Rows() << "," << + S.Cols() << ") cannot be subtracted from matrix with size (" << + xxTbTb.Rows() << "," << xxTbTb.Cols() << " )" ); + } - multiSpec->SetRequestedRegion(msRequestedRegion); - multiSpec->PropagateRequestedRegion(); - multiSpec->UpdateOutputData(); + for ( unsigned int r=0; r<S.Rows(); r++) + { + for ( unsigned int c=0; c<S.Cols(); c++ ) + { + S(r,c) += xxTbTb(r,c); + } + } + //**** END TODO ****/ - panchro->SetRequestedRegion(panchroRequestedRegion); - panchro->PropagateRequestedRegion(); - panchro->UpdateOutputData(); + unsigned int size1 = multiSpec->GetLargestPossibleRegion().GetSize()[0]*multiSpec->GetLargestPossibleRegion().GetSize()[1]; + unsigned int size2 = multiSpec->GetNumberOfComponentsPerPixel()+1; + m_S = S(0,0); + m_S /= static_cast<float>(size1-size2); + + // cutBeta is the N-1 last m_Beta element matrix. + // varPan contains transpose(cutBeta)*cutBeta/S + MatrixType varPan, cutBeta; + varPan.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), 1); + varPan.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + cutBeta.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), 1); + cutBeta.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + // Take the N-1 m_Beta last elements + for ( unsigned int r=1; r<m_Beta.Rows(); r++ ) + { + cutBeta(r-1,0) = m_Beta(r,0); + } + varPan = cutBeta; + + MatrixType tempvarPan; + tempvarPan = varPan.GetTranspose(); + varPan *= tempvarPan; + varPan /= m_S; + // Compute the optimization matrix : m_Vcondopt + // eye is the identical matrix which size is the number of components of the multispectral image + MatrixType eye; + eye.SetSize(multiSpecInterp->GetNumberOfComponentsPerPixel(), multiSpecInterp->GetNumberOfComponentsPerPixel()); + eye.Fill(itk::NumericTraits<InputMultiSpectralInterpRealType>::Zero); + for ( unsigned int r=1; r<eye.Rows(); r++) + { + eye(r,r) = vcl_pow(10., -12.); + } + /** TODO + * To modify using + method operator. If we use it now -> exceptionmacro (no GetClassName...) + * m_Vcondopt = 2 *m_Lambda*varPan+2*m_CovarianceInvMatrix*(1-m_Lambda)+eye; + **/ + if ( (m_Vcondopt.Cols() != varPan.Cols()) || (m_Vcondopt.Cols() != varPan.Cols()) + || (m_Vcondopt.Cols() != m_CovarianceInvMatrix.Cols()) || (m_Vcondopt.Cols() != m_CovarianceInvMatrix.Cols())) + { + itkExceptionMacro( << "Matrix with size (" << m_Vcondopt.Rows() << "," << + m_Vcondopt.Cols() << ") cannot be subtracted from matrix with size (" << + varPan.Rows() << "," << varPan.Cols() << " ) or ( " << + m_CovarianceInvMatrix.Rows() << "," << m_CovarianceInvMatrix.Cols()<<")" ); } + for ( unsigned int r=0; r<m_Vcondopt.Rows(); r++) + { + for ( unsigned int c=0; c<m_Vcondopt.Cols(); c++ ) + { + m_Vcondopt(r,c) = 2 *m_Lambda*varPan(r,c) + +2*m_CovarianceInvMatrix(r,c)*(1-m_Lambda) + +eye(r,c); + } + } + //**** END TODO ****/ + m_Vcondopt = m_Vcondopt.GetInverse(); + // Functor initialisation + this->GetFunctor().SetVcondopt(m_Vcondopt); + this->GetFunctor().SetBeta(cutBeta); + this->GetFunctor().SetAlpha(m_Beta(0,0)); + this->GetFunctor().SetCovarianceInvMatrix(m_CovarianceInvMatrix); + this->GetFunctor().SetLambda(m_Lambda); + this->GetFunctor().SetS(m_S); + + + // Restore the previous buffered data + multiSpecInterp->SetRequestedRegion(msiRequestedRegion); + multiSpecInterp->PropagateRequestedRegion(); + multiSpecInterp->UpdateOutputData(); + + multiSpec->SetRequestedRegion(msRequestedRegion); + multiSpec->PropagateRequestedRegion(); + multiSpec->UpdateOutputData(); + + panchro->SetRequestedRegion(panchroRequestedRegion); + panchro->PropagateRequestedRegion(); + panchro->UpdateOutputData(); + +} } // end namespace otb #endif diff --git a/Code/Fusion/otbFusionImageBase.h b/Code/Fusion/otbFusionImageBase.h index 9da333376bf7a98c8b6ffa84a9c355dd9de23dcf..c5a3493934f634602af4db44c57b6d8298c5cd9b 100644 --- a/Code/Fusion/otbFusionImageBase.h +++ b/Code/Fusion/otbFusionImageBase.h @@ -24,95 +24,104 @@ namespace otb { - /** \class FusionImageBase - * Basic class for every Fusion classes. - * \sa TernaryFunctorImageFilter - */ - template <class TInputMultiSpectralImage, class TInputMultiSpectralInterpImage, class TInputPanchroImage, class TOutputImage, class TFunctor> - class ITK_EXPORT FusionImageBase : public itk::TernaryFunctorImageFilter<TInputMultiSpectralImage, TInputMultiSpectralInterpImage, TInputPanchroImage, TOutputImage, TFunctor> - { - public: - /** Extract input and output images dimensions.*/ - itkStaticConstMacro( InputImageDimension,unsigned int, TInputMultiSpectralImage::ImageDimension); - itkStaticConstMacro( OutputImageDimension,unsigned int, TOutputImage::ImageDimension); - - /** "typedef" to simplify the variables definition and the declaration. */ - typedef TInputMultiSpectralImage InputMultiSpectralImageType; - typedef TInputMultiSpectralInterpImage InputMultiSpectralInterpImageType; - typedef TInputPanchroImage InputPanchroImageType; - typedef TOutputImage OutputImageType; - typedef TFunctor FunctorType; - - /** "typedef" for standard classes. */ - typedef FusionImageBase Self; - typedef itk::TernaryFunctorImageFilter< InputMultiSpectralImageType, - InputMultiSpectralInterpImageType, - InputPanchroImageType, - OutputImageType, - FunctorType> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** object factory method. */ - itkNewMacro(Self); - - /** return class name. */ - itkTypeMacro(FusionImageBase, TernaryFunctorImageFilter); - - /** Supported images definition. */ - typedef typename InputMultiSpectralImageType::PixelType InputMultiSpectralPixelType; - typedef typename InputMultiSpectralInterpImageType::PixelType InputMultiSpectralInterpPixelType; - typedef typename InputPanchroImageType::PixelType InputPanchroPixelType; - typedef typename OutputImageType::PixelType OutputPixelType; - /** Real class typedef definition. */ - typedef typename itk::NumericTraits<InputMultiSpectralPixelType>::RealType InputMultiSpectralRealType; - typedef typename itk::NumericTraits<InputMultiSpectralInterpPixelType>::RealType InputMultiSpectralInterpRealType; - typedef typename itk::NumericTraits<InputPanchroPixelType>::RealType InputPanchroRealType; - typedef typename InputMultiSpectralImageType::RegionType InputMultiSpectralImageRegionType; - typedef typename InputMultiSpectralInterpImageType::RegionType InputMultiSpectralInterpImageRegionType; - typedef typename InputPanchroImageType::RegionType InputPanchroImageRegionType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - - /** Image size "typedef" definition. */ - typedef typename InputMultiSpectralImageType::SizeType SizeType; - - - void SetMultiSpect(const InputMultiSpectralImageType *multiSpect){ this->SetInput1( multiSpect ); }; - void SetMultiSpectInterp(const InputMultiSpectralInterpImageType *multiSpectInterp){ this->SetInput2( multiSpectInterp ); }; - void SetPanchro(const InputPanchroImageType *panchro){ this->SetInput3( panchro ); }; - - const InputMultiSpectralImageType* GetMultiSpect() +/** \class FusionImageBase + * Basic class for every Fusion classes. + * \sa TernaryFunctorImageFilter + */ +template <class TInputMultiSpectralImage, class TInputMultiSpectralInterpImage, class TInputPanchroImage, class TOutputImage, class TFunctor> +class ITK_EXPORT FusionImageBase : public itk::TernaryFunctorImageFilter<TInputMultiSpectralImage, TInputMultiSpectralInterpImage, TInputPanchroImage, TOutputImage, TFunctor> +{ +public: + /** Extract input and output images dimensions.*/ + itkStaticConstMacro( InputImageDimension,unsigned int, TInputMultiSpectralImage::ImageDimension); + itkStaticConstMacro( OutputImageDimension,unsigned int, TOutputImage::ImageDimension); + + /** "typedef" to simplify the variables definition and the declaration. */ + typedef TInputMultiSpectralImage InputMultiSpectralImageType; + typedef TInputMultiSpectralInterpImage InputMultiSpectralInterpImageType; + typedef TInputPanchroImage InputPanchroImageType; + typedef TOutputImage OutputImageType; + typedef TFunctor FunctorType; + + /** "typedef" for standard classes. */ + typedef FusionImageBase Self; + typedef itk::TernaryFunctorImageFilter< InputMultiSpectralImageType, + InputMultiSpectralInterpImageType, + InputPanchroImageType, + OutputImageType, + FunctorType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** object factory method. */ + itkNewMacro(Self); + + /** return class name. */ + itkTypeMacro(FusionImageBase, TernaryFunctorImageFilter); + + /** Supported images definition. */ + typedef typename InputMultiSpectralImageType::PixelType InputMultiSpectralPixelType; + typedef typename InputMultiSpectralInterpImageType::PixelType InputMultiSpectralInterpPixelType; + typedef typename InputPanchroImageType::PixelType InputPanchroPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + /** Real class typedef definition. */ + typedef typename itk::NumericTraits<InputMultiSpectralPixelType>::RealType InputMultiSpectralRealType; + typedef typename itk::NumericTraits<InputMultiSpectralInterpPixelType>::RealType InputMultiSpectralInterpRealType; + typedef typename itk::NumericTraits<InputPanchroPixelType>::RealType InputPanchroRealType; + typedef typename InputMultiSpectralImageType::RegionType InputMultiSpectralImageRegionType; + typedef typename InputMultiSpectralInterpImageType::RegionType InputMultiSpectralInterpImageRegionType; + typedef typename InputPanchroImageType::RegionType InputPanchroImageRegionType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + /** Image size "typedef" definition. */ + typedef typename InputMultiSpectralImageType::SizeType SizeType; + + + void SetMultiSpect(const InputMultiSpectralImageType *multiSpect) + { + this->SetInput1( multiSpect ); + }; + void SetMultiSpectInterp(const InputMultiSpectralInterpImageType *multiSpectInterp) { - if( this->GetNumberOfInputs() < 1 ) - { - return 0; - } + this->SetInput2( multiSpectInterp ); + }; + void SetPanchro(const InputPanchroImageType *panchro) + { + this->SetInput3( panchro ); + }; + + const InputMultiSpectralImageType* GetMultiSpect() + { + if ( this->GetNumberOfInputs() < 1 ) + { + return 0; + } else return( static_cast<const InputMultiSpectralImageType *>(this->itk::ProcessObject::GetInput(0)) ); } - const InputMultiSpectralInterpImageType* GetMultiSpectInterp() + const InputMultiSpectralInterpImageType* GetMultiSpectInterp() { - if( this->GetNumberOfInputs() < 2 ) - { - return 0; - } + if ( this->GetNumberOfInputs() < 2 ) + { + return 0; + } else return( static_cast<const InputMultiSpectralInterpImageType *>(this->itk::ProcessObject::GetInput(1)) ); } - const InputPanchroImageType* GetPanchro() + const InputPanchroImageType* GetPanchro() { - if( this->GetNumberOfInputs() < 3 ) - { - return 0; - } + if ( this->GetNumberOfInputs() < 3 ) + { + return 0; + } else return( static_cast<const InputPanchroImageType *>(this->itk::ProcessObject::GetInput(2)) ); } - }; +}; } // end namespace otb diff --git a/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.h b/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.h index 547c93b3a2d8531fbd40e0c82655299b549ac350..3156f8472b81acae0133c66476fa36c723438004 100644 --- a/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.h +++ b/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.h @@ -26,99 +26,100 @@ #include "itkDivideImageFilter.h" #include "itkMultiplyImageFilter.h" -namespace otb { - /** - * \class SimpleRcsPanSharpeningFusionImageFilter - * \brief This class performs a simple Pan sharpening operation - * - * Given a Pan image and the corresponding Xs image (oversampled to have the - * same number of pixels), this filter realizes a simple Pan sharpening - * operation: - * - * \f[ \frac{XS}{\mathrm{Filtered}(PAN)} PAN \f] - * - * \ingroup Streamed - * \ingroup Multithreaded - * \ingroup Fusion - * - * - * \example Fusion/PanSharpeningExample.cxx - * - **/ - - template <class TPanImageType,class TXsImageType,class TOutputImageType> +namespace otb +{ +/** + * \class SimpleRcsPanSharpeningFusionImageFilter + * \brief This class performs a simple Pan sharpening operation + * + * Given a Pan image and the corresponding Xs image (oversampled to have the + * same number of pixels), this filter realizes a simple Pan sharpening + * operation: + * + * \f[ \frac{XS}{\mathrm{Filtered}(PAN)} PAN \f] + * + * \ingroup Streamed + * \ingroup Multithreaded + * \ingroup Fusion + * + * + * \example Fusion/PanSharpeningExample.cxx + * + **/ + +template <class TPanImageType,class TXsImageType,class TOutputImageType> class ITK_EXPORT SimpleRcsPanSharpeningFusionImageFilter : - public itk::ImageToImageFilter<TXsImageType, TOutputImageType> - { - public: - typedef SimpleRcsPanSharpeningFusionImageFilter Self; - typedef itk::ImageToImageFilter - <TXsImageType, TOutputImageType> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef otb::Image<double,2> InternalImageType; - typedef otb::VectorImage<double> InternalVectorImageType; + public itk::ImageToImageFilter<TXsImageType, TOutputImageType> +{ +public: + typedef SimpleRcsPanSharpeningFusionImageFilter Self; + typedef itk::ImageToImageFilter + <TXsImageType, TOutputImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef otb::Image<double,2> InternalImageType; + typedef otb::VectorImage<double> InternalVectorImageType; - typedef typename InternalImageType::PixelType InternalPixelType; - typedef typename itk::NumericTraits<InternalPixelType>::RealType InternalRealType; - typedef typename itk::Array<InternalRealType> ArrayType; + typedef typename InternalImageType::PixelType InternalPixelType; + typedef typename itk::NumericTraits<InternalPixelType>::RealType InternalRealType; + typedef typename itk::Array<InternalRealType> ArrayType; - /** Method for creation through object factory */ - itkNewMacro(Self); + /** Method for creation through object factory */ + itkNewMacro(Self); - /** Run-time type information */ - itkTypeMacro(SimpleRcsPanSharpeningFusionImageFilter, - itk::ImageToImageFilter); + /** Run-time type information */ + itkTypeMacro(SimpleRcsPanSharpeningFusionImageFilter, + itk::ImageToImageFilter); - /** Display */ - void PrintSelf( std::ostream& os, itk::Indent indent ) const; + /** Display */ + void PrintSelf( std::ostream& os, itk::Indent indent ) const; - typedef typename InternalImageType::SizeType RadiusType; + typedef typename InternalImageType::SizeType RadiusType; - /** Set the filter radius */ - itkGetMacro( Radius, RadiusType); - itkSetMacro( Radius, RadiusType); + /** Set the filter radius */ + itkGetMacro( Radius, RadiusType); + itkSetMacro( Radius, RadiusType); - /** Set the input filter */ - itkSetMacro(Filter, ArrayType); - itkGetConstReferenceMacro(Filter, ArrayType); + /** Set the input filter */ + itkSetMacro(Filter, ArrayType); + itkGetConstReferenceMacro(Filter, ArrayType); - virtual void SetPanInput( const TPanImageType * image); - const TPanImageType * GetPanInput(void) const; + virtual void SetPanInput( const TPanImageType * image); + const TPanImageType * GetPanInput(void) const; - virtual void SetXsInput( const TXsImageType * path); - const TXsImageType * GetXsInput(void) const; + virtual void SetXsInput( const TXsImageType * path); + const TXsImageType * GetXsInput(void) const; - protected: +protected: - SimpleRcsPanSharpeningFusionImageFilter(); + SimpleRcsPanSharpeningFusionImageFilter(); - typedef otb::ConvolutionImageFilter - <TPanImageType, InternalImageType> ConvolutionFilterType; - typedef itk::DivideImageFilter - <TXsImageType,InternalImageType, - InternalVectorImageType> DivideFilterType; - typedef itk::MultiplyImageFilter - <InternalVectorImageType,TPanImageType,TOutputImageType> MultiplyFilterType; + typedef otb::ConvolutionImageFilter + <TPanImageType, InternalImageType> ConvolutionFilterType; + typedef itk::DivideImageFilter + <TXsImageType,InternalImageType, + InternalVectorImageType> DivideFilterType; + typedef itk::MultiplyImageFilter + <InternalVectorImageType,TPanImageType,TOutputImageType> MultiplyFilterType; // Software Guide : EndCodeSnippet - void GenerateData(); + void GenerateData(); - private: +private: - SimpleRcsPanSharpeningFusionImageFilter(Self&); // intentionally not implemented - void operator=(const Self&); // intentionally not implemented + SimpleRcsPanSharpeningFusionImageFilter(Self&); // intentionally not implemented + void operator=(const Self&); // intentionally not implemented - typename ConvolutionFilterType::Pointer m_ConvolutionFilter; - typename DivideFilterType::Pointer m_DivideFilter; - typename MultiplyFilterType::Pointer m_MultiplyFilter; + typename ConvolutionFilterType::Pointer m_ConvolutionFilter; + typename DivideFilterType::Pointer m_DivideFilter; + typename MultiplyFilterType::Pointer m_MultiplyFilter; - RadiusType m_Radius; - ArrayType m_Filter; + RadiusType m_Radius; + ArrayType m_Filter; - }; +}; } // end namespace otb diff --git a/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.txx b/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.txx index a83ad7e2fd0c691da8af87e9f50020d685544134..826b9b66626bc6e9afbbd70c67f63414c175c44d 100644 --- a/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.txx +++ b/Code/Fusion/otbSimpleRcsPanSharpeningFusionImageFilter.txx @@ -26,129 +26,129 @@ namespace otb { - template <class TPanImageType, class TXsImageType, class TOutputImageType> - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::SimpleRcsPanSharpeningFusionImageFilter() - { - this->SetNumberOfRequiredInputs(2); - m_ConvolutionFilter = ConvolutionFilterType::New(); - m_ConvolutionFilter->NormalizeFilterOn(); - m_DivideFilter = DivideFilterType::New(); - m_MultiplyFilter = MultiplyFilterType::New(); +template <class TPanImageType, class TXsImageType, class TOutputImageType> +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::SimpleRcsPanSharpeningFusionImageFilter() +{ + this->SetNumberOfRequiredInputs(2); + m_ConvolutionFilter = ConvolutionFilterType::New(); + m_ConvolutionFilter->NormalizeFilterOn(); + m_DivideFilter = DivideFilterType::New(); + m_MultiplyFilter = MultiplyFilterType::New(); - m_Radius.Fill(3); - m_Filter.SetSize(7*7); - m_Filter.Fill(1); + m_Radius.Fill(3); + m_Filter.SetSize(7*7); + m_Filter.Fill(1); - m_DivideFilter->SetInput2(m_ConvolutionFilter->GetOutput()); - m_MultiplyFilter->SetInput1(m_DivideFilter->GetOutput()); + m_DivideFilter->SetInput2(m_ConvolutionFilter->GetOutput()); + m_MultiplyFilter->SetInput1(m_DivideFilter->GetOutput()); - } +} - template <class TPanImageType, class TXsImageType, class TOutputImageType> - void - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::SetPanInput(const TPanImageType *image) - { +template <class TPanImageType, class TXsImageType, class TOutputImageType> +void +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::SetPanInput(const TPanImageType *image) +{ // We have 2 inputs: an image and a vector image // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(1, - const_cast< TPanImageType* >( image ) ); - this->Modified(); - } - - template <class TPanImageType, class TXsImageType, class TOutputImageType> - const TPanImageType * - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::GetPanInput(void) const + this->itk::ProcessObject::SetNthInput(1, + const_cast< TPanImageType* >( image ) ); + this->Modified(); +} + +template <class TPanImageType, class TXsImageType, class TOutputImageType> +const TPanImageType * +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::GetPanInput(void) const +{ + if (this->GetNumberOfInputs() < 2) { - if (this->GetNumberOfInputs() < 2) - { - return 0; - } - - return static_cast<const TPanImageType * > - (this->itk::ProcessObject::GetInput(1) ); + return 0; } - template <class TPanImageType, class TXsImageType, class TOutputImageType> - void - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::SetXsInput(const TXsImageType *image) - { + return static_cast<const TPanImageType * > + (this->itk::ProcessObject::GetInput(1) ); +} + +template <class TPanImageType, class TXsImageType, class TOutputImageType> +void +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::SetXsInput(const TXsImageType *image) +{ // We have 2 inputs: an image and a vector image // Process object is not const-correct so the const_cast is required here - this->itk::ProcessObject::SetNthInput(0, - const_cast< TXsImageType* >( image ) ); - this->Modified(); + this->itk::ProcessObject::SetNthInput(0, + const_cast< TXsImageType* >( image ) ); + this->Modified(); +} + +template <class TPanImageType, class TXsImageType, class TOutputImageType> +const TXsImageType * +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::GetXsInput(void) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; } - template <class TPanImageType, class TXsImageType, class TOutputImageType> - const TXsImageType * - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::GetXsInput(void) const - { - if (this->GetNumberOfInputs() < 1) - { - return 0; - } + return static_cast<const TXsImageType * > + (this->itk::ProcessObject::GetInput(0) ); +} + + +template <class TPanImageType,class TXsImageType,class TOutputImageType> +void +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::GenerateData() +{ - return static_cast<const TXsImageType * > - (this->itk::ProcessObject::GetInput(0) ); + //Check if size is correct + typename InternalImageType::SizeType sizePan; + typename InternalVectorImageType::SizeType sizeXs; + sizePan = this->GetPanInput()->GetLargestPossibleRegion().GetSize(); + sizeXs = this->GetXsInput()->GetLargestPossibleRegion().GetSize(); + if ((sizePan[0] != sizeXs[0]) || (sizePan[1] != sizeXs[1])) + { + itkExceptionMacro(<<"SimpleRcsPanSharpeningFusionImageFilter: Wrong Pan/Xs size"); } + //Process the fusion + m_ConvolutionFilter->SetInput( this->GetPanInput() ); + m_ConvolutionFilter->SetRadius( this->m_Radius); + m_ConvolutionFilter->SetFilter( this->m_Filter); + + m_DivideFilter->SetInput1(this->GetXsInput()); + + m_MultiplyFilter->SetInput2(this->GetPanInput()); + + m_MultiplyFilter->GraftOutput( this->GetOutput() ); + m_MultiplyFilter->Update(); + this->GraftOutput( m_MultiplyFilter->GetOutput() ); +} + +template <class TPanImageType,class TXsImageType,class TOutputImageType> +void +SimpleRcsPanSharpeningFusionImageFilter +<TPanImageType, TXsImageType, TOutputImageType> +::PrintSelf( std::ostream& os, itk::Indent indent ) const +{ + Superclass::PrintSelf(os,indent); - template <class TPanImageType,class TXsImageType,class TOutputImageType> - void - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::GenerateData() - { - - //Check if size is correct - typename InternalImageType::SizeType sizePan; - typename InternalVectorImageType::SizeType sizeXs; - sizePan = this->GetPanInput()->GetLargestPossibleRegion().GetSize(); - sizeXs = this->GetXsInput()->GetLargestPossibleRegion().GetSize(); - if ((sizePan[0] != sizeXs[0]) || (sizePan[1] != sizeXs[1])) - { - itkExceptionMacro(<<"SimpleRcsPanSharpeningFusionImageFilter: Wrong Pan/Xs size"); - } - - //Process the fusion - m_ConvolutionFilter->SetInput( this->GetPanInput() ); - m_ConvolutionFilter->SetRadius( this->m_Radius); - m_ConvolutionFilter->SetFilter( this->m_Filter); - - m_DivideFilter->SetInput1(this->GetXsInput()); - - m_MultiplyFilter->SetInput2(this->GetPanInput()); - - m_MultiplyFilter->GraftOutput( this->GetOutput() ); - m_MultiplyFilter->Update(); - this->GraftOutput( m_MultiplyFilter->GetOutput() ); - } - - template <class TPanImageType,class TXsImageType,class TOutputImageType> - void - SimpleRcsPanSharpeningFusionImageFilter - <TPanImageType, TXsImageType, TOutputImageType> - ::PrintSelf( std::ostream& os, itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - - os - << indent << "Radius:" << this->m_Radius - << std::endl; - } + os + << indent << "Radius:" << this->m_Radius + << std::endl; +} } // end namespace otb diff --git a/Code/Gui/otbFltkFilterWatcher.cxx b/Code/Gui/otbFltkFilterWatcher.cxx index c42af830406938e5fdeaafba254255f51fd4b008..45d194f2349a06f1bf985e6eeae19f45c8792453 100644 --- a/Code/Gui/otbFltkFilterWatcher.cxx +++ b/Code/Gui/otbFltkFilterWatcher.cxx @@ -25,9 +25,9 @@ namespace otb FltkFilterWatcher ::FltkFilterWatcher(itk::ProcessObject* process, - int x, int y, int w, int h, - const char *comment) - : FilterWatcherBase(process, comment) + int x, int y, int w, int h, + const char *comment) + : FilterWatcherBase(process, comment) { m_Window = new Fl_Window(x,y,w+10,h+10); m_Window->label(m_Comment.c_str()); diff --git a/Code/Gui/otbFltkFilterWatcher.h b/Code/Gui/otbFltkFilterWatcher.h index 74021c7ba8d8c44fe0de44e486f12e5ce7958a9f..13a50a6787b12ecf923434b41a0ed73cb172a979 100644 --- a/Code/Gui/otbFltkFilterWatcher.h +++ b/Code/Gui/otbFltkFilterWatcher.h @@ -35,7 +35,7 @@ namespace otb * on pipeline filtering execution * */ - class ITK_EXPORT FltkFilterWatcher : public FilterWatcherBase +class ITK_EXPORT FltkFilterWatcher : public FilterWatcherBase { public: /** Classes that need access to filter's private data */ @@ -44,8 +44,8 @@ public: /** Constructor. Takes a ProcessObject to monitor and an optional * comment string that is prepended to each event message. */ FltkFilterWatcher(itk::ProcessObject* process, - int x, int y, int w,int h, - const char *comment=""); + int x, int y, int w,int h, + const char *comment=""); /** Destructor. */ virtual ~FltkFilterWatcher(); @@ -63,10 +63,10 @@ protected: virtual void ShowProgress() { if (m_Process) - { - m_Progress->value(m_Process->GetProgress()); - Fl::check(); - } + { + m_Progress->value(m_Process->GetProgress()); + Fl::check(); + } } /** Callback method to show the StartEvent */ diff --git a/Code/Gui/otbFltkWriterWatcher.cxx b/Code/Gui/otbFltkWriterWatcher.cxx index 34c176221d76a5e859cef77efa09b740bdb455f7..d1cd88f21f1887e2b78a7a8bf7d3da54cd017174 100644 --- a/Code/Gui/otbFltkWriterWatcher.cxx +++ b/Code/Gui/otbFltkWriterWatcher.cxx @@ -25,9 +25,9 @@ namespace otb FltkWriterWatcher ::FltkWriterWatcher(itk::ProcessObject* process, - int x, int y, int w, int h, - const char *comment) - : WriterWatcherBase(process, comment) + int x, int y, int w, int h, + const char *comment) + : WriterWatcherBase(process, comment) { this->BuildGUI(x,y,w,h,comment); } @@ -35,10 +35,10 @@ FltkWriterWatcher FltkWriterWatcher ::FltkWriterWatcher(itk::ProcessObject* process, - itk::ProcessObject* source, - int x, int y, int w, int h, - const char *comment) - : WriterWatcherBase(process,source,comment) + itk::ProcessObject* source, + int x, int y, int w, int h, + const char *comment) + : WriterWatcherBase(process,source,comment) { this->BuildGUI(x,y,w,h,comment); } @@ -47,7 +47,7 @@ FltkWriterWatcher void FltkWriterWatcher ::BuildGUI(int x, int y, int w, int h,const char * comment) { - m_Window = new Fl_Window(x,y,w+10,h+15); + m_Window = new Fl_Window(x,y,w+10,h+15); m_Window->label(m_Comment.c_str()); m_Window->begin(); m_FilterProgress = new Fl_Progress(5,5,w,h/2); diff --git a/Code/Gui/otbFltkWriterWatcher.h b/Code/Gui/otbFltkWriterWatcher.h index 112651d47fbd591fdb98dd81f7fd4d080187c439..7765f1645bdbec050b3d76066894cb4d21401cfc 100644 --- a/Code/Gui/otbFltkWriterWatcher.h +++ b/Code/Gui/otbFltkWriterWatcher.h @@ -35,7 +35,7 @@ namespace otb * on pipeline filtering execution * */ - class ITK_EXPORT FltkWriterWatcher : public WriterWatcherBase +class ITK_EXPORT FltkWriterWatcher : public WriterWatcherBase { public: /** Classes that need access to filter's private data */ @@ -44,13 +44,13 @@ public: /** Constructor. Takes a ProcessObject to monitor and an optional * comment string that is prepended to each event message. */ FltkWriterWatcher(itk::ProcessObject* process, - int x, int y, int w,int h, - const char *comment=""); + int x, int y, int w,int h, + const char *comment=""); FltkWriterWatcher(itk::ProcessObject* process, - itk::ProcessObject * source, - int x, int y, int w,int h, - const char *comment=""); + itk::ProcessObject * source, + int x, int y, int w,int h, + const char *comment=""); /** Destructor. */ @@ -72,20 +72,20 @@ protected: virtual void ShowFilterProgress() { if (m_SourceProcess) - { - m_FilterProgress->value(m_SourceProcess->GetProgress()); - Fl::check(); - } + { + m_FilterProgress->value(m_SourceProcess->GetProgress()); + Fl::check(); + } } - /** Callback method to show the ProgressEvent */ + /** Callback method to show the ProgressEvent */ virtual void ShowWriterProgress() { if (m_Process) - { - m_WriterProgress->value(m_Process->GetProgress()); - Fl::check(); - } + { + m_WriterProgress->value(m_Process->GetProgress()); + Fl::check(); + } } /** Callback method to show the StartEvent */ @@ -98,7 +98,7 @@ protected: } - /** Callback method to show the StartEvent */ + /** Callback method to show the StartEvent */ virtual void StartFilter() { m_Window->show(); diff --git a/Code/IO/otbBSQImageIO.cxx b/Code/IO/otbBSQImageIO.cxx index 27c21e89150d37e0d789586f6adeaad250ce7274..6004646c39dcd99fd8572eeb650accb6e21d9e02 100644 --- a/Code/IO/otbBSQImageIO.cxx +++ b/Code/IO/otbBSQImageIO.cxx @@ -33,653 +33,653 @@ namespace otb { - BSQImageIO::BSQImageIO() - { +BSQImageIO::BSQImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); - m_PixelType = SCALAR; - m_ComponentType = UCHAR; - if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) - { - m_ByteOrder = LittleEndian; - } - else - { - m_ByteOrder = BigEndian; - } + this->SetNumberOfDimensions(2); + m_PixelType = SCALAR; + m_ComponentType = UCHAR; + if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) + { + m_ByteOrder = LittleEndian; + } + else + { + m_ByteOrder = BigEndian; + } - m_FileByteOrder = m_ByteOrder; - m_TypeBsq=""; + m_FileByteOrder = m_ByteOrder; + m_TypeBsq=""; // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; - m_ChannelsFile = NULL; - m_FlagWriteImageInformation = true; - } + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; + m_ChannelsFile = NULL; + m_FlagWriteImageInformation = true; +} - BSQImageIO::~BSQImageIO() +BSQImageIO::~BSQImageIO() +{ + if ( m_HeaderFile.is_open() ) { - if( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } - if( m_ChannelsFile != NULL) + m_HeaderFile.close(); + } + if ( m_ChannelsFile != NULL) + { + for (unsigned int numComponent = 0; numComponent<this->GetNumberOfComponents(); numComponent++) { - for(unsigned int numComponent = 0; numComponent<this->GetNumberOfComponents(); numComponent++) + if ( m_ChannelsFile[numComponent].is_open() ) { - if( m_ChannelsFile[numComponent].is_open() ) - { - m_ChannelsFile[numComponent].close(); - } + m_ChannelsFile[numComponent].close(); } - delete [] m_ChannelsFile; } + delete [] m_ChannelsFile; } +} - bool BSQImageIO::CanReadFile( const char* filename ) +bool BSQImageIO::CanReadFile( const char* filename ) +{ + std::fstream header_file; + std::string lFileName(filename); + std::string extension = System::GetExtension(filename); + if ((extension!="HD")&&(extension!="hd")) { - std::fstream header_file; - std::string lFileName(filename); - std::string extension = System::GetExtension(filename); - if ((extension!="HD")&&(extension!="hd")) - { - return false; - } - if( System::IsADirName(lFileName) == true ) - { - return false; - } - if( System::SetToLower(System::GetExtension(lFileName)) != "hd" ) - { - return false; - } - - header_file.open( lFileName.c_str(), std::ios::in ); - if( header_file.fail() ) - { - otbMsgDevMacro(<<"BSQImageIO::CanReadFile() failed header open ! " ); - return false; - } - //Read header informations - bool lResult = InternalReadHeaderInformation(lFileName, header_file,false); - header_file.close(); - return (lResult); + return false; } - - -// Used to print information about this object - void BSQImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const + if ( System::IsADirName(lFileName) == true ) { - Superclass::PrintSelf(os, indent); + return false; } - -// Read a 3D image (or event more bands)... not implemented yet - void BSQImageIO::ReadVolume(void*) + if ( System::SetToLower(System::GetExtension(lFileName)) != "hd" ) { + return false; } -// Read image - void BSQImageIO::Read(void* buffer) + header_file.open( lFileName.c_str(), std::ios::in ); + if ( header_file.fail() ) { - unsigned long step = this->GetNumberOfComponents(); - char * p = static_cast<char *>(buffer); - - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + otbMsgDevMacro(<<"BSQImageIO::CanReadFile() failed header open ! " ); + return false; + } + //Read header informations + bool lResult = InternalReadHeaderInformation(lFileName, header_file,false); + header_file.close(); + return (lResult); +} - otbMsgDevMacro( <<" BSQImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - std::streamoff headerLength(0); - std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); - std::streamoff offset; - std::streamsize numberOfBytesToBeRead = this->GetComponentSize() * lNbColumns; - std::streamsize numberOfBytesRead; - unsigned long cpt = 0; +// Used to print information about this object +void BSQImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} - // Update the step variable - step = step * (unsigned long)(this->GetComponentSize()); +// Read a 3D image (or event more bands)... not implemented yet +void BSQImageIO::ReadVolume(void*) +{ +} - char * value = new char[numberOfBytesToBeRead]; - if(value==NULL) - { - itkExceptionMacro(<<"BSQImageIO::Read(): Bad alloc"); - return; - } +// Read image +void BSQImageIO::Read(void* buffer) +{ + unsigned long step = this->GetNumberOfComponents(); + char * p = static_cast<char *>(buffer); + + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + + otbMsgDevMacro( <<" BSQImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + + std::streamoff headerLength(0); + std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); + std::streamoff offset; + std::streamsize numberOfBytesToBeRead = this->GetComponentSize() * lNbColumns; + std::streamsize numberOfBytesRead; + unsigned long cpt = 0; + + // Update the step variable + step = step * (unsigned long)(this->GetComponentSize()); + + char * value = new char[numberOfBytesToBeRead]; + if (value==NULL) + { + itkExceptionMacro(<<"BSQImageIO::Read(): Bad alloc"); + return; + } - otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); - otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); - otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); - otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); - otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); - otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); + otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); + otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); + otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); + otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); + otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); + otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); - for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) - { - cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()); - //Read region of the channel - for(int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); - m_ChannelsFile[nbComponents].seekg(offset, std::ios::beg); - //Read a line - m_ChannelsFile[nbComponents].read( static_cast<char *>( value ), numberOfBytesToBeRead ); - numberOfBytesRead = m_ChannelsFile[nbComponents].gcount(); + for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) + { + cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()); + //Read region of the channel + for (int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); + m_ChannelsFile[nbComponents].seekg(offset, std::ios::beg); + //Read a line + m_ChannelsFile[nbComponents].read( static_cast<char *>( value ), numberOfBytesToBeRead ); + numberOfBytesRead = m_ChannelsFile[nbComponents].gcount(); #ifdef __APPLE_CC__ - // fail() is broken in the Mac. It returns true when reaches eof(). - if ( numberOfBytesRead != numberOfBytesToBeRead ) + // fail() is broken in the Mac. It returns true when reaches eof(). + if ( numberOfBytesRead != numberOfBytesToBeRead ) #else - if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_ChannelsFile[nbComponents].fail() ) + if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_ChannelsFile[nbComponents].fail() ) #endif - { - itkExceptionMacro(<<"BSQImageIO::Read() Can Read the specified Region"); // read failed - } + { + itkExceptionMacro(<<"BSQImageIO::Read() Can Read the specified Region"); // read failed + } // cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()) + numberOfBytesToBeRead * this->GetNumberOfComponents() * LineNo; // cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()) + numberOfBytesToBeRead * this->GetNumberOfComponents(); - for ( std::streamsize i=0; i < numberOfBytesToBeRead; i = i+static_cast<std::streamsize>(this->GetComponentSize()) ) - { - memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(this->GetComponentSize())); - cpt += step; - } + for ( std::streamsize i=0; i < numberOfBytesToBeRead; i = i+static_cast<std::streamsize>(this->GetComponentSize()) ) + { + memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(this->GetComponentSize())); + cpt += step; } } - unsigned long numberOfPixelsOfRegion = lNbLines * lNbColumns * this->GetNumberOfComponents(); - - delete [] value; - - // Swap bytes if necessary - if ( 0 ) {} - otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsOfRegion ) - else - { - itkExceptionMacro(<<"BSQImageIO::Read() undefined component type! " ); - } } + unsigned long numberOfPixelsOfRegion = lNbLines * lNbColumns * this->GetNumberOfComponents(); + + delete [] value; + + // Swap bytes if necessary + if ( 0 ) {} + otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsOfRegion ) + else + { + itkExceptionMacro(<<"BSQImageIO::Read() undefined component type! " ); + } +} - void BSQImageIO::ReadImageInformation() +void BSQImageIO::ReadImageInformation() +{ + if ( m_HeaderFile.is_open() ) { - if( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } - m_HeaderFile.open( m_FileName.c_str(), std::ios::in ); - if( m_HeaderFile.fail() ) - { - itkExceptionMacro(<<"BSQImageIO::ReadImageInformation() failed header open ! " ); - } + m_HeaderFile.close(); + } + m_HeaderFile.open( m_FileName.c_str(), std::ios::in ); + if ( m_HeaderFile.fail() ) + { + itkExceptionMacro(<<"BSQImageIO::ReadImageInformation() failed header open ! " ); + } - //Read header informations - InternalReadHeaderInformation(m_FileName, m_HeaderFile,true); + //Read header informations + InternalReadHeaderInformation(m_FileName, m_HeaderFile,true); - otbMsgDebugMacro( <<"Driver to read: BSQ"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to read: BSQ"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} - bool BSQImageIO::InternalReadHeaderInformation(const std::string & file_name, std::fstream & file, const bool reportError) - { +bool BSQImageIO::InternalReadHeaderInformation(const std::string & file_name, std::fstream & file, const bool reportError) +{ - std::string lString; - std::string lStrCodePix; - //Read TYPE information - file >> lString; - lString = System::SetToUpper(lString); - if( lString != "TYPE" ) + std::string lString; + std::string lStrCodePix; + //Read TYPE information + file >> lString; + lString = System::SetToUpper(lString); + if ( lString != "TYPE" ) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : the first line of the header file must be contains 'TYPE' caracters."); - } - else - { - return false; - } + itkExceptionMacro(<< "BSQ : the first line of the header file must be contains 'TYPE' caracters."); } - file >> lStrCodePix; - lStrCodePix = System::SetToUpper(lStrCodePix); - if(lStrCodePix == "OCT") + else { - SetComponentType(CHAR); + return false; } - else if(lStrCodePix == "UOCT") + } + file >> lStrCodePix; + lStrCodePix = System::SetToUpper(lStrCodePix); + if (lStrCodePix == "OCT") + { + SetComponentType(CHAR); + } + else if (lStrCodePix == "UOCT") + { + SetComponentType(UCHAR); + } + else if (lStrCodePix == "I2") + { + SetComponentType(SHORT); + } + else if (lStrCodePix == "UI2") + { + SetComponentType(USHORT); + } + else if (lStrCodePix == "I4") + { + SetComponentType(INT); + } + else if (lStrCodePix == "UI4") + { + SetComponentType(UINT); + } + else if (lStrCodePix == "R4") + { + SetComponentType(FLOAT); + } + else if (lStrCodePix == "R8") + { + SetComponentType(DOUBLE); + } + else + { + if ( reportError == true ) { - SetComponentType(UCHAR); + itkExceptionMacro(<< "BSQ : the value type '"<<lStrCodePix<<"' (second line) set in the header file is not reconized as correct value."); } - else if(lStrCodePix == "I2") + else { - SetComponentType(SHORT); + return false; } - else if(lStrCodePix == "UI2") + } + //Read LABEL information + file >> lString; + lString = System::SetToUpper(lString); + if ( lString != "LABEL" ) + { + if ( reportError == true ) { - SetComponentType(USHORT); + itkExceptionMacro(<< "BSQ : the third line of the header file must be contains 'LABEL' caracters."); } - else if(lStrCodePix == "I4") + else { - SetComponentType(INT); + return false; } - else if(lStrCodePix == "UI4") + } + while ( (lString != "CHANNELS") || (file.eof())) + { + file >> lString; + lString = System::SetToUpper(lString); + } + if ( lString != "CHANNELS" ) + { + if ( reportError == true ) { - SetComponentType(UINT); + itkExceptionMacro(<< "BSQ : 'CHANNELS' keyword is not find in the header file."); } - else if(lStrCodePix == "R4") + else { - SetComponentType(FLOAT); + return false; } - else if(lStrCodePix == "R8") + } + unsigned int lNbChannels; + file >> lNbChannels; + this->SetNumberOfComponents( lNbChannels ); + + //Read LINES information + file >> lString; + lString = System::SetToUpper(lString); + if ( lString != "LINES" ) + { + if ( reportError == true ) { - SetComponentType(DOUBLE); + itkExceptionMacro(<< "BSQ : 'LINES' keyword is not find in the header file."); } else { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : the value type '"<<lStrCodePix<<"' (second line) set in the header file is not reconized as correct value."); - } - else - { - return false; - } + return false; } - //Read LABEL information - file >> lString; - lString = System::SetToUpper(lString); - if( lString != "LABEL" ) + } + file >> m_Dimensions[1]; + //Read COLUMNS information + file >> lString; + lString = System::SetToUpper(lString); + if ( lString != "COLUMNS" ) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : the third line of the header file must be contains 'LABEL' caracters."); - } - else - { - return false; - } + itkExceptionMacro(<< "BSQ : 'COLUMNS' keyword is not find in the header file."); } - while( (lString != "CHANNELS") || (file.eof())) + else { - file >> lString; - lString = System::SetToUpper(lString); + return false; } - if( lString != "CHANNELS" ) + } + file >> m_Dimensions[0]; + + //Read "BITS PER PIXEL" informations + file >> lString; + std::string lStrBitsPerPixels(lString); + file >> lString; + lStrBitsPerPixels = lStrBitsPerPixels + " " + lString; + file >> lString; + lStrBitsPerPixels = lStrBitsPerPixels + " " + lString; + lStrBitsPerPixels = System::SetToUpper(lStrBitsPerPixels); + if ( lStrBitsPerPixels != "BITS PER PIXEL" ) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : 'CHANNELS' keyword is not find in the header file."); - } - else - { - return false; - } + itkExceptionMacro(<< "BSQ : 'BITS PER PIXEL' keyword is not find in the header file."); } - unsigned int lNbChannels; - file >> lNbChannels; - this->SetNumberOfComponents( lNbChannels ); - - //Read LINES information - file >> lString; - lString = System::SetToUpper(lString); - if( lString != "LINES" ) + else { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : 'LINES' keyword is not find in the header file."); - } - else - { - return false; - } + return false; } - file >> m_Dimensions[1]; - //Read COLUMNS information - file >> lString; + } + int lNbBitsPerPixels; + file >> lNbBitsPerPixels; + + //Read "SENSCODAGE" informations (optionnal) + file >> lString; + if ( lString.empty() == false) + { lString = System::SetToUpper(lString); - if( lString != "COLUMNS" ) + if ( lString == "SENSCODAGE" ) { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : 'COLUMNS' keyword is not find in the header file."); - } - else + file >> lString; + lString = System::SetToUpper(lString); + if ( lString == "INTEL" ) { - return false; + m_FileByteOrder = LittleEndian; } - } - file >> m_Dimensions[0]; - - //Read "BITS PER PIXEL" informations - file >> lString; - std::string lStrBitsPerPixels(lString); - file >> lString; - lStrBitsPerPixels = lStrBitsPerPixels + " " + lString; - file >> lString; - lStrBitsPerPixels = lStrBitsPerPixels + " " + lString; - lStrBitsPerPixels = System::SetToUpper(lStrBitsPerPixels); - if( lStrBitsPerPixels != "BITS PER PIXEL" ) - { - if( reportError == true ) + else if ( lString == "IEEE" ) { - itkExceptionMacro(<< "BSQ : 'BITS PER PIXEL' keyword is not find in the header file."); + m_FileByteOrder = BigEndian; } else { - return false; - } - } - int lNbBitsPerPixels; - file >> lNbBitsPerPixels; - - //Read "SENSCODAGE" informations (optionnal) - file >> lString; - if( lString.empty() == false) - { - lString = System::SetToUpper(lString); - if( lString == "SENSCODAGE" ) - { - file >> lString; - lString = System::SetToUpper(lString); - if( lString == "INTEL" ) + if ( reportError == true ) { - m_FileByteOrder = LittleEndian; - } - else if( lString == "IEEE" ) - { - m_FileByteOrder = BigEndian; + itkExceptionMacro(<< "BSQ : the value SENSCODAGE '"<<lString<<"' set in the header file is not reconized as correct value. Possible values are INTEL or IEEE"); } else { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : the value SENSCODAGE '"<<lString<<"' set in the header file is not reconized as correct value. Possible values are INTEL or IEEE"); - } - else - { - return false; - } + return false; } } } - file.close(); + } + file.close(); - //Define channels file name - std::string lRootName = System::GetRootName( file_name ); - m_ChannelsFileName.clear(); - for(unsigned int i=0; i<this->GetNumberOfComponents(); i++) - { - ::itk::OStringStream lStream; - lStream << lRootName << ".c" << i+1; - m_ChannelsFileName.push_back(lStream.str()); - } + //Define channels file name + std::string lRootName = System::GetRootName( file_name ); + m_ChannelsFileName.clear(); + for (unsigned int i=0; i<this->GetNumberOfComponents(); i++) + { + ::itk::OStringStream lStream; + lStream << lRootName << ".c" << i+1; + m_ChannelsFileName.push_back(lStream.str()); + } - m_ChannelsFile = new std::fstream[this->GetNumberOfComponents() ]; + m_ChannelsFile = new std::fstream[this->GetNumberOfComponents() ]; - //Try to open channels file - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + //Try to open channels file + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { + m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::in | std::ios::binary ); + if ( m_ChannelsFile[channels].fail() ) { - m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::in | std::ios::binary ); - if( m_ChannelsFile[channels].fail() ) + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "BSQ : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); - } - else - { - return false; - } + itkExceptionMacro(<< "BSQ : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); + } + else + { + return false; } } - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); - - return(true); } + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); + + return(true); +} - bool BSQImageIO::CanWriteFile( const char* filename ) +bool BSQImageIO::CanWriteFile( const char* filename ) +{ + std::string lFileName(filename); + std::string extension = System::GetExtension(filename); + if ((extension!="HD")&&(extension!="hd")) { - std::string lFileName(filename); - std::string extension = System::GetExtension(filename); - if ((extension!="HD")&&(extension!="hd")) - { - return false; - } - if( System::IsADirName(lFileName) == true ) - { - return false; - } - const std::string Extension = System::GetExtension(filename); - if( (Extension == "hd") || (Extension == "HD") ) - { - return true; - } - else - { - return false; - } + return false; + } + if ( System::IsADirName(lFileName) == true ) + { + return false; + } + const std::string Extension = System::GetExtension(filename); + if ( (Extension == "hd") || (Extension == "HD") ) + { + return true; + } + else + { + return false; } +} - void BSQImageIO::Write(const void* buffer) +void BSQImageIO::Write(const void* buffer) +{ + if ( m_FlagWriteImageInformation == true ) { - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } - unsigned long step = this->GetNumberOfComponents(); - unsigned int lNbLines = this->GetIORegion().GetSize()[1]; - unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + unsigned long step = this->GetNumberOfComponents(); + unsigned int lNbLines = this->GetIORegion().GetSize()[1]; + unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] // Cas particuliers : on controle que si la r�gion � �crire est de la m�me dimension que l'image enti�re, // on commence l'offset � 0 (lorsque que l'on est pas en "Streaming") - if( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) - { - otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); - lFirstLine = 0; - lFirstColumn = 0; - } + if ( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) + { + otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); + lFirstLine = 0; + lFirstColumn = 0; + } - otbMsgDevMacro( <<" BSQImageIO::Write() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); + otbMsgDevMacro( <<" BSQImageIO::Write() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); - std::streamoff headerLength(0); - std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); - std::streamsize numberOfBytesToBeWrite = static_cast<std::streamsize>(this->GetComponentSize() * lNbColumns); - std::streamoff offset = 0; - unsigned long cpt = 0; + std::streamoff headerLength(0); + std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); + std::streamsize numberOfBytesToBeWrite = static_cast<std::streamsize>(this->GetComponentSize() * lNbColumns); + std::streamoff offset = 0; + unsigned long cpt = 0; - // Update the step variable - step = step * (unsigned long)(this->GetComponentSize()); - const char * p = static_cast<const char *>(buffer); + // Update the step variable + step = step * (unsigned long)(this->GetComponentSize()); + const char * p = static_cast<const char *>(buffer); - char* value = new char[numberOfBytesToBeWrite]; - if(value==NULL) - { - itkExceptionMacro(<<"Erreur allocation meoire"); - return; - } + char* value = new char[numberOfBytesToBeWrite]; + if (value==NULL) + { + itkExceptionMacro(<<"Erreur allocation meoire"); + return; + } - for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) + for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) + { + cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()); + //Read region of the channel + for (unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) { - cpt = (unsigned long )(nbComponents)* (unsigned long)(this->GetComponentSize()); - //Read region of the channel - for(unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + for ( std::streamsize i=0; i < numberOfBytesToBeWrite; i = i+static_cast<std::streamsize>(this->GetComponentSize()) ) { - for ( std::streamsize i=0; i < numberOfBytesToBeWrite; i = i+static_cast<std::streamsize>(this->GetComponentSize()) ) - { - memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(this->GetComponentSize())); - cpt += step; - } - - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); - m_ChannelsFile[nbComponents].seekp(offset, std::ios::beg); - //Write a line - m_ChannelsFile[nbComponents].write( static_cast<char *>( value ), numberOfBytesToBeWrite ); + memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(this->GetComponentSize())); + cpt += step; } + + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); + m_ChannelsFile[nbComponents].seekp(offset, std::ios::beg); + //Write a line + m_ChannelsFile[nbComponents].write( static_cast<char *>( value ), numberOfBytesToBeWrite ); } - delete [] value; } + delete [] value; +} - void BSQImageIO::WriteImageInformation() +void BSQImageIO::WriteImageInformation() +{ + if ( m_FileName == "" ) { - if ( m_FileName == "" ) - { - itkExceptionMacro(<<"A FileName must be specified."); - } - if( CanWriteFile(m_FileName.c_str()) == false) - { - itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a BSQ file"); - } - // Close file from any previous image - if ( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } + itkExceptionMacro(<<"A FileName must be specified."); + } + if ( CanWriteFile(m_FileName.c_str()) == false) + { + itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a BSQ file"); + } + // Close file from any previous image + if ( m_HeaderFile.is_open() ) + { + m_HeaderFile.close(); + } - // Open the new file for writing - // Actually open the file - m_HeaderFile.open( m_FileName.c_str(), std::ios::out | std::ios::trunc ); - if( m_HeaderFile.fail() ) - { - itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); - } + // Open the new file for writing + // Actually open the file + m_HeaderFile.open( m_FileName.c_str(), std::ios::out | std::ios::trunc ); + if ( m_HeaderFile.fail() ) + { + itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); + } - if( 0 ) {} - otbSetTypeBsqMacro( CHAR, "OCT") - otbSetTypeBsqMacro( UCHAR, "UOCT") - otbSetTypeBsqMacro( SHORT, "I2") - otbSetTypeBsqMacro( USHORT, "UI2") - otbSetTypeBsqMacro( INT, "I4") - otbSetTypeBsqMacro( UINT, "UI4") - otbSetTypeBsqMacro( FLOAT, "R4") - otbSetTypeBsqMacro( DOUBLE, "R8") - else - { - itkExceptionMacro(<< "BSQ format doesn't reconized (TYPE)."); - } + if ( 0 ) {} + otbSetTypeBsqMacro( CHAR, "OCT") + otbSetTypeBsqMacro( UCHAR, "UOCT") + otbSetTypeBsqMacro( SHORT, "I2") + otbSetTypeBsqMacro( USHORT, "UI2") + otbSetTypeBsqMacro( INT, "I4") + otbSetTypeBsqMacro( UINT, "UI4") + otbSetTypeBsqMacro( FLOAT, "R4") + otbSetTypeBsqMacro( DOUBLE, "R8") + else + { + itkExceptionMacro(<< "BSQ format doesn't reconized (TYPE)."); + } - std::string lString; - //Write TYPE information - m_HeaderFile << "TYPE" << std::endl; - m_HeaderFile << m_TypeBsq << std::endl; + std::string lString; + //Write TYPE information + m_HeaderFile << "TYPE" << std::endl; + m_HeaderFile << m_TypeBsq << std::endl; - //Write LABEL information - m_HeaderFile << "LABEL" << std::endl; - m_HeaderFile << m_TypeBsq << " - This BSQ image file was producted by OTB software." << std::endl; + //Write LABEL information + m_HeaderFile << "LABEL" << std::endl; + m_HeaderFile << m_TypeBsq << " - This BSQ image file was producted by OTB software." << std::endl; - //Write CHANNELS information - m_HeaderFile << "CHANNELS" << std::endl; - m_HeaderFile <<this->GetNumberOfComponents() << std::endl; + //Write CHANNELS information + m_HeaderFile << "CHANNELS" << std::endl; + m_HeaderFile <<this->GetNumberOfComponents() << std::endl; - //Write LINES information - m_HeaderFile << "LINES" << std::endl; - m_HeaderFile << m_Dimensions[1] << std::endl; - //Write COLUMNS information - m_HeaderFile << "COLUMNS" << std::endl; - m_HeaderFile << m_Dimensions[0] << std::endl; + //Write LINES information + m_HeaderFile << "LINES" << std::endl; + m_HeaderFile << m_Dimensions[1] << std::endl; + //Write COLUMNS information + m_HeaderFile << "COLUMNS" << std::endl; + m_HeaderFile << m_Dimensions[0] << std::endl; - //Write "BITS PER PIXEL" informations - m_HeaderFile << "BITS PER PIXEL" << std::endl; - m_HeaderFile << this->GetComponentSize()*8 << std::endl; + //Write "BITS PER PIXEL" informations + m_HeaderFile << "BITS PER PIXEL" << std::endl; + m_HeaderFile << this->GetComponentSize()*8 << std::endl; - //Write "SENSCODAGE" informations - m_HeaderFile << "SENSCODAGE" << std::endl; - if( m_ByteOrder == LittleEndian ) - { - m_HeaderFile << "INTEL" << std::endl; - } - else - { - m_HeaderFile << "IEEE" << std::endl; - } + //Write "SENSCODAGE" informations + m_HeaderFile << "SENSCODAGE" << std::endl; + if ( m_ByteOrder == LittleEndian ) + { + m_HeaderFile << "INTEL" << std::endl; + } + else + { + m_HeaderFile << "IEEE" << std::endl; + } - m_HeaderFile.close(); + m_HeaderFile.close(); - //Create channels files + //Create channels files - //Define channels file name - std::string lRootName = System::GetRootName( m_FileName ); - m_ChannelsFileName.clear(); - for(unsigned int i=0; i<this->GetNumberOfComponents(); i++) - { - ::itk::OStringStream lStream; - lStream << lRootName << ".c" << i+1; - m_ChannelsFileName.push_back(lStream.str()); - } + //Define channels file name + std::string lRootName = System::GetRootName( m_FileName ); + m_ChannelsFileName.clear(); + for (unsigned int i=0; i<this->GetNumberOfComponents(); i++) + { + ::itk::OStringStream lStream; + lStream << lRootName << ".c" << i+1; + m_ChannelsFileName.push_back(lStream.str()); + } - //Allocate buffer of stream file - m_ChannelsFile = new std::fstream[this->GetNumberOfComponents() ]; + //Allocate buffer of stream file + m_ChannelsFile = new std::fstream[this->GetNumberOfComponents() ]; - //Try to open channels file - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + //Try to open channels file + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { + m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); + if ( m_ChannelsFile[channels].fail() ) { - m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); - if( m_ChannelsFile[channels].fail() ) - { - itkExceptionMacro(<< "BSQ : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); - } + itkExceptionMacro(<< "BSQ : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); } - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); + } + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); - unsigned long headerLength = this->GetComponentSize() * m_Dimensions[0]; - char* value = new char[headerLength]; + unsigned long headerLength = this->GetComponentSize() * m_Dimensions[0]; + char* value = new char[headerLength]; - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { + m_ChannelsFile[channels].seekp(0, std::ios::beg ); + //Write Header line and all file (whitout information) + for (unsigned int numLigne=0; numLigne<(m_Dimensions[1]); numLigne++) { - m_ChannelsFile[channels].seekp(0, std::ios::beg ); - //Write Header line and all file (whitout information) - for(unsigned int numLigne=0; numLigne<(m_Dimensions[1]); numLigne++) - { - m_ChannelsFile[channels].write(value,headerLength); - } + m_ChannelsFile[channels].write(value,headerLength); } + } - delete [] value; + delete [] value; - otbMsgDebugMacro( <<"Driver to write: BSQ"); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" Type Bsq : "<<m_TypeBsq); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to write: BSQ"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" Type Bsq : "<<m_TypeBsq); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} } // end namespace otb diff --git a/Code/IO/otbBSQImageIO.h b/Code/IO/otbBSQImageIO.h index 76ad3cfdd237992fde7fa213e0d74daf0c85e974..1709dfb6556e3bc2f40d51ba8d2f891ddd9637da 100644 --- a/Code/IO/otbBSQImageIO.h +++ b/Code/IO/otbBSQImageIO.h @@ -61,7 +61,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -79,7 +82,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ diff --git a/Code/IO/otbDEMHandler.cxx b/Code/IO/otbDEMHandler.cxx index 4754a216d7bc78f24a55b8b57268efa183d4ec64..8fe5ace4e1eafd4150238f5913c1e43f11fc6c7a 100644 --- a/Code/IO/otbDEMHandler.cxx +++ b/Code/IO/otbDEMHandler.cxx @@ -22,62 +22,62 @@ namespace otb { - DEMHandler - ::DEMHandler() - { - m_ElevManager=ossimElevManager::instance(); - } - +DEMHandler +::DEMHandler() +{ + m_ElevManager=ossimElevManager::instance(); +} - DEMHandler - ::~DEMHandler() - { - // not needed, m_ElevManager created with instance() method - // delete m_ElevManager; - } +DEMHandler +::~DEMHandler() +{ + // not needed, m_ElevManager created with instance() method + // delete m_ElevManager; +} - void - DEMHandler - ::OpenDEMDirectory(const char* DEMDirectory) - { - m_Mutex.Lock(); - ossimFilename ossimDEMDir; - ossimDEMDir=ossimFilename(DEMDirectory); - ossimDirectory od(DEMDirectory); - if (!m_ElevManager->loadElevationPath(ossimDEMDir)) - { - m_Mutex.Unlock(); - itkExceptionMacro("Failed to open DEM Directory: "<<ossimDEMDir); - } +void +DEMHandler +::OpenDEMDirectory(const char* DEMDirectory) +{ + m_Mutex.Lock(); + ossimFilename ossimDEMDir; + ossimDEMDir=ossimFilename(DEMDirectory); + ossimDirectory od(DEMDirectory); + if (!m_ElevManager->loadElevationPath(ossimDEMDir)) + { m_Mutex.Unlock(); + itkExceptionMacro("Failed to open DEM Directory: "<<ossimDEMDir); } + m_Mutex.Unlock(); +} - double - DEMHandler - ::GetHeightAboveMSL(const PointType& geoPoint) - { - double height; - ossimGpt ossimWorldPoint; - ossimWorldPoint.lon=geoPoint[0]; - ossimWorldPoint.lat=geoPoint[1]; - m_Mutex.Lock(); - height=m_ElevManager->getHeightAboveMSL(ossimWorldPoint); - m_Mutex.Unlock(); - return height; - } + +double +DEMHandler +::GetHeightAboveMSL(const PointType& geoPoint) +{ + double height; + ossimGpt ossimWorldPoint; + ossimWorldPoint.lon=geoPoint[0]; + ossimWorldPoint.lat=geoPoint[1]; + m_Mutex.Lock(); + height=m_ElevManager->getHeightAboveMSL(ossimWorldPoint); + m_Mutex.Unlock(); + return height; +} - void - DEMHandler - ::PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "DEMHandler" << std::endl; - } +void +DEMHandler +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "DEMHandler" << std::endl; +} } // namespace otb diff --git a/Code/IO/otbDEMHandler.h b/Code/IO/otbDEMHandler.h index 50ffda478addf46dddcdc6414a08a2451bf26c64..6009bafa6decc5a2e517efee357ced2a4157a672 100644 --- a/Code/IO/otbDEMHandler.h +++ b/Code/IO/otbDEMHandler.h @@ -32,52 +32,52 @@ namespace otb { - /** \class DEMHandler - * - * \brief Class for Reading a DEM data - * - * This class is based on ossimElevManager. - * It allows to obtain height above MSL(Mean Sea Level) of a geographic point - * Handle DTED and SRTM formats. - * \ingroup Images - * - */ - - class ITK_EXPORT DEMHandler: public itk::Object - { - public : +/** \class DEMHandler + * + * \brief Class for Reading a DEM data + * + * This class is based on ossimElevManager. + * It allows to obtain height above MSL(Mean Sea Level) of a geographic point + * Handle DTED and SRTM formats. + * \ingroup Images + * + */ + +class ITK_EXPORT DEMHandler: public itk::Object +{ +public : /** Standard class typedefs. */ typedef itk::Indent Indent; - typedef DEMHandler Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + typedef DEMHandler Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::Point<double, 2> PointType; + typedef itk::Point<double, 2> PointType; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(DEMHandler,Object); + /** Run-time type information (and related methods). */ + itkTypeMacro(DEMHandler,Object); - /** Try to open the DEM directory. */ - virtual void OpenDEMDirectory(const char* DEMDirectory); + /** Try to open the DEM directory. */ + virtual void OpenDEMDirectory(const char* DEMDirectory); - /** Compute the height above MSL(Mean Sea Level) of a geographic point. */ - virtual double GetHeightAboveMSL(const PointType& geoPoint); + /** Compute the height above MSL(Mean Sea Level) of a geographic point. */ + virtual double GetHeightAboveMSL(const PointType& geoPoint); - protected: - DEMHandler(); - ~DEMHandler(); +protected: + DEMHandler(); + ~DEMHandler(); - void PrintSelf(std::ostream& os, Indent indent) const; + void PrintSelf(std::ostream& os, Indent indent) const; - ossimElevManager* m_ElevManager; + ossimElevManager* m_ElevManager; - itk::SimpleFastMutexLock m_Mutex; + itk::SimpleFastMutexLock m_Mutex; - }; +}; } // namespace otb diff --git a/Code/IO/otbDEMToImageGenerator.h b/Code/IO/otbDEMToImageGenerator.h index a5508cb9923e5f6ab710d8ab38cf2850a38587c5..6f7ae1db0e8aab00f4ccc683ca17af5fa77d7f60 100644 --- a/Code/IO/otbDEMToImageGenerator.h +++ b/Code/IO/otbDEMToImageGenerator.h @@ -32,90 +32,90 @@ namespace otb { - /** \class DEMToImageGenerator - * - * \brief Class for Reading a DEM data - * - * This class is based on ossimElevManager. It takes in input the UL and LR geographic coordinates and the spacing. - * Handle DTED and SRTM formats. - * - * \ingroup Images - * - * - * \example IO/DEMToImageGenerator.cxx - * - */ - template <class TDEMImage> - class ITK_EXPORT DEMToImageGenerator: +/** \class DEMToImageGenerator + * + * \brief Class for Reading a DEM data + * + * This class is based on ossimElevManager. It takes in input the UL and LR geographic coordinates and the spacing. + * Handle DTED and SRTM formats. + * + * \ingroup Images + * + * + * \example IO/DEMToImageGenerator.cxx + * + */ +template <class TDEMImage> +class ITK_EXPORT DEMToImageGenerator: public itk::ImageSource<TDEMImage> - { - public : +{ +public : /** Standard class typedefs. */ typedef itk::Indent Indent; - typedef TDEMImage DEMImageType; - typedef typename DEMImageType::Pointer DEMImagePointerType; - typedef typename DEMImageType::PixelType PixelType; - - typedef DEMToImageGenerator Self; - typedef itk::ImageSource<DEMImageType> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef Image<PixelType,2> OutputImageType; - - typedef typename Superclass::Pointer OutputImagePointer; - typedef typename OutputImageType::SpacingType SpacingType; - typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::PointType PointType; - typedef typename OutputImageType::IndexType IndexType; - typedef typename Superclass::OutputImageRegionType OutputImageRegionType; - typedef itk::ImageRegionIteratorWithIndex< DEMImageType > ImageIteratorType; - - typedef otb::DEMHandler DEMHandlerType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(DEMToImageGenerator,ImageSource); - - /** Set/Get the Output Origin coordinates. */ - itkSetMacro(OutputOrigin,PointType); - itkGetConstReferenceMacro(OutputOrigin,PointType); - - /** Set/Get the Output Size. */ - itkSetMacro(OutputSize,SizeType); - itkGetConstReferenceMacro(OutputSize,SizeType); - - /** Set/Get the Output Spacing. */ - itkSetMacro(OutputSpacing,SpacingType); - itkGetConstReferenceMacro(OutputSpacing,SpacingType); - - /** Set/Get the Default Unknown Value. */ - itkSetMacro(DefaultUnknownValue,PixelType); - itkGetConstReferenceMacro(DefaultUnknownValue,PixelType); - - /** Set the DEM directory. */ - virtual void SetDEMDirectoryPath(const char* DEMDirectory); - - - protected: - DEMToImageGenerator(); - ~DEMToImageGenerator(); - - void PrintSelf(std::ostream& os, Indent indent) const; - void GenerateData(); - virtual void GenerateOutputInformation(); - - DEMHandlerType::Pointer m_DEMHandler; - PointType m_OutputOrigin; - SpacingType m_OutputSpacing; - SizeType m_OutputSize; - PixelType m_DefaultUnknownValue; - - private: - DEMToImageGenerator(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; + typedef TDEMImage DEMImageType; + typedef typename DEMImageType::Pointer DEMImagePointerType; + typedef typename DEMImageType::PixelType PixelType; + + typedef DEMToImageGenerator Self; + typedef itk::ImageSource<DEMImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef Image<PixelType,2> OutputImageType; + + typedef typename Superclass::Pointer OutputImagePointer; + typedef typename OutputImageType::SpacingType SpacingType; + typedef typename OutputImageType::SizeType SizeType; + typedef typename OutputImageType::PointType PointType; + typedef typename OutputImageType::IndexType IndexType; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef itk::ImageRegionIteratorWithIndex< DEMImageType > ImageIteratorType; + + typedef otb::DEMHandler DEMHandlerType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(DEMToImageGenerator,ImageSource); + + /** Set/Get the Output Origin coordinates. */ + itkSetMacro(OutputOrigin,PointType); + itkGetConstReferenceMacro(OutputOrigin,PointType); + + /** Set/Get the Output Size. */ + itkSetMacro(OutputSize,SizeType); + itkGetConstReferenceMacro(OutputSize,SizeType); + + /** Set/Get the Output Spacing. */ + itkSetMacro(OutputSpacing,SpacingType); + itkGetConstReferenceMacro(OutputSpacing,SpacingType); + + /** Set/Get the Default Unknown Value. */ + itkSetMacro(DefaultUnknownValue,PixelType); + itkGetConstReferenceMacro(DefaultUnknownValue,PixelType); + + /** Set the DEM directory. */ + virtual void SetDEMDirectoryPath(const char* DEMDirectory); + + +protected: + DEMToImageGenerator(); + ~DEMToImageGenerator(); + + void PrintSelf(std::ostream& os, Indent indent) const; + void GenerateData(); + virtual void GenerateOutputInformation(); + + DEMHandlerType::Pointer m_DEMHandler; + PointType m_OutputOrigin; + SpacingType m_OutputSpacing; + SizeType m_OutputSize; + PixelType m_DefaultUnknownValue; + +private: + DEMToImageGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/IO/otbDEMToImageGenerator.txx b/Code/IO/otbDEMToImageGenerator.txx index aa32149854522e881cf3580f7dd7efba4366fc2a..6b936449b491aca93753e869b3d96d5cef075284 100644 --- a/Code/IO/otbDEMToImageGenerator.txx +++ b/Code/IO/otbDEMToImageGenerator.txx @@ -25,113 +25,113 @@ namespace otb { - template<class TDEMImage> - DEMToImageGenerator<TDEMImage> - ::DEMToImageGenerator() - { - m_DEMHandler = DEMHandlerType::New(); - m_OutputSpacing[0]=0.0001; - m_OutputSpacing[1]=-0.0001; - m_OutputSize[0]=1; - m_OutputSize[1]=1; - m_OutputOrigin[0]=0; - m_OutputOrigin[1]=0; - m_DefaultUnknownValue = static_cast<PixelType>(-32768); // Value defined in the norm for points strm doesn't have information. - } - - template<class TDEMImage> - DEMToImageGenerator<TDEMImage> - ::~DEMToImageGenerator() - { - // Nothing to be done... - } - - // DEM folder specification method - template<class TDEMImage> - void - DEMToImageGenerator<TDEMImage>:: - SetDEMDirectoryPath(const char* DEMDirectory) - { - m_DEMHandler->OpenDEMDirectory(DEMDirectory); - } - - // GenerateOutputInformation method - template <class TDEMImage> - void DEMToImageGenerator<TDEMImage> - ::GenerateOutputInformation() - { - DEMImageType *output; - output = this->GetOutput(0); +template<class TDEMImage> +DEMToImageGenerator<TDEMImage> +::DEMToImageGenerator() +{ + m_DEMHandler = DEMHandlerType::New(); + m_OutputSpacing[0]=0.0001; + m_OutputSpacing[1]=-0.0001; + m_OutputSize[0]=1; + m_OutputSize[1]=1; + m_OutputOrigin[0]=0; + m_OutputOrigin[1]=0; + m_DefaultUnknownValue = static_cast<PixelType>(-32768); // Value defined in the norm for points strm doesn't have information. +} + +template<class TDEMImage> +DEMToImageGenerator<TDEMImage> +::~DEMToImageGenerator() +{ + // Nothing to be done... +} + +// DEM folder specification method +template<class TDEMImage> +void +DEMToImageGenerator<TDEMImage>:: +SetDEMDirectoryPath(const char* DEMDirectory) +{ + m_DEMHandler->OpenDEMDirectory(DEMDirectory); +} - IndexType start; - start[0]=0; - start[1]=0; +// GenerateOutputInformation method +template <class TDEMImage> +void DEMToImageGenerator<TDEMImage> +::GenerateOutputInformation() +{ + DEMImageType *output; + output = this->GetOutput(0); + + IndexType start; + start[0]=0; + start[1]=0; + + // Specify region parameters + OutputImageRegionType largestPossibleRegion; + largestPossibleRegion.SetSize( m_OutputSize ); + largestPossibleRegion.SetIndex( start ); + + output->SetLargestPossibleRegion( largestPossibleRegion ); + output->SetSpacing(m_OutputSpacing); + output->SetOrigin(m_OutputOrigin); +} + +// GenerateData method +template <class TDEMImage> +void +DEMToImageGenerator<TDEMImage> +::GenerateData() +{ + DEMImagePointerType DEMImage = this->GetOutput(); - // Specify region parameters - OutputImageRegionType largestPossibleRegion; - largestPossibleRegion.SetSize( m_OutputSize ); - largestPossibleRegion.SetIndex( start ); + // allocate the output buffer + DEMImage->SetBufferedRegion( DEMImage->GetRequestedRegion() ); + DEMImage->Allocate(); + DEMImage->FillBuffer(0); + // Create an iterator that will walk the output region + ImageIteratorType outIt = ImageIteratorType(DEMImage,DEMImage->GetRequestedRegion()); - output->SetLargestPossibleRegion( largestPossibleRegion ); - output->SetSpacing(m_OutputSpacing); - output->SetOrigin(m_OutputOrigin); - } + // Walk the output image, evaluating the height at each pixel + IndexType currentindex; + PointType phyPoint; + double height; - // GenerateData method - template <class TDEMImage> - void - DEMToImageGenerator<TDEMImage> - ::GenerateData() + for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) { - DEMImagePointerType DEMImage = this->GetOutput(); - - // allocate the output buffer - DEMImage->SetBufferedRegion( DEMImage->GetRequestedRegion() ); - DEMImage->Allocate(); - DEMImage->FillBuffer(0); - // Create an iterator that will walk the output region - ImageIteratorType outIt = ImageIteratorType(DEMImage,DEMImage->GetRequestedRegion()); - - // Walk the output image, evaluating the height at each pixel - IndexType currentindex; - PointType phyPoint; - double height; - - for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) - { - currentindex=outIt.GetIndex(); - DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint); + currentindex=outIt.GetIndex(); + DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint); // otbMsgDevMacro(<< "PhyPoint : (" << phyPoint[0] << "," << phyPoint[1] << ")"); - height=m_DEMHandler->GetHeightAboveMSL(phyPoint); // Altitude calculation + height=m_DEMHandler->GetHeightAboveMSL(phyPoint); // Altitude calculation // otbMsgDevMacro(<< "height" << height); - // MNT sets a default value (-32768) at point where it doesn't have altitude information. - // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). - if (!ossim::isnan(height)) - { - // Fill the image - DEMImage->SetPixel(currentindex, static_cast<PixelType>(height) ); - } - else - { - // Back to the MNT default value - DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); - } + // MNT sets a default value (-32768) at point where it doesn't have altitude information. + // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). + if (!ossim::isnan(height)) + { + // Fill the image + DEMImage->SetPixel(currentindex, static_cast<PixelType>(height) ); + } + else + { + // Back to the MNT default value + DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); } } +} - template <class TDEMImage> - void - DEMToImageGenerator<TDEMImage> - ::PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); +template <class TDEMImage> +void +DEMToImageGenerator<TDEMImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); - os << indent << "Output Spacing:"<< m_OutputSpacing[0] << ","<< m_OutputSpacing[1] << std::endl; - os << indent << "Output Origin:"<< m_OutputOrigin[0] << ","<< m_OutputOrigin[1] << std::endl; - os << indent << "Output Size:"<< m_OutputSize[0] << ","<< m_OutputSize[1] << std::endl; - } + os << indent << "Output Spacing:"<< m_OutputSpacing[0] << ","<< m_OutputSpacing[1] << std::endl; + os << indent << "Output Origin:"<< m_OutputOrigin[0] << ","<< m_OutputOrigin[1] << std::endl; + os << indent << "Output Size:"<< m_OutputSize[0] << ","<< m_OutputSize[1] << std::endl; +} } // namespace otb diff --git a/Code/IO/otbDEMToOrthoImageGenerator.h b/Code/IO/otbDEMToOrthoImageGenerator.h index e7c3a018cd84a02c87bdd2a20298db17eaf2c90b..2b0933d04f3f85467406cc718beb98023402384e 100644 --- a/Code/IO/otbDEMToOrthoImageGenerator.h +++ b/Code/IO/otbDEMToOrthoImageGenerator.h @@ -32,91 +32,91 @@ namespace otb { - /** \class DEMToOrthoImageGenerator - * - * \brief Class for Reading a DEM data - * - * This class is based on ossimElevManager. It takes in input the UL and LR map coordinates and the spacing. - * Handle DTED and SRTM formats. - * \ingroup Images - * - */ - template <class TDEMImage, class TMapProjection> - class ITK_EXPORT DEMToOrthoImageGenerator: - public otb::DEMToImageGenerator<TDEMImage> - { - public : - /** Standard class typedefs. */ - typedef itk::Indent Indent; - typedef TDEMImage DEMImageType; - typedef typename DEMImageType::Pointer DEMImagePointerType; - typedef typename DEMImageType::PixelType PixelType; - - typedef TMapProjection MapProjectionType; - typedef typename MapProjectionType::Pointer MapProjectionPointerType; - - typedef DEMToOrthoImageGenerator Self; - typedef otb::DEMToImageGenerator<DEMImageType> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef Image<PixelType,2> OutputImageType; - - typedef typename Superclass::Pointer OutputImagePointer; - typedef typename OutputImageType::SpacingType SpacingType; - typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::PointType PointType; - typedef typename OutputImageType::IndexType IndexType; - typedef typename Superclass::OutputImageRegionType OutputImageRegionType; - typedef itk::ImageRegionIteratorWithIndex< DEMImageType > ImageIteratorType; - - typedef otb::DEMHandler DEMHandlerType; - typedef typename DEMHandlerType::Pointer DEMHandlerPointerType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(DEMToOrthoImageGenerator,ImageSource); - - /** Set/Get the Output Origin coordinates. */ - itkSetMacro(OutputOrigin,PointType); - itkGetConstReferenceMacro(OutputOrigin,PointType); - - /** Set/Get the Output Size. */ - itkSetMacro(OutputSize,SizeType); - itkGetConstReferenceMacro(OutputSize,SizeType); - - /** Set/Get the Output Spacing. */ - itkSetMacro(OutputSpacing,SpacingType); - itkGetConstReferenceMacro(OutputSpacing,SpacingType); - - /** Set/Get the Default Unknown Value. */ - itkSetMacro(DefaultUnknownValue,PixelType); - itkGetConstReferenceMacro(DefaultUnknownValue,PixelType); - - /** Set/Get the projection*/ - itkSetMacro(MapProjection, MapProjectionPointerType); - itkGetMacro(MapProjection, MapProjectionPointerType); - - protected: - DEMToOrthoImageGenerator(); - ~DEMToOrthoImageGenerator(); - - void PrintSelf(std::ostream& os, Indent indent) const; - void GenerateData(); - virtual void GenerateOutputInformation(); - - DEMHandlerPointerType m_DEMHandler; - PointType m_OutputOrigin; - SpacingType m_OutputSpacing; - SizeType m_OutputSize; - PixelType m_DefaultUnknownValue; - MapProjectionPointerType m_MapProjection; - - private: - DEMToOrthoImageGenerator(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +/** \class DEMToOrthoImageGenerator + * + * \brief Class for Reading a DEM data + * + * This class is based on ossimElevManager. It takes in input the UL and LR map coordinates and the spacing. + * Handle DTED and SRTM formats. + * \ingroup Images + * + */ +template <class TDEMImage, class TMapProjection> +class ITK_EXPORT DEMToOrthoImageGenerator: + public otb::DEMToImageGenerator<TDEMImage> +{ +public : + /** Standard class typedefs. */ + typedef itk::Indent Indent; + typedef TDEMImage DEMImageType; + typedef typename DEMImageType::Pointer DEMImagePointerType; + typedef typename DEMImageType::PixelType PixelType; + + typedef TMapProjection MapProjectionType; + typedef typename MapProjectionType::Pointer MapProjectionPointerType; + + typedef DEMToOrthoImageGenerator Self; + typedef otb::DEMToImageGenerator<DEMImageType> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef Image<PixelType,2> OutputImageType; + + typedef typename Superclass::Pointer OutputImagePointer; + typedef typename OutputImageType::SpacingType SpacingType; + typedef typename OutputImageType::SizeType SizeType; + typedef typename OutputImageType::PointType PointType; + typedef typename OutputImageType::IndexType IndexType; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef itk::ImageRegionIteratorWithIndex< DEMImageType > ImageIteratorType; + + typedef otb::DEMHandler DEMHandlerType; + typedef typename DEMHandlerType::Pointer DEMHandlerPointerType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(DEMToOrthoImageGenerator,ImageSource); + + /** Set/Get the Output Origin coordinates. */ + itkSetMacro(OutputOrigin,PointType); + itkGetConstReferenceMacro(OutputOrigin,PointType); + + /** Set/Get the Output Size. */ + itkSetMacro(OutputSize,SizeType); + itkGetConstReferenceMacro(OutputSize,SizeType); + + /** Set/Get the Output Spacing. */ + itkSetMacro(OutputSpacing,SpacingType); + itkGetConstReferenceMacro(OutputSpacing,SpacingType); + + /** Set/Get the Default Unknown Value. */ + itkSetMacro(DefaultUnknownValue,PixelType); + itkGetConstReferenceMacro(DefaultUnknownValue,PixelType); + + /** Set/Get the projection*/ + itkSetMacro(MapProjection, MapProjectionPointerType); + itkGetMacro(MapProjection, MapProjectionPointerType); + +protected: + DEMToOrthoImageGenerator(); + ~DEMToOrthoImageGenerator(); + + void PrintSelf(std::ostream& os, Indent indent) const; + void GenerateData(); + virtual void GenerateOutputInformation(); + + DEMHandlerPointerType m_DEMHandler; + PointType m_OutputOrigin; + SpacingType m_OutputSpacing; + SizeType m_OutputSize; + PixelType m_DefaultUnknownValue; + MapProjectionPointerType m_MapProjection; + +private: + DEMToOrthoImageGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/IO/otbDEMToOrthoImageGenerator.txx b/Code/IO/otbDEMToOrthoImageGenerator.txx index f478473d9c42cea1718dac27c8a336646ccfab92..24302d040d5dc2d44ed9fd0b92869a3aef6aca32 100644 --- a/Code/IO/otbDEMToOrthoImageGenerator.txx +++ b/Code/IO/otbDEMToOrthoImageGenerator.txx @@ -25,118 +25,118 @@ namespace otb { - template<class TDEMImage, class TMapProjection> - DEMToOrthoImageGenerator<TDEMImage, TMapProjection> - ::DEMToOrthoImageGenerator() - { - m_DEMHandler = DEMHandlerType::New(); - m_OutputSpacing[0]=0.0001; - m_OutputSpacing[1]=-0.0001; - m_OutputSize[0]=1; - m_OutputSize[1]=1; - m_OutputOrigin[0]=0; - m_OutputOrigin[1]=0; - m_DefaultUnknownValue = static_cast<PixelType>(-32768); // Value defined in the norm for points strm doesn't have information. - m_MapProjection = NULL; - } +template<class TDEMImage, class TMapProjection> +DEMToOrthoImageGenerator<TDEMImage, TMapProjection> +::DEMToOrthoImageGenerator() +{ + m_DEMHandler = DEMHandlerType::New(); + m_OutputSpacing[0]=0.0001; + m_OutputSpacing[1]=-0.0001; + m_OutputSize[0]=1; + m_OutputSize[1]=1; + m_OutputOrigin[0]=0; + m_OutputOrigin[1]=0; + m_DefaultUnknownValue = static_cast<PixelType>(-32768); // Value defined in the norm for points strm doesn't have information. + m_MapProjection = NULL; +} + +template<class TDEMImage, class TMapProjection> +DEMToOrthoImageGenerator<TDEMImage, TMapProjection> +::~DEMToOrthoImageGenerator() +{ + // Nothing to be done... +} + + +// GenerateOutputInformation method +template <class TDEMImage, class TMapProjection> +void DEMToOrthoImageGenerator<TDEMImage, TMapProjection> +::GenerateOutputInformation() +{ + DEMImageType *output; + output = this->GetOutput(0); + + IndexType start; + start[0]=0; + start[1]=0; + + // Specify region parameters + OutputImageRegionType largestPossibleRegion; + largestPossibleRegion.SetSize( m_OutputSize ); + largestPossibleRegion.SetIndex( start ); + + output->SetLargestPossibleRegion( largestPossibleRegion ); + output->SetSpacing(m_OutputSpacing); + output->SetOrigin(m_OutputOrigin); +} + +// GenerateData method +template <class TDEMImage, class TMapProjection> +void +DEMToOrthoImageGenerator<TDEMImage, TMapProjection> +::GenerateData() +{ - template<class TDEMImage, class TMapProjection> - DEMToOrthoImageGenerator<TDEMImage, TMapProjection> - ::~DEMToOrthoImageGenerator() + if (!m_MapProjection) { - // Nothing to be done... + itkExceptionMacro( << + "Please set map projection!" ); } - - // GenerateOutputInformation method - template <class TDEMImage, class TMapProjection> - void DEMToOrthoImageGenerator<TDEMImage, TMapProjection> - ::GenerateOutputInformation() + DEMImagePointerType DEMImage = this->GetOutput(); + + // allocate the output buffer + DEMImage->SetBufferedRegion( DEMImage->GetRequestedRegion() ); + DEMImage->Allocate(); + DEMImage->FillBuffer(0); + // Create an iterator that will walk the output region + ImageIteratorType outIt = ImageIteratorType(DEMImage,DEMImage->GetRequestedRegion()); + + // Walk the output image, evaluating the height at each pixel + IndexType currentindex; + PointType cartoPoint; + double height; + PointType geoPoint; + for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) { - DEMImageType *output; - output = this->GetOutput(0); + currentindex=outIt.GetIndex(); - IndexType start; - start[0]=0; - start[1]=0; + DEMImage->TransformIndexToPhysicalPoint(currentindex, cartoPoint); - // Specify region parameters - OutputImageRegionType largestPossibleRegion; - largestPossibleRegion.SetSize( m_OutputSize ); - largestPossibleRegion.SetIndex( start ); + otbMsgDevMacro(<< "CartoPoint : (" << cartoPoint[0] << "," << cartoPoint[1] << ")"); - output->SetLargestPossibleRegion( largestPossibleRegion ); - output->SetSpacing(m_OutputSpacing); - output->SetOrigin(m_OutputOrigin); - } + geoPoint = m_MapProjection->TransformPoint(cartoPoint); - // GenerateData method - template <class TDEMImage, class TMapProjection> - void - DEMToOrthoImageGenerator<TDEMImage, TMapProjection> - ::GenerateData() - { + otbMsgDevMacro(<< "CartoPoint : (" << geoPoint[0] << "," << geoPoint[1] << ")"); - if(!m_MapProjection) + height=m_DEMHandler->GetHeightAboveMSL(geoPoint); // Altitude calculation + otbMsgDevMacro(<< "height" << height); + // MNT sets a default value (-32768) at point where it doesn't have altitude information. + // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). + if (!ossim::isnan(height)) { - itkExceptionMacro( << - "Please set map projection!" ); + // Fill the image + DEMImage->SetPixel(currentindex, static_cast<PixelType>(height) ); } - - DEMImagePointerType DEMImage = this->GetOutput(); - - // allocate the output buffer - DEMImage->SetBufferedRegion( DEMImage->GetRequestedRegion() ); - DEMImage->Allocate(); - DEMImage->FillBuffer(0); - // Create an iterator that will walk the output region - ImageIteratorType outIt = ImageIteratorType(DEMImage,DEMImage->GetRequestedRegion()); - - // Walk the output image, evaluating the height at each pixel - IndexType currentindex; - PointType cartoPoint; - double height; - PointType geoPoint; - for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) + else { - currentindex=outIt.GetIndex(); - - DEMImage->TransformIndexToPhysicalPoint(currentindex, cartoPoint); - - otbMsgDevMacro(<< "CartoPoint : (" << cartoPoint[0] << "," << cartoPoint[1] << ")"); - - geoPoint = m_MapProjection->TransformPoint(cartoPoint); - - otbMsgDevMacro(<< "CartoPoint : (" << geoPoint[0] << "," << geoPoint[1] << ")"); - - height=m_DEMHandler->GetHeightAboveMSL(geoPoint); // Altitude calculation - otbMsgDevMacro(<< "height" << height); - // MNT sets a default value (-32768) at point where it doesn't have altitude information. - // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). - if (!ossim::isnan(height)) - { - // Fill the image - DEMImage->SetPixel(currentindex, static_cast<PixelType>(height) ); - } - else - { - // Back to the MNT default value - DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); - } + // Back to the MNT default value + DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); } } +} - template <class TDEMImage, class TMapProjection> - void - DEMToOrthoImageGenerator<TDEMImage, TMapProjection> - ::PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); +template <class TDEMImage, class TMapProjection> +void +DEMToOrthoImageGenerator<TDEMImage, TMapProjection> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); - os << indent << "Output Spacing:"<< m_OutputSpacing[0] << ","<< m_OutputSpacing[1] << std::endl; - os << indent << "Output Origin:"<< m_OutputOrigin[0] << ","<< m_OutputOrigin[1] << std::endl; - os << indent << "Output Size:"<< m_OutputSize[0] << ","<< m_OutputSize[1] << std::endl; - } + os << indent << "Output Spacing:"<< m_OutputSpacing[0] << ","<< m_OutputSpacing[1] << std::endl; + os << indent << "Output Origin:"<< m_OutputOrigin[0] << ","<< m_OutputOrigin[1] << std::endl; + os << indent << "Output Size:"<< m_OutputSize[0] << ","<< m_OutputSize[1] << std::endl; +} } // namespace otb diff --git a/Code/IO/otbDXFToSpatialObjectGroupFilter.h b/Code/IO/otbDXFToSpatialObjectGroupFilter.h index 69580b88c22a2ffcfc24326ada20c30f74a7cded..9a442843fd5063f9d365e2ca259d139e845b07a2 100644 --- a/Code/IO/otbDXFToSpatialObjectGroupFilter.h +++ b/Code/IO/otbDXFToSpatialObjectGroupFilter.h @@ -33,15 +33,15 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class DXFToSpatialObjectGroupFilter - * \brief - * - */ +/** \class DXFToSpatialObjectGroupFilter + * \brief + * + */ template <class TSpatialObject> class ITK_EXPORT DXFToSpatialObjectGroupFilter - : public DL_CreationAdapter, public SpatialObjectSource<TSpatialObject> + : public DL_CreationAdapter, public SpatialObjectSource<TSpatialObject> { - public: +public: /** Standard typedefs */ typedef DXFToSpatialObjectGroupFilter Self; typedef SpatialObjectSource< TSpatialObject > Superclass; @@ -85,7 +85,7 @@ class ITK_EXPORT DXFToSpatialObjectGroupFilter /** Workaround while waiting for the SpatialObject bug to be fixed */ virtual void Update(void); - protected: +protected: /** Constructor */ DXFToSpatialObjectGroupFilter(); /** Destructor */ @@ -97,7 +97,7 @@ class ITK_EXPORT DXFToSpatialObjectGroupFilter /** PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: DXFToSpatialObjectGroupFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented int m_CurrentObjectType; diff --git a/Code/IO/otbDXFToSpatialObjectGroupFilter.txx b/Code/IO/otbDXFToSpatialObjectGroupFilter.txx index 12b36df280ff9bf749d5faa86372a081e7a725e6..e57b2eb914102337582a0e503c44001e580246c8 100644 --- a/Code/IO/otbDXFToSpatialObjectGroupFilter.txx +++ b/Code/IO/otbDXFToSpatialObjectGroupFilter.txx @@ -22,413 +22,414 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor. - */ - template <class TSpatialObject> - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::DXFToSpatialObjectGroupFilter() - { - m_CurrentObjectType=0; - m_PointList.clear(); - m_layer=""; - layerspecified=false; - this->SetNumberOfRequiredOutputs(0); - } - /** - * Set the layer to read - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::SetLayer(const char* layer) { - m_layer=layer; - layerspecified=true; - } - /** - * Sample implementation of the method which handles layers. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addLayer(const DL_LayerData& data) +/** + * Constructor. + */ +template <class TSpatialObject> +DXFToSpatialObjectGroupFilter<TSpatialObject> +::DXFToSpatialObjectGroupFilter() +{ + m_CurrentObjectType=0; + m_PointList.clear(); + m_layer=""; + layerspecified=false; + this->SetNumberOfRequiredOutputs(0); +} +/** + * Set the layer to read + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::SetLayer(const char* layer) +{ + m_layer=layer; + layerspecified=true; +} +/** + * Sample implementation of the method which handles layers. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addLayer(const DL_LayerData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); + { + grpPtr->AddSpatialObject(m_CurrentPolyLine); } - m_CurrentObjectType=0; - otbMsgDebugMacro(<<"LAYER: "<< data.name <<" flags: "<<data.flags); - + } + else + grpPtr->AddSpatialObject(m_CurrentPolyLine); } - /** - * Sample implementation of the method which handles point entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addPoint(const DL_PointData& data) + m_CurrentObjectType=0; + otbMsgDebugMacro(<<"LAYER: "<< data.name <<" flags: "<<data.flags); + +} +/** + * Sample implementation of the method which handles point entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addPoint(const DL_PointData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp( attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - m_CurrentObjectType=1; - LandmarkPointer landmark=LandmarkType::New(); - PointType point; - LandmarkListType list; - point.SetPosition(data.x, data.y, data.z ); - list.push_back(point); - landmark->SetPoints(list); - if(layerspecified) { - if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(landmark); - } + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + } else + grpPtr->AddSpatialObject(m_CurrentPolyLine); + } + m_CurrentObjectType=1; + LandmarkPointer landmark=LandmarkType::New(); + PointType point; + LandmarkListType list; + point.SetPosition(data.x, data.y, data.z ); + list.push_back(point); + landmark->SetPoints(list); + if (layerspecified) + { + if (!strcmp(attributes.getLayer().c_str(),m_layer)) + { grpPtr->AddSpatialObject(landmark); - otbMsgDebugMacro(<<"POINT ("<<data.x<<", "<<data.y<<", "<<data.z<<") ( nb objects "<<grpPtr->GetNumberOfChildren()<<")"); - + } } - /** - * Sample implementation of the method which handles line entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addLine(const DL_LineData& data) + else + grpPtr->AddSpatialObject(landmark); + otbMsgDebugMacro(<<"POINT ("<<data.x<<", "<<data.y<<", "<<data.z<<") ( nb objects "<<grpPtr->GetNumberOfChildren()<<")"); + +} +/** + * Sample implementation of the method which handles line entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addLine(const DL_LineData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp( attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - m_CurrentObjectType=2; - LinePointer line=LineType::New(); - LinePointType point1,point2; - LineListType list,pointlist; - pointlist.clear(); - point1.SetPosition(data.x1, data.y1, data.z1); - list.push_back(point1); - point2.SetPosition(data.x2, data.y2, data.z2); - list.push_back(point2); - line->SetPoints(list); - if(layerspecified) { - if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(line); - } + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + } else + grpPtr->AddSpatialObject(m_CurrentPolyLine); + } + m_CurrentObjectType=2; + LinePointer line=LineType::New(); + LinePointType point1,point2; + LineListType list,pointlist; + pointlist.clear(); + point1.SetPosition(data.x1, data.y1, data.z1); + list.push_back(point1); + point2.SetPosition(data.x2, data.y2, data.z2); + list.push_back(point2); + line->SetPoints(list); + if (layerspecified) + { + if (!strcmp(attributes.getLayer().c_str(),m_layer)) + { grpPtr->AddSpatialObject(line); - otbMsgDebugMacro(<<"LINE "<<"("<<data.x1<<", "<<data.y1<<", "<<data.z1<<") (" - <<data.x2<<", "<<data.y2<<", "<<data.z2 <<grpPtr->GetNumberOfChildren()<<")"); - + } } - /** - * Sample implementation of the method which handles 3DFace entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::add3DFace(const DL_3DFaceData& data) + else + grpPtr->AddSpatialObject(line); + otbMsgDebugMacro(<<"LINE "<<"("<<data.x1<<", "<<data.y1<<", "<<data.z1<<") (" + <<data.x2<<", "<<data.y2<<", "<<data.z2 <<grpPtr->GetNumberOfChildren()<<")"); + +} +/** + * Sample implementation of the method which handles 3DFace entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::add3DFace(const DL_3DFaceData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - m_CurrentObjectType=7; - LinePointer line=LineType::New(); - LinePointType point1,point2,point3,point4; - LineListType list,pointlist; - pointlist.clear(); - point1.SetPosition(data.x1, data.y1, data.z1); - list.push_back(point1); - point2.SetPosition(data.x2, data.y2, data.z2); - list.push_back(point2); - point3.SetPosition(data.x3, data.y3, data.z3); - list.push_back(point3); - point4.SetPosition(data.x4, data.y4, data.z4); - list.push_back(point4); - list.push_back(point1); - line->SetPoints(list); - if(layerspecified) { - if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(line); - } + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + } else + grpPtr->AddSpatialObject(m_CurrentPolyLine); + } + m_CurrentObjectType=7; + LinePointer line=LineType::New(); + LinePointType point1,point2,point3,point4; + LineListType list,pointlist; + pointlist.clear(); + point1.SetPosition(data.x1, data.y1, data.z1); + list.push_back(point1); + point2.SetPosition(data.x2, data.y2, data.z2); + list.push_back(point2); + point3.SetPosition(data.x3, data.y3, data.z3); + list.push_back(point3); + point4.SetPosition(data.x4, data.y4, data.z4); + list.push_back(point4); + list.push_back(point1); + line->SetPoints(list); + if (layerspecified) + { + if (!strcmp(attributes.getLayer().c_str(),m_layer)) + { grpPtr->AddSpatialObject(line); - otbMsgDebugMacro(<<"3D Face "<<"("<<data.x1<<", "<<data.y1<<", "<<data.z1<<") (" - <<data.x2<<", "<<data.y2<<", "<<data.z2<<") (" - <<data.x3<<", "<<data.y3<<", "<<data.z3<<") (" - <<data.x4<<", "<<data.y4<<", "<<data.z4<<") (" - <<grpPtr->GetNumberOfChildren()<<")"); - + } } - /** - * Sample implementation of the method which handles arc entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addArc(const DL_ArcData& data) + else + grpPtr->AddSpatialObject(line); + otbMsgDebugMacro(<<"3D Face "<<"("<<data.x1<<", "<<data.y1<<", "<<data.z1<<") (" + <<data.x2<<", "<<data.y2<<", "<<data.z2<<") (" + <<data.x3<<", "<<data.y3<<", "<<data.z3<<") (" + <<data.x4<<", "<<data.y4<<", "<<data.z4<<") (" + <<grpPtr->GetNumberOfChildren()<<")"); + +} +/** + * Sample implementation of the method which handles arc entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addArc(const DL_ArcData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); + { + grpPtr->AddSpatialObject(m_CurrentPolyLine); } - otbMsgDebugMacro(<<"ARC ("<<data.cx<<", "<<data.cy<<", "<<data.cz<<") " - <<data.radius<<", "<<data.angle1<<", "<<data.angle2 - <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); - + } + else + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + otbMsgDebugMacro(<<"ARC ("<<data.cx<<", "<<data.cy<<", "<<data.cz<<") " + <<data.radius<<", "<<data.angle1<<", "<<data.angle2 + <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); - /** - * Sample implementation of the method which handles circle entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addCircle(const DL_CircleData& data) +} + +/** + * Sample implementation of the method which handles circle entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addCircle(const DL_CircleData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - m_CurrentObjectType=4; - EllipsePointer ellipse=EllipseType::New(); - ellipse->SetRadius(data.radius); - double offset[TSpatialObject::ObjectDimension]; - offset[ 0 ] = data.cx; - offset[ 1 ] = data.cy; - if (TSpatialObject::ObjectDimension==3) { - offset[ 2 ] = data.cz; + grpPtr->AddSpatialObject(m_CurrentPolyLine); } - ellipse->GetObjectToParentTransform()->SetOffset(offset); - ellipse->ComputeObjectToWorldTransform(); - if(layerspecified) - { - if (!strcmp(attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(ellipse); } - } else + grpPtr->AddSpatialObject(m_CurrentPolyLine); + } + m_CurrentObjectType=4; + EllipsePointer ellipse=EllipseType::New(); + ellipse->SetRadius(data.radius); + double offset[TSpatialObject::ObjectDimension]; + offset[ 0 ] = data.cx; + offset[ 1 ] = data.cy; + if (TSpatialObject::ObjectDimension==3) + { + offset[ 2 ] = data.cz; + } + ellipse->GetObjectToParentTransform()->SetOffset(offset); + ellipse->ComputeObjectToWorldTransform(); + if (layerspecified) + { + if (!strcmp(attributes.getLayer().c_str(),m_layer)) + { grpPtr->AddSpatialObject(ellipse); + } + } + else + grpPtr->AddSpatialObject(ellipse); - otbMsgDebugMacro(<<"CIRCLE ("<<data.cx<<", "<<data.cy<<", "<<data.cz<<") " - <<data.radius - <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); + otbMsgDebugMacro(<<"CIRCLE ("<<data.cx<<", "<<data.cy<<", "<<data.cz<<") " + <<data.radius + <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); - } - /** - * Sample implementation of the method which handles polyline entities. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addPolyline(const DL_PolylineData& data) +} +/** + * Sample implementation of the method which handles polyline entities. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addPolyline(const DL_PolylineData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp( attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - m_CurrentObjectType=5; - - m_PointList.clear();//reset list - - if ((int)data.flags==1) { - m_PolylineClosed=1; + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + } else - m_PolylineClosed=0; - otbMsgDebugMacro(<<"POLYLINE "); - otbMsgDebugMacro(<<"flags: "<< data.flags <<",nombre de sommets: "<< data.number); - + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + m_CurrentObjectType=5; + m_PointList.clear();//reset list - /** - * Sample implementation of the method which handles vertices. - */ - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::addVertex(const DL_VertexData& data) + if ((int)data.flags==1) { - GroupPointer grpPtr = this->GetOutput(); - m_CurrentObjectType=6; - LinePointType point; - point.SetPosition(data.x, data.y, data.z); - m_PointList.push_back(point); - m_PremierPoint=m_PointList[0]; - otbMsgDebugMacro(<<"VERTEX ("<<data.x<<", "<<data.y<<", "<<data.z<<") " - <<data.bulge - <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); - + m_PolylineClosed=1; } + else + m_PolylineClosed=0; + otbMsgDebugMacro(<<"POLYLINE "); + otbMsgDebugMacro(<<"flags: "<< data.flags <<",nombre de sommets: "<< data.number); + +} + + +/** + * Sample implementation of the method which handles vertices. + */ +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::addVertex(const DL_VertexData& data) +{ + GroupPointer grpPtr = this->GetOutput(); + m_CurrentObjectType=6; + LinePointType point; + point.SetPosition(data.x, data.y, data.z); + m_PointList.push_back(point); + m_PremierPoint=m_PointList[0]; + otbMsgDebugMacro(<<"VERTEX ("<<data.x<<", "<<data.y<<", "<<data.z<<") " + <<data.bulge + <<" (nb objects "<<grpPtr->GetNumberOfChildren()<<")"); + +} - template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::GenerateData() +template <class TSpatialObject> +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::GenerateData() +{ + GroupPointer grpPtr = this->GetOutput(); + //If the previous object is a vertex we create the polyline: + if (m_CurrentObjectType==6) { - GroupPointer grpPtr = this->GetOutput(); - //If the previous object is a vertex we create the polyline: - if (m_CurrentObjectType==6) - { - //If the polyline is closed then we add the first point at the end of the list: - if (m_PolylineClosed==1) + //If the polyline is closed then we add the first point at the end of the list: + if (m_PolylineClosed==1) { m_PointList.push_back(m_PremierPoint); } - LinePointer m_CurrentPolyLine=LineType::New(); - m_CurrentPolyLine->SetPoints(m_PointList); - if(layerspecified) + LinePointer m_CurrentPolyLine=LineType::New(); + m_CurrentPolyLine->SetPoints(m_PointList); + if (layerspecified) { if (!strcmp( attributes.getLayer().c_str(),m_layer)) - { - grpPtr->AddSpatialObject(m_CurrentPolyLine); - } - } - else - grpPtr->AddSpatialObject(m_CurrentPolyLine); + { + grpPtr->AddSpatialObject(m_CurrentPolyLine); } + } + else + grpPtr->AddSpatialObject(m_CurrentPolyLine); } +} template <class TSpatialObject> - void - DXFToSpatialObjectGroupFilter<TSpatialObject> - ::Update() - { - this->GenerateData(); - } +void +DXFToSpatialObjectGroupFilter<TSpatialObject> +::Update() +{ + this->GenerateData(); +} template <class TSpatialObject> void diff --git a/Code/IO/otbFileName.cxx b/Code/IO/otbFileName.cxx index e6138ec2ee3aec442aedfe38346fd6a23115c9ce..6728480aebe2d189e1fa14907a5b0118b0397932 100644 --- a/Code/IO/otbFileName.cxx +++ b/Code/IO/otbFileName.cxx @@ -25,19 +25,19 @@ FileName::FileName() : ossimFilename() {} FileName::FileName(const FileName& src) - : ossimFilename(src) + : ossimFilename(src) {} FileName::FileName(const ossimFilename& src) - : ossimFilename(src) + : ossimFilename(src) {} FileName::FileName(const ossimString& src) - : ossimFilename(src) + : ossimFilename(src) {} FileName::FileName(const char* src) - : ossimFilename(src) + : ossimFilename(src) {} diff --git a/Code/IO/otbFileName.h b/Code/IO/otbFileName.h index f108af2c796d721da3e67d8dc92626e3c6b543a5..3e80bbd6eb37e574579d9bc8bb362b501409a59b 100644 --- a/Code/IO/otbFileName.h +++ b/Code/IO/otbFileName.h @@ -35,16 +35,16 @@ class ITK_EXPORT FileName : public ossimFilename { public: - FileName(); - FileName(const FileName& src); - FileName(const ossimFilename& src); - FileName(const ossimString& src); - FileName(const char* src); - - /** - * Return "t1" if file is "/data/images/t1.tif". - */ - FileName ObtainFileNameWithNoExtension() const; + FileName(); + FileName(const FileName& src); + FileName(const ossimFilename& src); + FileName(const ossimString& src); + FileName(const char* src); + + /** + * Return "t1" if file is "/data/images/t1.tif". + */ + FileName ObtainFileNameWithNoExtension() const; }; diff --git a/Code/IO/otbGDALImageIO.cxx b/Code/IO/otbGDALImageIO.cxx index cd05b2c4cbbd86bcff2ab3c9f9fee241b99d9672..1bf5a872b655609ed06e7629c1abfd911ca9db9e 100644 --- a/Code/IO/otbGDALImageIO.cxx +++ b/Code/IO/otbGDALImageIO.cxx @@ -47,287 +47,287 @@ namespace otb { - GDALImageIO::GDALImageIO() - { +GDALImageIO::GDALImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); // By default set pixel type to scalar. - m_PixelType = SCALAR; + m_PixelType = SCALAR; // By default set component type to unsigned char - m_ComponentType = UCHAR; - m_UseCompression = false; - m_CompressionLevel = 4; // Range 0-9; 0 = no file compression, 9 = maximum file compression + m_ComponentType = UCHAR; + m_UseCompression = false; + m_CompressionLevel = 4; // Range 0-9; 0 = no file compression, 9 = maximum file compression // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_currentfile = NULL; - m_poBands = NULL; - m_hDriver = NULL; - m_poDataset = NULL; + m_currentfile = NULL; + m_poBands = NULL; + m_hDriver = NULL; + m_poDataset = NULL; - m_NbBands = 0; - m_FlagWriteImageInformation = true; + m_NbBands = 0; + m_FlagWriteImageInformation = true; - } +} - GDALImageIO::~GDALImageIO() - { +GDALImageIO::~GDALImageIO() +{ //THOMAS // if( m_hDriver != NULL ) GDALClose( m_hDriver ); //Ne pas le faire sinon SegFault !!!! // if( m_poBands != NULL ) delete [] m_poBands; // if( m_poDataset != NULL ) delete m_poDataset; - if(m_poDataset != NULL) - { + if (m_poDataset != NULL) + { - GDALClose(m_poDataset); - m_poDataset = NULL; - } - if(m_poBands != NULL) - { - delete [] m_poBands; - } - GDALDestroyDriverManager(); + GDALClose(m_poDataset); + m_poDataset = NULL; + } + if (m_poBands != NULL) + { + delete [] m_poBands; } + GDALDestroyDriverManager(); +} // Tell only if the file can be read with GDAL. - bool GDALImageIO::CanReadFile(const char* file) - { +bool GDALImageIO::CanReadFile(const char* file) +{ // First check the extension - if( file == NULL ) - { - itkDebugMacro(<<"No filename specified."); - return false; - } - bool lCanRead(false); - - //Traitement particulier sur certain format o� l'on pr�f�re utiliser - // Format PNG -> lecture avec ITK (pas GDAL car certains tests sortent en erreurs) - itk::PNGImageIO::Pointer lPNGImageIO = itk::PNGImageIO::New(); - lCanRead = lPNGImageIO->CanReadFile(file); - if ( lCanRead == true) - { - return false; - } - itk::JPEGImageIO::Pointer lJPEGImageIO = itk::JPEGImageIO::New(); - lCanRead = lJPEGImageIO->CanReadFile(file); - if ( lCanRead == true) - { - return false; - } + if ( file == NULL ) + { + itkDebugMacro(<<"No filename specified."); + return false; + } + bool lCanRead(false); - // Regarde si c'est un r�pertoire -/* std::string lFileNameGdal; - otbMsgDevMacro(<<"GDALImageIO::CanReadFile()"); - bool found = GetGdalReadImageFileName(file,lFileNameGdal); - if( found == false ) - { + //Traitement particulier sur certain format o� l'on pr�f�re utiliser + // Format PNG -> lecture avec ITK (pas GDAL car certains tests sortent en erreurs) + itk::PNGImageIO::Pointer lPNGImageIO = itk::PNGImageIO::New(); + lCanRead = lPNGImageIO->CanReadFile(file); + if ( lCanRead == true) + { return false; } -*/ - std::string lFileNameGdal; - lFileNameGdal = std::string(file); + itk::JPEGImageIO::Pointer lJPEGImageIO = itk::JPEGImageIO::New(); + lCanRead = lJPEGImageIO->CanReadFile(file); + if ( lCanRead == true) + { + return false; + } + + // Regarde si c'est un r�pertoire + /* std::string lFileNameGdal; + otbMsgDevMacro(<<"GDALImageIO::CanReadFile()"); + bool found = GetGdalReadImageFileName(file,lFileNameGdal); + if( found == false ) + { + return false; + } + */ + std::string lFileNameGdal; + lFileNameGdal = std::string(file); - // Init GDAL parameters - GDALAllRegister(); + // Init GDAL parameters + GDALAllRegister(); // Open file with GDAL - m_poDataset = static_cast<GDALDataset *>(GDALOpen(lFileNameGdal.c_str(), GA_ReadOnly )); + m_poDataset = static_cast<GDALDataset *>(GDALOpen(lFileNameGdal.c_str(), GA_ReadOnly )); - if(m_poDataset==NULL) - { - fprintf( stderr, - "GDALOpen failed - %d\n%s\n", - CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); - - GDALDestroyDriverManager(); - CPLDumpSharedList( NULL ); - itkDebugMacro(<<"No dataset "); - otbMsgDevMacro(<<"Not CanReadFile GDAL"); - return false; - } - else - { - GDALClose(m_poDataset); - m_poDataset = NULL; - GDALDestroyDriverManager(); - CPLDumpSharedList( NULL ); + if (m_poDataset==NULL) + { + fprintf( stderr, + "GDALOpen failed - %d\n%s\n", + CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); - otbMsgDevMacro(<<"CanReadFile GDAL"); - return true; - } + GDALDestroyDriverManager(); + CPLDumpSharedList( NULL ); + itkDebugMacro(<<"No dataset "); + otbMsgDevMacro(<<"Not CanReadFile GDAL"); + return false; } - -// Used to print information about this object - void GDALImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const + else { - Superclass::PrintSelf(os, indent); - os << indent << "Compression Level : " << m_CompressionLevel << "\n"; + GDALClose(m_poDataset); + m_poDataset = NULL; + GDALDestroyDriverManager(); + CPLDumpSharedList( NULL ); + + otbMsgDevMacro(<<"CanReadFile GDAL"); + return true; } +} + +// Used to print information about this object +void GDALImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Compression Level : " << m_CompressionLevel << "\n"; +} // Read a 3D image (or event more bands)... not implemented yet - void GDALImageIO::ReadVolume(void*) - { - } +void GDALImageIO::ReadVolume(void*) +{ +} // Read image with GDAL - void GDALImageIO::Read(void* buffer) +void GDALImageIO::Read(void* buffer) +{ + std::streamoff step = static_cast<std::streamoff>(this->GetNumberOfComponents()); + unsigned char * p = static_cast<unsigned char *>(buffer); + if (p==NULL) { - std::streamoff step = static_cast<std::streamoff>(this->GetNumberOfComponents()); - unsigned char * p = static_cast<unsigned char *>(buffer); - if(p==NULL) - { - itkExceptionMacro(<<"Memory allocation error"); - return; - } + itkExceptionMacro(<<"Memory allocation error"); + return; + } - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] - - otbMsgDevMacro( <<" GDALImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - - std::streamoff lNbPixels = (static_cast<std::streamoff>(lNbColumns))*(static_cast<std::streamoff>(lNbLines)); - std::streamoff lBufferSize = static_cast<std::streamoff>(m_NbOctetPixel)*lNbPixels; - - otbMsgDevMacro( <<" Allocation buff size : "<<lNbPixels<<"*"<<m_NbOctetPixel<<" (NbOctetPixel) = "<<lBufferSize); - otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); - otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); - otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); - otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); - otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + + otbMsgDevMacro( <<" GDALImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + + std::streamoff lNbPixels = (static_cast<std::streamoff>(lNbColumns))*(static_cast<std::streamoff>(lNbLines)); + std::streamoff lBufferSize = static_cast<std::streamoff>(m_NbOctetPixel)*lNbPixels; + + otbMsgDevMacro( <<" Allocation buff size : "<<lNbPixels<<"*"<<m_NbOctetPixel<<" (NbOctetPixel) = "<<lBufferSize); + otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); + otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); + otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); + otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); + otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); //otbMsgDevMacro( <<" sizeof(pos_type) : "<<sizeof(pos_type)); //otbMsgDevMacro( <<" sizeof(off_type) : "<<sizeof(off_type)); - otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); + otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); - unsigned char* value = new unsigned char[lBufferSize]; - if(value==NULL) - { - itkExceptionMacro(<<"Memory allocation error"); - return; - } + unsigned char* value = new unsigned char[lBufferSize]; + if (value==NULL) + { + itkExceptionMacro(<<"Memory allocation error"); + return; + } + + CPLErr lCrGdal; + std::streamoff cpt(0); - CPLErr lCrGdal; - std::streamoff cpt(0); + if ( GDALDataTypeIsComplex(m_PxType) ) + { + otbMsgDevMacro( << " GDALDataTypeIsComplex begin "); + lCrGdal = m_poBands[0]->RasterIO( GF_Read,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); - if( GDALDataTypeIsComplex(m_PxType) ) + if (lCrGdal == CE_Failure) + { + itkExceptionMacro(<< "Error while reading image (GDAL format) " << m_FileName.c_str()<<"."); + } + cpt = 0; + for ( std::streamoff i=0; i < lBufferSize; i = i+static_cast<std::streamoff>(m_NbOctetPixel) ) { - otbMsgDevMacro( << " GDALDataTypeIsComplex begin "); - lCrGdal = m_poBands[0]->RasterIO( GF_Read,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); + memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(m_NbOctetPixel)); + cpt += static_cast<std::streamoff>(m_NbOctetPixel); + } + } + else + { + // Mise a jour du step + step = step * static_cast<std::streamoff>(m_NbOctetPixel); + for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) + { + lCrGdal = m_poBands[nbComponents]->RasterIO( GF_Read,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); if (lCrGdal == CE_Failure) { itkExceptionMacro(<< "Error while reading image (GDAL format) " << m_FileName.c_str()<<"."); } - cpt = 0; + // Recopie dans le buffer + cpt = static_cast<std::streamoff>(nbComponents)*static_cast<std::streamoff>(m_NbOctetPixel); for ( std::streamoff i=0; i < lBufferSize; i = i+static_cast<std::streamoff>(m_NbOctetPixel) ) { memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(m_NbOctetPixel)); - cpt += static_cast<std::streamoff>(m_NbOctetPixel); - } - } - else - { - // Mise a jour du step - step = step * static_cast<std::streamoff>(m_NbOctetPixel); - - for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) - { - lCrGdal = m_poBands[nbComponents]->RasterIO( GF_Read,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); - if (lCrGdal == CE_Failure) - { - itkExceptionMacro(<< "Error while reading image (GDAL format) " << m_FileName.c_str()<<"."); - } - // Recopie dans le buffer - cpt = static_cast<std::streamoff>(nbComponents)*static_cast<std::streamoff>(m_NbOctetPixel); - for ( std::streamoff i=0; i < lBufferSize; i = i+static_cast<std::streamoff>(m_NbOctetPixel) ) - { - memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(m_NbOctetPixel)); - cpt += step; - } + cpt += step; } } - - delete [] value; - value = NULL; - otbMsgDevMacro( << "GDALImageIO::Read() completed"); } - void GDALImageIO::ReadImageInformation() - { + delete [] value; + value = NULL; + otbMsgDevMacro( << "GDALImageIO::Read() completed"); +} + +void GDALImageIO::ReadImageInformation() +{ //std::ifstream file; - this->InternalReadImageInformation(); - } + this->InternalReadImageInformation(); +} - void GDALImageIO::InternalReadImageInformation() - { - int i; +void GDALImageIO::InternalReadImageInformation() +{ + int i; - if( m_FileName.empty() == true ) - { - itkExceptionMacro(<<"GDAl read : empty image file name file."); - } + if ( m_FileName.empty() == true ) + { + itkExceptionMacro(<<"GDAl read : empty image file name file."); + } - std::string lFileNameGdal = m_FileName; + std::string lFileNameGdal = m_FileName; // Init GDAL parameters - GDALAllRegister(); + GDALAllRegister(); // Get Dataset - if(m_poDataset != NULL) - { + if (m_poDataset != NULL) + { // delete m_poDataset; - GDALClose(m_poDataset); - m_poDataset = NULL; - } - otbMsgDevMacro( <<" lFileNameGdal : " << lFileNameGdal); - m_poDataset = static_cast<GDALDataset *>( GDALOpen(lFileNameGdal.c_str(), GA_ReadOnly )); - otbMsgDevMacro( <<" GCPCount (original): " << m_poDataset->GetGCPCount()); - if(m_poDataset==NULL) + GDALClose(m_poDataset); + m_poDataset = NULL; + } + otbMsgDevMacro( <<" lFileNameGdal : " << lFileNameGdal); + m_poDataset = static_cast<GDALDataset *>( GDALOpen(lFileNameGdal.c_str(), GA_ReadOnly )); + otbMsgDevMacro( <<" GCPCount (original): " << m_poDataset->GetGCPCount()); + if (m_poDataset==NULL) + { + itkExceptionMacro(<<"Gdal dataset is null."); + return; + } + + else + { + // Get image dimensions + m_width = m_poDataset->GetRasterXSize(); + m_height = m_poDataset->GetRasterYSize(); + + if ( (m_width==0) || (m_height==0)) { - itkExceptionMacro(<<"Gdal dataset is null."); - return; + itkExceptionMacro(<<"Dimension is undefined."); } - else { - // Get image dimensions - m_width = m_poDataset->GetRasterXSize(); - m_height = m_poDataset->GetRasterYSize(); - - if( (m_width==0) || (m_height==0)) - { - itkExceptionMacro(<<"Dimension is undefined."); - } - else - { // Set image dimensions into IO - m_Dimensions[0] = m_width; - m_Dimensions[1] = m_height; - otbMsgDevMacro(<<"Get Dimensions : x="<<m_Dimensions[0]<<" & y="<<m_Dimensions[1]); - } + m_Dimensions[0] = m_width; + m_Dimensions[1] = m_height; + otbMsgDevMacro(<<"Get Dimensions : x="<<m_Dimensions[0]<<" & y="<<m_Dimensions[1]); + } // Get Number of Bands - m_NbBands = m_poDataset->GetRasterCount(); - if(m_NbBands==0) - { + m_NbBands = m_poDataset->GetRasterCount(); + if (m_NbBands==0) + { //FIXME this happen in the case of a hdf file with SUBDATASETS // in this situation, at least the first dataset should be open (ideally all in an imagelist) // char** papszMetadata; @@ -350,801 +350,801 @@ namespace otb // std::cout << key << std::endl; // } - itkExceptionMacro(<<"Zero band found in the dataset"); - return; - } - this->SetNumberOfComponents(m_NbBands); + itkExceptionMacro(<<"Zero band found in the dataset"); + return; + } + this->SetNumberOfComponents(m_NbBands); - otbMsgDevMacro(<<"NbBands : "<<m_NbBands); - otbMsgDevMacro(<<"Nb of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro(<<"NbBands : "<<m_NbBands); + otbMsgDevMacro(<<"Nb of Components : "<<this->GetNumberOfComponents()); // Set the number of dimensions (verify for the dim ) - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); - otbMsgDevMacro(<<"Nb of Dimensions : "<<m_NumberOfDimensions); + otbMsgDevMacro(<<"Nb of Dimensions : "<<m_NumberOfDimensions); // Automatically set the Type to Binary for GDAL data - this->SetFileTypeToBinary(); + this->SetFileTypeToBinary(); - // Get all the Bands - m_poBands = new GDALRasterBand * [m_NbBands]; - if(m_poBands==NULL) - { - itkExceptionMacro(<<"Memory allocation error for the 'rasterBands'"); - return; - } - for(i=0; i<m_NbBands; i++) - m_poBands[i] = m_poDataset->GetRasterBand(i+1); + // Get all the Bands + m_poBands = new GDALRasterBand * [m_NbBands]; + if (m_poBands==NULL) + { + itkExceptionMacro(<<"Memory allocation error for the 'rasterBands'"); + return; + } + for (i=0; i<m_NbBands; i++) + m_poBands[i] = m_poDataset->GetRasterBand(i+1); // Get Data Type // Consider only the data type given by the first band!!!!! // Maybe be could changed (to check) - m_PxType = m_poBands[0]->GetRasterDataType(); + m_PxType = m_poBands[0]->GetRasterDataType(); // Following the data type given by GDAL we set it for ImageIO // BE CAREFUL !!!! At this time the complex data type are regarded // as integer data type in hope that ITK uses that kind of system // (take time to check !!) - if(m_PxType == GDT_Byte) - { - SetComponentType(UCHAR); - } - else if(m_PxType == GDT_UInt16) - { - SetComponentType(USHORT); - } - else if((m_PxType == GDT_Int16) || (m_PxType == GDT_CInt16) ) - { - SetComponentType(SHORT); - } - else if(m_PxType == GDT_UInt32) - { - SetComponentType(UINT); - } - else if((m_PxType == GDT_Int32) || (m_PxType == GDT_CInt32) ) - { - SetComponentType(INT); - } - else if((m_PxType == GDT_Float32) || (m_PxType == GDT_CFloat32) ) - { - SetComponentType(FLOAT); - } - else if((m_PxType == GDT_Float64) || (m_PxType == GDT_CFloat64) ) - { - SetComponentType(DOUBLE); - } - else - { - itkExceptionMacro(<<"Pixel type unknown"); - } + if (m_PxType == GDT_Byte) + { + SetComponentType(UCHAR); + } + else if (m_PxType == GDT_UInt16) + { + SetComponentType(USHORT); + } + else if ((m_PxType == GDT_Int16) || (m_PxType == GDT_CInt16) ) + { + SetComponentType(SHORT); + } + else if (m_PxType == GDT_UInt32) + { + SetComponentType(UINT); + } + else if ((m_PxType == GDT_Int32) || (m_PxType == GDT_CInt32) ) + { + SetComponentType(INT); + } + else if ((m_PxType == GDT_Float32) || (m_PxType == GDT_CFloat32) ) + { + SetComponentType(FLOAT); + } + else if ((m_PxType == GDT_Float64) || (m_PxType == GDT_CFloat64) ) + { + SetComponentType(DOUBLE); + } + else + { + itkExceptionMacro(<<"Pixel type unknown"); + } - if ( this->GetComponentType() == CHAR ) - { - m_NbOctetPixel = 1; - } - else if ( this->GetComponentType() == UCHAR ) - { - m_NbOctetPixel = 1; - } - else if ( this->GetComponentType() == USHORT ) - { - m_NbOctetPixel = 2; - } - else if ( this->GetComponentType() == SHORT ) - { - m_NbOctetPixel = 2; - } - else if ( this->GetComponentType() == INT ) - { - m_NbOctetPixel = 4; - } - else if ( this->GetComponentType() == UINT ) - { - m_NbOctetPixel = 4; - } - else if ( this->GetComponentType() == FLOAT ) - { - m_NbOctetPixel = 4; - } - else if ( this->GetComponentType() == DOUBLE ) - { - m_NbOctetPixel = 8; - } - else - { - m_NbOctetPixel = 1; - } + if ( this->GetComponentType() == CHAR ) + { + m_NbOctetPixel = 1; + } + else if ( this->GetComponentType() == UCHAR ) + { + m_NbOctetPixel = 1; + } + else if ( this->GetComponentType() == USHORT ) + { + m_NbOctetPixel = 2; + } + else if ( this->GetComponentType() == SHORT ) + { + m_NbOctetPixel = 2; + } + else if ( this->GetComponentType() == INT ) + { + m_NbOctetPixel = 4; + } + else if ( this->GetComponentType() == UINT ) + { + m_NbOctetPixel = 4; + } + else if ( this->GetComponentType() == FLOAT ) + { + m_NbOctetPixel = 4; + } + else if ( this->GetComponentType() == DOUBLE ) + { + m_NbOctetPixel = 8; + } + else + { + m_NbOctetPixel = 1; + } - /******************************************************************/ + /******************************************************************/ // Pixel Type always set to Scalar for GDAL ? maybe also to vector ? - // Modif Patrick: LIRE LES IMAGES COMPLEXES - if( GDALDataTypeIsComplex(m_PxType) ) + // Modif Patrick: LIRE LES IMAGES COMPLEXES + if ( GDALDataTypeIsComplex(m_PxType) ) + { + otbMsgDevMacro(<<"SetPixelType(COMPLEX)"); + m_NbOctetPixel = m_NbOctetPixel * 2; + this->SetNumberOfComponents( 2 ); + this->SetPixelType(COMPLEX); + // Is this necessary ? + //if(m_NbBands !=1) itkExceptionMacro(<<"GDALImageIO::InternalReadImageInformation() Can read only one band image "); + } + else + { + otbMsgDevMacro(<<"SetPixelType(NoCOMPLEX)"); + this-> SetNumberOfComponents(m_NbBands); + if ( this->GetNumberOfComponents() == 1 ) { - otbMsgDevMacro(<<"SetPixelType(COMPLEX)"); - m_NbOctetPixel = m_NbOctetPixel * 2; - this->SetNumberOfComponents( 2 ); - this->SetPixelType(COMPLEX); - // Is this necessary ? - //if(m_NbBands !=1) itkExceptionMacro(<<"GDALImageIO::InternalReadImageInformation() Can read only one band image "); + this->SetPixelType(SCALAR); } else { - otbMsgDevMacro(<<"SetPixelType(NoCOMPLEX)"); - this-> SetNumberOfComponents(m_NbBands); - if( this->GetNumberOfComponents() == 1 ) - { - this->SetPixelType(SCALAR); - } - else - { - this->SetPixelType(VECTOR); - } + this->SetPixelType(VECTOR); } - - otbMsgDevMacro(<<"m_PxType : "<<m_PxType); - otbMsgDevMacro(<<"Component Type : "<<m_ComponentType); - otbMsgDevMacro(<<"NbOctetPixel : "<<m_NbOctetPixel); - - } - /*----------------------------------------------------------------------*/ - /*-------------------------- METADATA ----------------------------------*/ - /*----------------------------------------------------------------------*/ + otbMsgDevMacro(<<"m_PxType : "<<m_PxType); + otbMsgDevMacro(<<"Component Type : "<<m_ComponentType); + otbMsgDevMacro(<<"NbOctetPixel : "<<m_NbOctetPixel); - // Now initialize the itk dictionary - itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); + } - /* -------------------------------------------------------------------- */ - /* Get Spacing */ - /* -------------------------------------------------------------------- */ + /*----------------------------------------------------------------------*/ + /*-------------------------- METADATA ----------------------------------*/ + /*----------------------------------------------------------------------*/ - // Default Spacing - m_Spacing[0]=1; - m_Spacing[1]=1; - if(m_NumberOfDimensions==3) - m_Spacing[2]=1; + // Now initialize the itk dictionary + itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); - char** papszMetadata; - papszMetadata = m_poDataset->GetMetadata( NULL ); + /* -------------------------------------------------------------------- */ + /* Get Spacing */ + /* -------------------------------------------------------------------- */ - /* -------------------------------------------------------------------- */ - /* Report general info. */ - /* -------------------------------------------------------------------- */ - GDALDriverH hDriver; + // Default Spacing + m_Spacing[0]=1; + m_Spacing[1]=1; + if (m_NumberOfDimensions==3) + m_Spacing[2]=1; - hDriver = m_poDataset->GetDriver(); + char** papszMetadata; + papszMetadata = m_poDataset->GetMetadata( NULL ); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::DriverShortNameKey, - static_cast<std::string>( GDALGetDriverShortName( hDriver ) ) ); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::DriverLongNameKey, - static_cast<std::string>( GDALGetDriverLongName( hDriver ) ) ); - otbMsgDevMacro( <<" GDAL Driver short name: " << GDALGetDriverShortName( hDriver )); - otbMsgDevMacro( <<" GDAL Driver long name: " << GDALGetDriverLongName( hDriver )); - /* -------------------------------------------------------------------- */ - /* Get the projection coordinate system of the image : ProjectionRef */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Report general info. */ + /* -------------------------------------------------------------------- */ + GDALDriverH hDriver; - if( m_poDataset->GetProjectionRef() != NULL ) - { - OGRSpatialReference* pSR; - const char * pszProjection = NULL; + hDriver = m_poDataset->GetDriver(); - pSR = new OGRSpatialReference( pszProjection ); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::DriverShortNameKey, + static_cast<std::string>( GDALGetDriverShortName( hDriver ) ) ); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::DriverLongNameKey, + static_cast<std::string>( GDALGetDriverLongName( hDriver ) ) ); + otbMsgDevMacro( <<" GDAL Driver short name: " << GDALGetDriverShortName( hDriver )); + otbMsgDevMacro( <<" GDAL Driver long name: " << GDALGetDriverLongName( hDriver )); - pszProjection = m_poDataset->GetProjectionRef(); + /* -------------------------------------------------------------------- */ + /* Get the projection coordinate system of the image : ProjectionRef */ + /* -------------------------------------------------------------------- */ - if( pSR->importFromWkt( (char **)(&pszProjection) ) == CE_None ) - { - char * pszPrettyWkt = NULL; + if ( m_poDataset->GetProjectionRef() != NULL ) + { + OGRSpatialReference* pSR; + const char * pszProjection = NULL; - pSR->exportToPrettyWkt( &pszPrettyWkt, FALSE ); - itk::EncapsulateMetaData<std::string> ( dict, MetaDataKey::ProjectionRefKey, - static_cast<std::string>( pszPrettyWkt ) ); + pSR = new OGRSpatialReference( pszProjection ); - CPLFree( pszPrettyWkt ); - } - else - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, - static_cast<std::string>( m_poDataset->GetProjectionRef() ) ); + pszProjection = m_poDataset->GetProjectionRef(); - if (pSR != NULL) - { - delete pSR; - pSR = NULL; - } + if ( pSR->importFromWkt( (char **)(&pszProjection) ) == CE_None ) + { + char * pszPrettyWkt = NULL; - } + pSR->exportToPrettyWkt( &pszPrettyWkt, FALSE ); + itk::EncapsulateMetaData<std::string> ( dict, MetaDataKey::ProjectionRefKey, + static_cast<std::string>( pszPrettyWkt ) ); - /* -------------------------------------------------------------------- */ - /* Get the GCP projection coordinates of the image : GCPProjection */ - /* -------------------------------------------------------------------- */ + CPLFree( pszPrettyWkt ); + } + else + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, + static_cast<std::string>( m_poDataset->GetProjectionRef() ) ); - unsigned int gcpCount = 0; - gcpCount = m_poDataset->GetGCPCount(); - if( gcpCount > 0 ) + if (pSR != NULL) { - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::GCPProjectionKey, - static_cast<std::string>( m_poDataset->GetGCPProjection() ) ); + delete pSR; + pSR = NULL; + } - std::string key; + } - itk::EncapsulateMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey,gcpCount); + /* -------------------------------------------------------------------- */ + /* Get the GCP projection coordinates of the image : GCPProjection */ + /* -------------------------------------------------------------------- */ + unsigned int gcpCount = 0; + gcpCount = m_poDataset->GetGCPCount(); + if ( gcpCount > 0 ) + { + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::GCPProjectionKey, + static_cast<std::string>( m_poDataset->GetGCPProjection() ) ); - otbMsgDevMacro( <<" GCPCount: " << m_poDataset->GetGCPCount()); - for( unsigned int cpt = 0; cpt < gcpCount; cpt++ ) - { - const GDAL_GCP *psGCP; - psGCP = m_poDataset->GetGCPs() + cpt; + std::string key; - OTB_GCP pOtbGCP(psGCP); + itk::EncapsulateMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey,gcpCount); - // Complete the key with the GCP number : GCP_i - ::itk::OStringStream lStream; - lStream << MetaDataKey::GCPParametersKey << cpt; - key = lStream.str(); - itk::EncapsulateMetaData<OTB_GCP>(dict, key, pOtbGCP); + otbMsgDevMacro( <<" GCPCount: " << m_poDataset->GetGCPCount()); + for ( unsigned int cpt = 0; cpt < gcpCount; cpt++ ) + { + const GDAL_GCP *psGCP; + psGCP = m_poDataset->GetGCPs() + cpt; - } + OTB_GCP pOtbGCP(psGCP); + // Complete the key with the GCP number : GCP_i + ::itk::OStringStream lStream; + lStream << MetaDataKey::GCPParametersKey << cpt; + key = lStream.str(); + itk::EncapsulateMetaData<OTB_GCP>(dict, key, pOtbGCP); } - /* -------------------------------------------------------------------- */ - /* Get the six coefficients of affine geoTtransform */ - /* -------------------------------------------------------------------- */ - double adfGeoTransform[6]; - VectorType VadfGeoTransform; - if( m_poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) - { - for(int cpt = 0; cpt < 6; cpt++ ) VadfGeoTransform.push_back(adfGeoTransform[cpt]); + } - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, VadfGeoTransform); + /* -------------------------------------------------------------------- */ + /* Get the six coefficients of affine geoTtransform */ + /* -------------------------------------------------------------------- */ - /// retrieve orgin and spacing from the geo transform - m_Origin[0]=VadfGeoTransform[0]; - m_Origin[1]=VadfGeoTransform[3]; - m_Spacing[0]=VadfGeoTransform[1]; - m_Spacing[1]=VadfGeoTransform[5]; - } + double adfGeoTransform[6]; + VectorType VadfGeoTransform; - /* -------------------------------------------------------------------- */ - /* Report metadata. */ - /* -------------------------------------------------------------------- */ + if ( m_poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) + { + for (int cpt = 0; cpt < 6; cpt++ ) VadfGeoTransform.push_back(adfGeoTransform[cpt]); - papszMetadata = m_poDataset->GetMetadata(NULL); - if( CSLCount(papszMetadata) > 0 ) - { - std::string key; + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, VadfGeoTransform); - for( int cpt = 0; papszMetadata[cpt] != NULL; cpt++ ) - { - ::itk::OStringStream lStream; - lStream << MetaDataKey::MetadataKey << cpt; - key = lStream.str(); + /// retrieve orgin and spacing from the geo transform + m_Origin[0]=VadfGeoTransform[0]; + m_Origin[1]=VadfGeoTransform[3]; + m_Spacing[0]=VadfGeoTransform[1]; + m_Spacing[1]=VadfGeoTransform[5]; + } - itk::EncapsulateMetaData<std::string>(dict, key, - static_cast<std::string>( papszMetadata[cpt] ) ); - } - } + /* -------------------------------------------------------------------- */ + /* Report metadata. */ + /* -------------------------------------------------------------------- */ - /* -------------------------------------------------------------------- */ - /* Report subdatasets. */ - /* -------------------------------------------------------------------- */ + papszMetadata = m_poDataset->GetMetadata(NULL); + if ( CSLCount(papszMetadata) > 0 ) + { + std::string key; - papszMetadata = m_poDataset->GetMetadata("SUBDATASETS"); - if( CSLCount(papszMetadata) > 0 ) + for ( int cpt = 0; papszMetadata[cpt] != NULL; cpt++ ) { - std::string key; + ::itk::OStringStream lStream; + lStream << MetaDataKey::MetadataKey << cpt; + key = lStream.str(); - for( int cpt = 0; papszMetadata[cpt] != NULL; cpt++ ) - { - ::itk::OStringStream lStream; - lStream << MetaDataKey::SubMetadataKey << cpt; - key = lStream.str(); + itk::EncapsulateMetaData<std::string>(dict, key, + static_cast<std::string>( papszMetadata[cpt] ) ); + } + } - itk::EncapsulateMetaData<std::string>(dict, key, - static_cast<std::string>( papszMetadata[cpt] ) ); - } + /* -------------------------------------------------------------------- */ + /* Report subdatasets. */ + /* -------------------------------------------------------------------- */ + + papszMetadata = m_poDataset->GetMetadata("SUBDATASETS"); + if ( CSLCount(papszMetadata) > 0 ) + { + std::string key; + + for ( int cpt = 0; papszMetadata[cpt] != NULL; cpt++ ) + { + ::itk::OStringStream lStream; + lStream << MetaDataKey::SubMetadataKey << cpt; + key = lStream.str(); + + itk::EncapsulateMetaData<std::string>(dict, key, + static_cast<std::string>( papszMetadata[cpt] ) ); } + } - /* -------------------------------------------------------------------- */ - /* Report corners */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Report corners */ + /* -------------------------------------------------------------------- */ - double GeoX(0), GeoY(0); - VectorType VGeo; + double GeoX(0), GeoY(0); + VectorType VGeo; - GDALInfoReportCorner( "Upper Left", 0.0, 0.0, GeoX, GeoY ); - VGeo.push_back(GeoX); - VGeo.push_back(GeoY); + GDALInfoReportCorner( "Upper Left", 0.0, 0.0, GeoX, GeoY ); + VGeo.push_back(GeoX); + VGeo.push_back(GeoY); - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, VGeo); + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, VGeo); - VGeo.clear(); + VGeo.clear(); - GDALInfoReportCorner( "Upper Right", m_width, 0.0, GeoX, GeoY ); - VGeo.push_back(GeoX); - VGeo.push_back(GeoY); + GDALInfoReportCorner( "Upper Right", m_width, 0.0, GeoX, GeoY ); + VGeo.push_back(GeoX); + VGeo.push_back(GeoY); - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, VGeo); + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, VGeo); - VGeo.clear(); + VGeo.clear(); - GDALInfoReportCorner( "Lower Left", 0.0, m_height, GeoX, GeoY); - VGeo.push_back(GeoX); - VGeo.push_back(GeoY); + GDALInfoReportCorner( "Lower Left", 0.0, m_height, GeoX, GeoY); + VGeo.push_back(GeoX); + VGeo.push_back(GeoY); - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, VGeo); + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, VGeo); - VGeo.clear(); + VGeo.clear(); - GDALInfoReportCorner( "Lower Right", m_width, m_height, GeoX, GeoY ); - VGeo.push_back(GeoX); - VGeo.push_back(GeoY); + GDALInfoReportCorner( "Lower Right", m_width, m_height, GeoX, GeoY ); + VGeo.push_back(GeoX); + VGeo.push_back(GeoY); - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, VGeo); + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, VGeo); - VGeo.clear(); + VGeo.clear(); - /* -------------------------------------------------------------------- */ - /* Color Table */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Color Table */ + /* -------------------------------------------------------------------- */ - for(int iBand = 0; iBand <m_poDataset->GetRasterCount(); iBand++ ) + for (int iBand = 0; iBand <m_poDataset->GetRasterCount(); iBand++ ) + { + GDALColorTableH hTable; + GDALRasterBandH hBand; + hBand=GDALGetRasterBand(m_poDataset,iBand+1); + if (GDALGetRasterColorInterpretation(hBand)==GCI_PaletteIndex&&(hTable=GDALGetRasterColorTable(hBand))!=NULL) { - GDALColorTableH hTable; - GDALRasterBandH hBand; - hBand=GDALGetRasterBand(m_poDataset,iBand+1); - if(GDALGetRasterColorInterpretation(hBand)==GCI_PaletteIndex&&(hTable=GDALGetRasterColorTable(hBand))!=NULL) - { - unsigned int ColorEntryCount=GDALGetColorEntryCount(hTable); + unsigned int ColorEntryCount=GDALGetColorEntryCount(hTable); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ColorTableNameKey, - static_cast<std::string>( GDALGetPaletteInterpretationName( - GDALGetPaletteInterpretation( hTable ) ) ) ); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ColorTableNameKey, + static_cast<std::string>( GDALGetPaletteInterpretationName( + GDALGetPaletteInterpretation( hTable ) ) ) ); - itk::EncapsulateMetaData<unsigned int>(dict, MetaDataKey::ColorEntryCountKey, ColorEntryCount); + itk::EncapsulateMetaData<unsigned int>(dict, MetaDataKey::ColorEntryCountKey, ColorEntryCount); - for(int i = 0; i < GDALGetColorEntryCount( hTable ); i++ ) - { - GDALColorEntry sEntry; - VectorType VColorEntry; + for (int i = 0; i < GDALGetColorEntryCount( hTable ); i++ ) + { + GDALColorEntry sEntry; + VectorType VColorEntry; - GDALGetColorEntryAsRGB( hTable, i, &sEntry ); + GDALGetColorEntryAsRGB( hTable, i, &sEntry ); - VColorEntry.push_back(sEntry.c1); - VColorEntry.push_back(sEntry.c2); - VColorEntry.push_back(sEntry.c3); - VColorEntry.push_back(sEntry.c4); + VColorEntry.push_back(sEntry.c1); + VColorEntry.push_back(sEntry.c2); + VColorEntry.push_back(sEntry.c3); + VColorEntry.push_back(sEntry.c4); - itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::ColorEntryAsRGBKey, VColorEntry); + itk::EncapsulateMetaData<VectorType>(dict, MetaDataKey::ColorEntryAsRGBKey, VColorEntry); - } } } - otbMsgDebugMacro( <<"Driver to read: GDAL"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); } - - bool GDALImageIO::CanWriteFile( const char* name ) + otbMsgDebugMacro( <<"Driver to read: GDAL"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); +} + +bool GDALImageIO::CanWriteFile( const char* name ) +{ + // First check the extension + if ( name == NULL ) { - // First check the extension - if( name == NULL ) - { - itkDebugMacro(<<"No filename specified."); - return false; - } - - //Traitement particulier sur certain format o� l'on pr�f�re utiliser - // Format PNG -> lecture avec ITK (pas GDAL) -/* itk::PNGImageIO::Pointer lPNGImageIO = itk::PNGImageIO::New(); - lCanWrite = lPNGImageIO->CanWriteFile(name); - if ( lCanWrite == true) - { + itkDebugMacro(<<"No filename specified."); return false; } -*/ - // Recuperation du type a partir du nom de fichier - std::string extGDAL = TypeConversion(name); - if (extGDAL=="NOT-FOUND") - { + + //Traitement particulier sur certain format o� l'on pr�f�re utiliser + // Format PNG -> lecture avec ITK (pas GDAL) + /* itk::PNGImageIO::Pointer lPNGImageIO = itk::PNGImageIO::New(); + lCanWrite = lPNGImageIO->CanWriteFile(name); + if ( lCanWrite == true) + { return false; } + */ + // Recuperation du type a partir du nom de fichier + std::string extGDAL = TypeConversion(name); + if (extGDAL=="NOT-FOUND") + { + return false; + } - return true; + return true; - } +} - /** TODO : Methode Write non implementee */ - void GDALImageIO::Write(const void* buffer) +/** TODO : Methode Write non implementee */ +void GDALImageIO::Write(const void* buffer) +{ + if ( m_FlagWriteImageInformation == true ) { - if( m_FlagWriteImageInformation == true ) - { - this->InternalWriteImageInformation(); - m_FlagWriteImageInformation = false; - } + this->InternalWriteImageInformation(); + m_FlagWriteImageInformation = false; + } - std::streamoff step = static_cast<std::streamoff>(this->GetNumberOfComponents()); - const unsigned char *p = static_cast<const unsigned char *>(buffer); - std::streamoff cpt(0); - if(p==NULL) - { - itkExceptionMacro(<<"GDAL : Bad alloc"); - return; - } + std::streamoff step = static_cast<std::streamoff>(this->GetNumberOfComponents()); + const unsigned char *p = static_cast<const unsigned char *>(buffer); + std::streamoff cpt(0); + if (p==NULL) + { + itkExceptionMacro(<<"GDAL : Bad alloc"); + return; + } - unsigned int lNbLines = this->GetIORegion().GetSize()[1]; - unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + unsigned int lNbLines = this->GetIORegion().GetSize()[1]; + unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] // Cas particuliers : on controle que si la r�gion � �crire est de la m�me dimension que l'image enti�re, // on commence l'offset � 0 (lorsque que l'on est pas en "Streaming") - if( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) - { - otbMsgDevMacro(<<"Forcing IORegion offset at 0"); - lFirstLine = 0; - lFirstColumn = 0; - } + if ( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) + { + otbMsgDevMacro(<<"Forcing IORegion offset at 0"); + lFirstLine = 0; + lFirstColumn = 0; + } - otbMsgDevMacro( << "GDALImageIO::Write() IORegion Start["<<this->GetIORegion().GetIndex()[0]<<","<<this->GetIORegion().GetIndex()[1]<<"] Size ["<<this->GetIORegion().GetSize()[0]<<","<<this->GetIORegion().GetSize()[1]<<"] on Image size ["<<m_Dimensions[0]<<","<<m_Dimensions[1]<<"]"); + otbMsgDevMacro( << "GDALImageIO::Write() IORegion Start["<<this->GetIORegion().GetIndex()[0]<<","<<this->GetIORegion().GetIndex()[1]<<"] Size ["<<this->GetIORegion().GetSize()[0]<<","<<this->GetIORegion().GetSize()[1]<<"] on Image size ["<<m_Dimensions[0]<<","<<m_Dimensions[1]<<"]"); - std::streamoff lNbPixels = static_cast<std::streamoff>(lNbColumns)*static_cast<std::streamoff>(lNbLines); - std::streamoff lBufferSize = static_cast<std::streamoff>(m_NbOctetPixel)*lNbPixels; - otbMsgDevMacro( <<" BufferSize allocated : "<< lBufferSize); + std::streamoff lNbPixels = static_cast<std::streamoff>(lNbColumns)*static_cast<std::streamoff>(lNbLines); + std::streamoff lBufferSize = static_cast<std::streamoff>(m_NbOctetPixel)*lNbPixels; + otbMsgDevMacro( <<" BufferSize allocated : "<< lBufferSize); - unsigned char* value = new unsigned char[lBufferSize]; - if(value==NULL) - { - itkExceptionMacro(<<"Memory allocation error"); - return; - } + unsigned char* value = new unsigned char[lBufferSize]; + if (value==NULL) + { + itkExceptionMacro(<<"Memory allocation error"); + return; + } - // Mise a jour du step - step = step * static_cast<std::streamoff>(m_NbOctetPixel); + // Mise a jour du step + step = step * static_cast<std::streamoff>(m_NbOctetPixel); - CPLErr lCrGdal; + CPLErr lCrGdal; - for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) - { - cpt = static_cast<std::streamoff>(nbComponents)* static_cast<std::streamoff>(m_NbOctetPixel); + for (unsigned int nbComponents = 0; nbComponents < this->GetNumberOfComponents(); nbComponents++) + { + cpt = static_cast<std::streamoff>(nbComponents)* static_cast<std::streamoff>(m_NbOctetPixel); - for ( std::streamoff i=0; i < lBufferSize; i = i+static_cast<std::streamoff>(m_NbOctetPixel) ) - { - memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(m_NbOctetPixel)); - cpt += step; - } - otbMsgDevMacro( << "NbBytes/pix : " << m_NbOctetPixel << " pxType : " << m_PxType); - otbMsgDevMacro( << "FirstCol : " << lFirstColumn << " FirsteLine : " << lFirstLine); - otbMsgDevMacro( << "NbCol : " << lNbColumns << " NbLines : " << lNbLines); - GDALRasterBand *poBand; - poBand = m_poBands[nbComponents]; //m_poDataset->GetRasterBand(nbComponents+1); + for ( std::streamoff i=0; i < lBufferSize; i = i+static_cast<std::streamoff>(m_NbOctetPixel) ) + { + memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(m_NbOctetPixel)); + cpt += step; + } + otbMsgDevMacro( << "NbBytes/pix : " << m_NbOctetPixel << " pxType : " << m_PxType); + otbMsgDevMacro( << "FirstCol : " << lFirstColumn << " FirsteLine : " << lFirstLine); + otbMsgDevMacro( << "NbCol : " << lNbColumns << " NbLines : " << lNbLines); + GDALRasterBand *poBand; + poBand = m_poBands[nbComponents]; //m_poDataset->GetRasterBand(nbComponents+1); // lCrGdal = poBand->RasterIO(GF_Write,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); - lCrGdal = m_poBands[nbComponents]->RasterIO(GF_Write,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); - if (lCrGdal == CE_Failure) - { - itkExceptionMacro(<< "Error while writing image (GDAL format) " << m_FileName.c_str()<<"."); - } + lCrGdal = m_poBands[nbComponents]->RasterIO(GF_Write,lFirstColumn,lFirstLine,lNbColumns, lNbLines, value , lNbColumns, lNbLines, m_PxType,0, 0 ); + if (lCrGdal == CE_Failure) + { + itkExceptionMacro(<< "Error while writing image (GDAL format) " << m_FileName.c_str()<<"."); } + } - delete [] value; - value = NULL; + delete [] value; + value = NULL; - m_poDataset->FlushCache(); + m_poDataset->FlushCache(); - otbMsgDevMacro( << "GDALImageIO::Write() terminee"); + otbMsgDevMacro( << "GDALImageIO::Write() terminee"); - } +} - /** TODO : Methode WriteImageInformation non implementee */ - void GDALImageIO::WriteImageInformation() - { +/** TODO : Methode WriteImageInformation non implementee */ +void GDALImageIO::WriteImageInformation() +{ - } +} - void GDALImageIO::InternalWriteImageInformation() - { +void GDALImageIO::InternalWriteImageInformation() +{ - char **papszOptions = NULL; - std::string extGDAL; - m_NbBands = this->GetNumberOfComponents(); + char **papszOptions = NULL; + std::string extGDAL; + m_NbBands = this->GetNumberOfComponents(); - if( (m_Dimensions[0]==0) && (m_Dimensions[1]==0)) - { - itkExceptionMacro(<<"Dimensions are not defined."); - } + if ( (m_Dimensions[0]==0) && (m_Dimensions[1]==0)) + { + itkExceptionMacro(<<"Dimensions are not defined."); + } - if ( this->GetComponentType() == CHAR ) - { - m_NbOctetPixel = 1; - m_PxType = GDT_Byte; - } - else if ( this->GetComponentType() == UCHAR ) - { - m_NbOctetPixel = 1; - m_PxType = GDT_Byte; - } - else if ( this->GetComponentType() == USHORT ) - { - m_NbOctetPixel = 2; - m_PxType = GDT_UInt16; - } - else if ( this->GetComponentType() == SHORT ) - { - m_NbOctetPixel = 2; - m_PxType = GDT_Int16; - } - else if ( this->GetComponentType() == INT ) - { - m_NbOctetPixel = 4; - m_PxType = GDT_Int32; - } - else if ( this->GetComponentType() == UINT ) - { - m_NbOctetPixel = 4; - m_PxType = GDT_UInt32; - } - else if ( this->GetComponentType() == FLOAT ) - { - m_NbOctetPixel = 4; - m_PxType = GDT_Float32; - } - else if ( this->GetComponentType() == DOUBLE ) - { - m_NbOctetPixel = 8; - m_PxType = GDT_Float64; - } - else - { - m_NbOctetPixel = 1; - m_PxType = GDT_Byte; - } + if ( this->GetComponentType() == CHAR ) + { + m_NbOctetPixel = 1; + m_PxType = GDT_Byte; + } + else if ( this->GetComponentType() == UCHAR ) + { + m_NbOctetPixel = 1; + m_PxType = GDT_Byte; + } + else if ( this->GetComponentType() == USHORT ) + { + m_NbOctetPixel = 2; + m_PxType = GDT_UInt16; + } + else if ( this->GetComponentType() == SHORT ) + { + m_NbOctetPixel = 2; + m_PxType = GDT_Int16; + } + else if ( this->GetComponentType() == INT ) + { + m_NbOctetPixel = 4; + m_PxType = GDT_Int32; + } + else if ( this->GetComponentType() == UINT ) + { + m_NbOctetPixel = 4; + m_PxType = GDT_UInt32; + } + else if ( this->GetComponentType() == FLOAT ) + { + m_NbOctetPixel = 4; + m_PxType = GDT_Float32; + } + else if ( this->GetComponentType() == DOUBLE ) + { + m_NbOctetPixel = 8; + m_PxType = GDT_Float64; + } + else + { + m_NbOctetPixel = 1; + m_PxType = GDT_Byte; + } - // Automatically set the Type to Binary for GDAL data - this->SetFileTypeToBinary(); + // Automatically set the Type to Binary for GDAL data + this->SetFileTypeToBinary(); - GDALAllRegister(); + GDALAllRegister(); - extGDAL = TypeConversion(m_FileName); - if (extGDAL=="NOT-FOUND") - { - itkExceptionMacro(<< "GDAL Writing failed : the image file name '"<<m_FileName.c_str()<<"' is not reconized by GDAL."); - } + extGDAL = TypeConversion(m_FileName); + if (extGDAL=="NOT-FOUND") + { + itkExceptionMacro(<< "GDAL Writing failed : the image file name '"<<m_FileName.c_str()<<"' is not reconized by GDAL."); + } - m_hDriver = GetGDALDriverManager()->GetDriverByName(extGDAL.c_str()); - if (m_hDriver == NULL) - { - itkExceptionMacro(<< "GDAL Writing failed : Driver not reconized"); - } - std::string realFileName = GetGdalWriteImageFileName(extGDAL, m_FileName); + m_hDriver = GetGDALDriverManager()->GetDriverByName(extGDAL.c_str()); + if (m_hDriver == NULL) + { + itkExceptionMacro(<< "GDAL Writing failed : Driver not reconized"); + } + std::string realFileName = GetGdalWriteImageFileName(extGDAL, m_FileName); - if(m_poDataset != NULL) - { - GDALClose(m_poDataset); - m_poDataset = NULL; - } - m_poDataset = m_hDriver->Create( realFileName.c_str(), m_Dimensions[0],m_Dimensions[1],m_NbBands,m_PxType, papszOptions ); - if (m_poDataset == NULL) - { - itkExceptionMacro(<< "GDAL Writing failed : Impossible to create the image file name '"<<realFileName.c_str()<<"'."); - } + if (m_poDataset != NULL) + { + GDALClose(m_poDataset); + m_poDataset = NULL; + } + m_poDataset = m_hDriver->Create( realFileName.c_str(), m_Dimensions[0],m_Dimensions[1],m_NbBands,m_PxType, papszOptions ); + if (m_poDataset == NULL) + { + itkExceptionMacro(<< "GDAL Writing failed : Impossible to create the image file name '"<<realFileName.c_str()<<"'."); + } - // Get all the Bands - m_poBands = new GDALRasterBand* [m_NbBands]; + // Get all the Bands + m_poBands = new GDALRasterBand* [m_NbBands]; - if(m_poBands==NULL) - { - itkExceptionMacro(<<"Memory allocation error for 'rasterBands'"); - } - for(int i=0; i<m_NbBands; i++) - { - m_poBands[i] = m_poDataset->GetRasterBand(i+1); - } + if (m_poBands==NULL) + { + itkExceptionMacro(<<"Memory allocation error for 'rasterBands'"); + } + for (int i=0; i<m_NbBands; i++) + { + m_poBands[i] = m_poDataset->GetRasterBand(i+1); + } - otbMsgDebugMacro( <<"Driver to write: GDAL - "<<extGDAL); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" GDAL file name : "<< realFileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<"Driver to write: GDAL - "<<extGDAL); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" GDAL file name : "<< realFileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); // JULIEN: ADDING SUPPORT FOR METADATA WRITING. - /*----------------------------------------------------------------------*/ - /*-------------------------- METADATA ----------------------------------*/ - /*----------------------------------------------------------------------*/ + /*----------------------------------------------------------------------*/ + /*-------------------------- METADATA ----------------------------------*/ + /*----------------------------------------------------------------------*/ // Now initialize the itk dictionary - itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); - char** papszMetadata; - papszMetadata = m_poDataset->GetMetadata( NULL ); - itk::OStringStream oss; + itk::MetaDataDictionary & dict = this->GetMetaDataDictionary(); + char** papszMetadata; + papszMetadata = m_poDataset->GetMetadata( NULL ); + itk::OStringStream oss; - /* -------------------------------------------------------------------- */ - /* Set the GCPs */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Set the GCPs */ + /* -------------------------------------------------------------------- */ - unsigned int gcpCount = 0; - itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, gcpCount); + unsigned int gcpCount = 0; + itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, gcpCount); - if(gcpCount>0) - { + if (gcpCount>0) + { - GDAL_GCP * gdalGcps = new GDAL_GCP[gcpCount]; + GDAL_GCP * gdalGcps = new GDAL_GCP[gcpCount]; - for(unsigned int gcpIndex = 0; gcpIndex < gcpCount;++gcpIndex) - { - //Build the GCP string in the form of GCP_n - itk::OStringStream lStream; - lStream << MetaDataKey::GCPParametersKey << gcpIndex; - std::string key = lStream.str(); - - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - - gdalGcps[gcpIndex].pszId = const_cast<char *>(gcp.m_Id.c_str()); - gdalGcps[gcpIndex].pszInfo = const_cast<char *>(gcp.m_Info.c_str()); - gdalGcps[gcpIndex].dfGCPPixel = gcp.m_GCPCol; - gdalGcps[gcpIndex].dfGCPLine = gcp.m_GCPRow; - gdalGcps[gcpIndex].dfGCPX = gcp.m_GCPX; - gdalGcps[gcpIndex].dfGCPY = gcp.m_GCPY; - gdalGcps[gcpIndex].dfGCPZ = gcp.m_GCPZ; + for (unsigned int gcpIndex = 0; gcpIndex < gcpCount;++gcpIndex) + { + //Build the GCP string in the form of GCP_n + itk::OStringStream lStream; + lStream << MetaDataKey::GCPParametersKey << gcpIndex; + std::string key = lStream.str(); + + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + + gdalGcps[gcpIndex].pszId = const_cast<char *>(gcp.m_Id.c_str()); + gdalGcps[gcpIndex].pszInfo = const_cast<char *>(gcp.m_Info.c_str()); + gdalGcps[gcpIndex].dfGCPPixel = gcp.m_GCPCol; + gdalGcps[gcpIndex].dfGCPLine = gcp.m_GCPRow; + gdalGcps[gcpIndex].dfGCPX = gcp.m_GCPX; + gdalGcps[gcpIndex].dfGCPY = gcp.m_GCPY; + gdalGcps[gcpIndex].dfGCPZ = gcp.m_GCPZ; - } + } - std::string gcpProjectionRef; - itk::ExposeMetaData<std::string>(dict, MetaDataKey::GCPProjectionKey, gcpProjectionRef ); - m_poDataset->SetGCPs(gcpCount,gdalGcps,gcpProjectionRef.c_str()); + std::string gcpProjectionRef; + itk::ExposeMetaData<std::string>(dict, MetaDataKey::GCPProjectionKey, gcpProjectionRef ); + m_poDataset->SetGCPs(gcpCount,gdalGcps,gcpProjectionRef.c_str()); - delete [] gdalGcps; - } + delete [] gdalGcps; + } - /* -------------------------------------------------------------------- */ - /* Set the projection coordinate system of the image : ProjectionRef */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Set the projection coordinate system of the image : ProjectionRef */ + /* -------------------------------------------------------------------- */ - std::string projectionRef; - itk::ExposeMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); - if(! projectionRef.empty()) - { - m_poDataset->SetProjection(projectionRef.c_str()); - } + std::string projectionRef; + itk::ExposeMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); + if (! projectionRef.empty()) + { + m_poDataset->SetProjection(projectionRef.c_str()); + } - /* -------------------------------------------------------------------- */ - /* Set the six coefficients of affine geoTtransform */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Set the six coefficients of affine geoTtransform */ + /* -------------------------------------------------------------------- */ - double * geoTransform = new double[6]; - /// Reporting origin and spacing - geoTransform[0]=m_Origin[0]; - geoTransform[3]=m_Origin[1]; - geoTransform[1]=m_Spacing[0]; - geoTransform[5]=m_Spacing[1]; + double * geoTransform = new double[6]; + /// Reporting origin and spacing + geoTransform[0]=m_Origin[0]; + geoTransform[3]=m_Origin[1]; + geoTransform[1]=m_Spacing[0]; + geoTransform[5]=m_Spacing[1]; - // FIXME: Here component 1 and 4 should be replaced by the orientation parameters - geoTransform[2]=0.; - geoTransform[4]=0.; - m_poDataset->SetGeoTransform(geoTransform); - delete [] geoTransform; + // FIXME: Here component 1 and 4 should be replaced by the orientation parameters + geoTransform[2]=0.; + geoTransform[4]=0.; + m_poDataset->SetGeoTransform(geoTransform); + delete [] geoTransform; - /* -------------------------------------------------------------------- */ - /* Report metadata. */ - /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + /* Report metadata. */ + /* -------------------------------------------------------------------- */ - std::string svalue=""; - std::vector<std::string> keys = dict.GetKeys(); - MetaDataKey key; + std::string svalue=""; + std::vector<std::string> keys = dict.GetKeys(); + MetaDataKey key; - for (unsigned int itkey=0; itkey<keys.size(); itkey++) + for (unsigned int itkey=0; itkey<keys.size(); itkey++) + { + if (keys[itkey].compare(0,key.MetadataKey.length(),key.MetadataKey)==0) { - if(keys[itkey].compare(0,key.MetadataKey.length(),key.MetadataKey)==0) - { - itk::ExposeMetaData<std::string>(dict,keys[itkey],svalue); - unsigned int equalityPos = svalue.find_first_of('='); - std::string tag = svalue.substr(0,equalityPos); - std::string value = svalue.substr(equalityPos+1); - otbMsgDevMacro(<<"Metadata: "<<tag<<"="<<value); - m_poDataset->SetMetadataItem(tag.c_str(),value.c_str(),NULL); - } + itk::ExposeMetaData<std::string>(dict,keys[itkey],svalue); + unsigned int equalityPos = svalue.find_first_of('='); + std::string tag = svalue.substr(0,equalityPos); + std::string value = svalue.substr(equalityPos+1); + otbMsgDevMacro(<<"Metadata: "<<tag<<"="<<value); + m_poDataset->SetMetadataItem(tag.c_str(),value.c_str(),NULL); } - // END - } + // END - std::string GDALImageIO::TypeConversion(std::string name) - { - std::string extension; - std::string extGDAL; +} + +std::string GDALImageIO::TypeConversion(std::string name) +{ + std::string extension; + std::string extGDAL; //Recuperer extension du fichier image - extension = System::GetExtension(name); - - if ((extension=="tif")||(extension=="tiff")||(extension=="TIF")||(extension=="TIFF")) - extGDAL="GTiff"; - else if ((extension=="hdr")||(extension=="HDR")) - extGDAL="ENVI"; - else if ((extension=="img")||(extension=="IMG")) - extGDAL="HFA"; + extension = System::GetExtension(name); + + if ((extension=="tif")||(extension=="tiff")||(extension=="TIF")||(extension=="TIFF")) + extGDAL="GTiff"; + else if ((extension=="hdr")||(extension=="HDR")) + extGDAL="ENVI"; + else if ((extension=="img")||(extension=="IMG")) + extGDAL="HFA"; //Pas PNG car BUG !! // else if ((extension=="png")||(extension=="PNG")) // extGDAL="PNG"; //Pas JPEG car BUG !! // else if ((extension=="jpg")||(extension=="JPG")||(extension=="jpeg")||(extension=="JPEG")) // extGDAL="JPEG"; - else - extGDAL="NOT-FOUND"; - return extGDAL; - } + else + extGDAL="NOT-FOUND"; + return extGDAL; +} - std::string GDALImageIO::GetGdalWriteImageFileName(std::string & extGDAL, std::string filename) - { - std::string gdalFileName; - - gdalFileName = filename; - //Suppression de l'extension HDR - if( extGDAL=="ENVI") - { - gdalFileName = System::GetRootName(filename); - } - return gdalFileName; - } +std::string GDALImageIO::GetGdalWriteImageFileName(std::string & extGDAL, std::string filename) +{ + std::string gdalFileName; - bool GDALImageIO::GDALInfoReportCorner( const char * corner_name, double x, double y, double &GeoX, double &GeoY) + gdalFileName = filename; + //Suppression de l'extension HDR + if ( extGDAL=="ENVI") { - const char *pszProjection; - double adfGeoTransform[6]; + gdalFileName = System::GetRootName(filename); + } + return gdalFileName; +} - bool IsTrue; +bool GDALImageIO::GDALInfoReportCorner( const char * corner_name, double x, double y, double &GeoX, double &GeoY) +{ + const char *pszProjection; + double adfGeoTransform[6]; - /* -------------------------------------------------------------------- */ - /* Transform the point into georeferenced coordinates. */ - /* -------------------------------------------------------------------- */ - if( m_poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) - { - pszProjection = m_poDataset->GetProjectionRef(); + bool IsTrue; - GeoX = adfGeoTransform[0] + adfGeoTransform[1] * x - + adfGeoTransform[2] * y; - GeoY = adfGeoTransform[3] + adfGeoTransform[4] * x - + adfGeoTransform[5] * y; - IsTrue = true; - } + /* -------------------------------------------------------------------- */ + /* Transform the point into georeferenced coordinates. */ + /* -------------------------------------------------------------------- */ + if ( m_poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) + { + pszProjection = m_poDataset->GetProjectionRef(); - else - { - GeoX = x; - GeoY = y; - IsTrue = false; - } + GeoX = adfGeoTransform[0] + adfGeoTransform[1] * x + + adfGeoTransform[2] * y; + GeoY = adfGeoTransform[3] + adfGeoTransform[4] * x + + adfGeoTransform[5] * y; + IsTrue = true; + } - return IsTrue; + else + { + GeoX = x; + GeoY = y; + IsTrue = false; } + return IsTrue; +} + } // end namespace otb diff --git a/Code/IO/otbGDALImageIO.h b/Code/IO/otbGDALImageIO.h index 760dd00186c0c6e46152287eb61e6aa4df5aa088..e3d25781f6161e0e4161f75603561b9ee7e595fc 100644 --- a/Code/IO/otbGDALImageIO.h +++ b/Code/IO/otbGDALImageIO.h @@ -54,7 +54,7 @@ namespace otb * */ class ITK_EXPORT GDALImageIO : public itk::ImageIOBase, - public MetaDataKey + public MetaDataKey { public: @@ -83,7 +83,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -102,7 +105,10 @@ public: /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ //THOMAS - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ @@ -159,7 +165,7 @@ private: int m_NbOctetPixel; bool GDALInfoReportCorner( const char * corner_name, double x, double y, - double &dfGeoX, double &dfGeoY); + double &dfGeoX, double &dfGeoY); bool m_FlagWriteImageInformation; diff --git a/Code/IO/otbImage.h b/Code/IO/otbImage.h index 739f744658a50df10f383ef134680a003407e833..c9a64d31d871a90a5ab84d05d31701365395983d 100644 --- a/Code/IO/otbImage.h +++ b/Code/IO/otbImage.h @@ -86,7 +86,7 @@ public: /** Tyepdef for the functor used to access a neighborhood of pixel pointers.*/ typedef itk::NeighborhoodAccessorFunctor< Self > - NeighborhoodAccessorFunctorType; + NeighborhoodAccessorFunctorType; /** Dimension of the image. This constant is used by functions that are @@ -130,19 +130,27 @@ public: /** Return the Pixel Accessor object */ AccessorType GetPixelAccessor( void ) - { return AccessorType(); } + { + return AccessorType(); + } /** Return the Pixel Accesor object */ const AccessorType GetPixelAccessor( void ) const - { return AccessorType(); } + { + return AccessorType(); + } /** Return the NeighborhoodAccessor functor */ NeighborhoodAccessorFunctorType GetNeighborhoodAccessor() - { return NeighborhoodAccessorFunctorType(); } + { + return NeighborhoodAccessorFunctorType(); + } /** Return the NeighborhoodAccessor functor */ const NeighborhoodAccessorFunctorType GetNeighborhoodAccessor() const - { return NeighborhoodAccessorFunctorType(); } + { + return NeighborhoodAccessorFunctorType(); + } @@ -180,11 +188,11 @@ public: void PrintSelf(std::ostream& os, itk::Indent indent) const; /// Copy metadata from a DataObject -virtual void CopyInformation(const itk::DataObject *); + virtual void CopyInformation(const itk::DataObject *); protected: Image(); - virtual ~Image(){}; + virtual ~Image() {}; private: diff --git a/Code/IO/otbImage.txx b/Code/IO/otbImage.txx index e0249ccefda2d98e831653bc5a76ef8c014a2a92..3bcd3d8bbb5c4bdea9000d0f606303fbfc177cdb 100644 --- a/Code/IO/otbImage.txx +++ b/Code/IO/otbImage.txx @@ -33,97 +33,97 @@ Image<TPixel,VImageDimension>::Image() } template <class TPixel, unsigned int VImageDimension> - std::string Image<TPixel, VImageDimension>::GetProjectionRef( void ) const +std::string Image<TPixel, VImageDimension>::GetProjectionRef( void ) const { - return ( this->ImageBase::GetProjectionRef( this->GetMetaDataDictionary() ) ); + return ( this->ImageBase::GetProjectionRef( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - std::string Image<TPixel, VImageDimension>::GetGCPProjection( void ) const +std::string Image<TPixel, VImageDimension>::GetGCPProjection( void ) const { return ( this->ImageBase::GetGCPProjection( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - unsigned int Image<TPixel, VImageDimension>::GetGCPCount( void ) const +unsigned int Image<TPixel, VImageDimension>::GetGCPCount( void ) const { return ( this->ImageBase::GetGCPCount( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - OTB_GCP & Image<TPixel, VImageDimension>::GetGCPs ( unsigned int GCPnum ) +OTB_GCP & Image<TPixel, VImageDimension>::GetGCPs ( unsigned int GCPnum ) { - return (this->ImageBase::GetGCPs( this->GetMetaDataDictionary(), GCPnum ) ); + return (this->ImageBase::GetGCPs( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - std::string Image<TPixel, VImageDimension>::GetGCPId( unsigned int GCPnum ) const +std::string Image<TPixel, VImageDimension>::GetGCPId( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPId( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - std::string Image<TPixel, VImageDimension>::GetGCPInfo( unsigned int GCPnum ) const +std::string Image<TPixel, VImageDimension>::GetGCPInfo( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPInfo( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double Image<TPixel, VImageDimension>::GetGCPRow( unsigned int GCPnum ) const +double Image<TPixel, VImageDimension>::GetGCPRow( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPRow( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double Image<TPixel, VImageDimension>::GetGCPCol( unsigned int GCPnum ) const +double Image<TPixel, VImageDimension>::GetGCPCol( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPCol( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double Image<TPixel, VImageDimension>::GetGCPX( unsigned int GCPnum ) const +double Image<TPixel, VImageDimension>::GetGCPX( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPX( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double Image<TPixel, VImageDimension>::GetGCPY( unsigned int GCPnum ) const +double Image<TPixel, VImageDimension>::GetGCPY( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPY( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double Image<TPixel, VImageDimension>::GetGCPZ( unsigned int GCPnum ) const +double Image<TPixel, VImageDimension>::GetGCPZ( unsigned int GCPnum ) const { return ( this->ImageBase::GetGCPZ( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType Image<TPixel, VImageDimension>::GetGeoTransform( void ) const +ImageBase::VectorType Image<TPixel, VImageDimension>::GetGeoTransform( void ) const { return ( this->ImageBase::GetGeoTransform( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType Image<TPixel, VImageDimension>::GetUpperLeftCorner( void ) const +ImageBase::VectorType Image<TPixel, VImageDimension>::GetUpperLeftCorner( void ) const { return ( this->ImageBase::GetUpperLeftCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType Image<TPixel, VImageDimension>::GetUpperRightCorner( void ) const +ImageBase::VectorType Image<TPixel, VImageDimension>::GetUpperRightCorner( void ) const { return ( this->ImageBase::GetUpperRightCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType Image<TPixel, VImageDimension>::GetLowerLeftCorner( void ) const +ImageBase::VectorType Image<TPixel, VImageDimension>::GetLowerLeftCorner( void ) const { return ( this->ImageBase::GetLowerLeftCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType Image<TPixel, VImageDimension>::GetLowerRightCorner( void ) const +ImageBase::VectorType Image<TPixel, VImageDimension>::GetLowerRightCorner( void ) const { return ( this->ImageBase::GetLowerRightCorner( this->GetMetaDataDictionary() ) ); } @@ -135,7 +135,7 @@ ImageBase::ImageKeywordlistType Image<TPixel, VImageDimension>::GetImageKeywordl } template <class TPixel, unsigned int VImageDimension> - const ImageBase::ImageKeywordlistType Image<TPixel, VImageDimension>::GetImageKeywordlist( void ) const +const ImageBase::ImageKeywordlistType Image<TPixel, VImageDimension>::GetImageKeywordlist( void ) const { return ( this->ImageBase::GetImageKeywordlist( this->GetMetaDataDictionary() ) ); } diff --git a/Code/IO/otbImageBase.cxx b/Code/IO/otbImageBase.cxx index 2206c1778be559d7a2943a1bb910562f0cc5729a..46c0f52c0c17c538302937805e57b679bab9d21f 100644 --- a/Code/IO/otbImageBase.cxx +++ b/Code/IO/otbImageBase.cxx @@ -41,36 +41,36 @@ std::string ImageBase::GetProjectionRef( const MetaDataDictionaryType & dict ) c { std::string metadata; - if(dict.HasKey(MetaDataKey::ProjectionRefKey)) - { - itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::ProjectionRefKey), metadata); - return ( metadata ); - } + if (dict.HasKey(MetaDataKey::ProjectionRefKey)) + { + itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::ProjectionRefKey), metadata); + return ( metadata ); + } else - return (""); + return (""); } std::string ImageBase::GetGCPProjection( const MetaDataDictionaryType & dict ) const { std::string metadata; - if(dict.HasKey(MetaDataKey::GCPProjectionKey)) - { - itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::GCPProjectionKey), metadata); - return ( metadata ); - } + if (dict.HasKey(MetaDataKey::GCPProjectionKey)) + { + itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::GCPProjectionKey), metadata); + return ( metadata ); + } else - return (""); + return (""); } unsigned int ImageBase::GetGCPCount( const MetaDataDictionaryType & dict) const { unsigned int GCPCount = 0; - if(dict.HasKey(MetaDataKey::GCPCountKey)) - { - itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, GCPCount); - } + if (dict.HasKey(MetaDataKey::GCPCountKey)) + { + itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, GCPCount); + } return (GCPCount); } @@ -84,11 +84,11 @@ OTB_GCP & ImageBase::GetGCPs( MetaDataDictionaryType & dict, unsigned int GCPnum lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { + if (dict.HasKey(key)) + { - itk::ExposeMetaData<OTB_GCP>(dict, key, m_GCP); - } + itk::ExposeMetaData<OTB_GCP>(dict, key, m_GCP); + } return ( m_GCP ); } @@ -101,14 +101,14 @@ std::string ImageBase::GetGCPId( const MetaDataDictionaryType & dict, unsigned i lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_Id ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_Id ); + } else - return (""); + return (""); } std::string ImageBase::GetGCPInfo( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -119,14 +119,14 @@ std::string ImageBase::GetGCPInfo( const MetaDataDictionaryType & dict, unsigned lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_Info ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_Info ); + } else - return (""); + return (""); } double ImageBase::GetGCPRow( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -138,14 +138,14 @@ double ImageBase::GetGCPRow( const MetaDataDictionaryType & dict, unsigned int G key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_GCPRow ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_GCPRow ); + } else - return (0); + return (0); } double ImageBase::GetGCPCol( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -157,14 +157,14 @@ double ImageBase::GetGCPCol( const MetaDataDictionaryType & dict, unsigned int G key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_GCPCol ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_GCPCol ); + } else - return (0); + return (0); } double ImageBase::GetGCPX( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -175,14 +175,14 @@ double ImageBase::GetGCPX( const MetaDataDictionaryType & dict, unsigned int GCP lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_GCPX ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_GCPX ); + } else - return (0); + return (0); } double ImageBase::GetGCPY( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -193,14 +193,14 @@ double ImageBase::GetGCPY( const MetaDataDictionaryType & dict, unsigned int GCP lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_GCPY ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_GCPY ); + } else - return (0); + return (0); } double ImageBase::GetGCPZ( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const @@ -211,24 +211,24 @@ double ImageBase::GetGCPZ( const MetaDataDictionaryType & dict, unsigned int GCP lStream << MetaDataKey::GCPParametersKey << GCPnum; key = lStream.str(); - if(dict.HasKey(key)) - { - OTB_GCP gcp; - itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); - return ( gcp.m_GCPZ ); - } + if (dict.HasKey(key)) + { + OTB_GCP gcp; + itk::ExposeMetaData<OTB_GCP>(dict, key, gcp); + return ( gcp.m_GCPZ ); + } else - return (0); + return (0); } ImageBase::VectorType ImageBase::GetGeoTransform( const MetaDataDictionaryType & dict ) const { VectorType adfGeoTransform; - if(dict.HasKey(MetaDataKey::GeoTransformKey)) - { - itk::ExposeMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, adfGeoTransform); - } + if (dict.HasKey(MetaDataKey::GeoTransformKey)) + { + itk::ExposeMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, adfGeoTransform); + } return ( adfGeoTransform ); } @@ -236,62 +236,62 @@ ImageBase::VectorType ImageBase::GetUpperLeftCorner( const MetaDataDictionaryTyp { VectorType UpperLeftCorner; - if(dict.HasKey(MetaDataKey::UpperLeftCornerKey)) - { - itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, UpperLeftCorner); - } - return ( UpperLeftCorner ); + if (dict.HasKey(MetaDataKey::UpperLeftCornerKey)) + { + itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, UpperLeftCorner); + } + return ( UpperLeftCorner ); } ImageBase::VectorType ImageBase::GetUpperRightCorner( const MetaDataDictionaryType & dict ) const { VectorType UpperRightCorner; - if(dict.HasKey(MetaDataKey::UpperRightCornerKey)) - { - itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, UpperRightCorner); - } - return ( UpperRightCorner ); + if (dict.HasKey(MetaDataKey::UpperRightCornerKey)) + { + itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, UpperRightCorner); + } + return ( UpperRightCorner ); } ImageBase::VectorType ImageBase::GetLowerLeftCorner( const MetaDataDictionaryType & dict ) const { VectorType LowerLeftCorner; - if(dict.HasKey(MetaDataKey::LowerLeftCornerKey)) - { - itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, LowerLeftCorner); - } - return ( LowerLeftCorner ); + if (dict.HasKey(MetaDataKey::LowerLeftCornerKey)) + { + itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, LowerLeftCorner); + } + return ( LowerLeftCorner ); } ImageBase::VectorType ImageBase::GetLowerRightCorner( const MetaDataDictionaryType & dict ) const { VectorType LowerRightCorner; - if(dict.HasKey(MetaDataKey::LowerRightCornerKey)) - { - itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, LowerRightCorner); - } - return ( LowerRightCorner ); + if (dict.HasKey(MetaDataKey::LowerRightCornerKey)) + { + itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, LowerRightCorner); + } + return ( LowerRightCorner ); } ImageBase::ImageKeywordlistType ImageBase::GetImageKeywordlist( MetaDataDictionaryType & dict ) { ImageKeywordlistType ImageKeywordlist; - if(dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) - { - itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist); - } - return ( ImageKeywordlist ); + if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) + { + itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist); + } + return ( ImageKeywordlist ); } const ImageBase::ImageKeywordlistType ImageBase::GetImageKeywordlist(const MetaDataDictionaryType & dict ) const { ImageKeywordlistType ImageKeywordlist; - if(dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) + if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist); } @@ -318,53 +318,53 @@ ImageBase::PrintSelf(std::ostream& os, itk::Indent indent, const MetaDataDiction MetaDataKey key; for (unsigned int itkey=0; itkey<keys.size(); itkey++) - { + { - switch( key.GetKeyType(keys[itkey]) ) - { - case MetaDataKey::TSTRING: - itk::ExposeMetaData<std::string>(dict2, keys[itkey], svalue); - os << indent << "---> " << keys[itkey] << " = " << svalue << std::endl; - break; + switch ( key.GetKeyType(keys[itkey]) ) + { + case MetaDataKey::TSTRING: + itk::ExposeMetaData<std::string>(dict2, keys[itkey], svalue); + os << indent << "---> " << keys[itkey] << " = " << svalue << std::endl; + break; - case MetaDataKey::TENTIER: - itk::ExposeMetaData<unsigned int>(dict2, keys[itkey], ivalue); - os << indent << "---> " << keys[itkey] << " = " << ivalue << std::endl; - break; + case MetaDataKey::TENTIER: + itk::ExposeMetaData<unsigned int>(dict2, keys[itkey], ivalue); + os << indent << "---> " << keys[itkey] << " = " << ivalue << std::endl; + break; - case MetaDataKey::TVECTOR: - itk::ExposeMetaData<VectorType>(dict2, keys[itkey], vvalue); + case MetaDataKey::TVECTOR: + itk::ExposeMetaData<VectorType>(dict2, keys[itkey], vvalue); - for(i = 0; i < vvalue.size(); i++ ) - { + for (i = 0; i < vvalue.size(); i++ ) + { os << indent << "---> " << keys[itkey] << "[" << i <<"] = "<< vvalue[i]<< std::endl; - } - vvalue.clear(); + } + vvalue.clear(); - break; + break; - case MetaDataKey::TDOUBLE: - itk::ExposeMetaData<double>(dict2, keys[itkey], dvalue); - os << indent << "---> " << keys[itkey] << " = " << dvalue << std::endl; - break; + case MetaDataKey::TDOUBLE: + itk::ExposeMetaData<double>(dict2, keys[itkey], dvalue); + os << indent << "---> " << keys[itkey] << " = " << dvalue << std::endl; + break; - case MetaDataKey::TOTB_GCP: - itk::ExposeMetaData<OTB_GCP>(dict2, keys[itkey], gcpvalue); + case MetaDataKey::TOTB_GCP: + itk::ExposeMetaData<OTB_GCP>(dict2, keys[itkey], gcpvalue); - os << indent << "---> " << keys[itkey] << std::endl; - gcpvalue.Print(os); - break; + os << indent << "---> " << keys[itkey] << std::endl; + gcpvalue.Print(os); + break; case MetaDataKey::TOSSIMKEYWORDLIST: - itk::ExposeMetaData<ImageKeywordlist>(dict2, keys[itkey], ossimvalue); + itk::ExposeMetaData<ImageKeywordlist>(dict2, keys[itkey], ossimvalue); - os << indent << "---> " << keys[itkey] << std::endl; - ossimvalue.Print(os); - // ossimvalue.Print(os); - break; + os << indent << "---> " << keys[itkey] << std::endl; + ossimvalue.Print(os); + // ossimvalue.Print(os); + break; } - } + } } diff --git a/Code/IO/otbImageBase.h b/Code/IO/otbImageBase.h index 0831068352e3aabc672ab8b17473fb8340a04d1b..1f098167bdf8643ab03344710f8eb7ff6b30742e 100644 --- a/Code/IO/otbImageBase.h +++ b/Code/IO/otbImageBase.h @@ -118,7 +118,7 @@ public: protected: ImageBase(); - virtual ~ImageBase(){}; + virtual ~ImageBase() {}; private: ImageBase(const Self&); //purposely not implemented diff --git a/Code/IO/otbImageFileReader.txx b/Code/IO/otbImageFileReader.txx index 7b976fcdaf28e757323e72764f1baedabae0ff87..ee06bfb4655791bf8262d925ec4fcddac6d339c0 100644 --- a/Code/IO/otbImageFileReader.txx +++ b/Code/IO/otbImageFileReader.txx @@ -64,14 +64,14 @@ void ImageFileReader<TOutputImage> Superclass::PrintSelf(os, indent); if (this->m_ImageIO) - { + { os << indent << "ImageIO: \n"; this->m_ImageIO->Print(os, indent.GetNextIndent()); - } + } else - { + { os << indent << "ImageIO: (null)" << "\n"; - } + } os << indent << "UserSpecifiedImageIO flag: " << this->m_UserSpecifiedImageIO << "\n"; os << indent << "m_FileName: " << this->m_FileName << "\n"; @@ -110,39 +110,39 @@ ImageFileReader<TOutputImage> itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); -/* Init IORegion with size or streaming size */ + /* Init IORegion with size or streaming size */ SizeType dimSize; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { if (i < this->m_ImageIO->GetNumberOfDimensions()) - { - if( !this->m_ImageIO->CanStreamRead() ) - dimSize[i] = this->m_ImageIO->GetDimensions(i); + { + if ( !this->m_ImageIO->CanStreamRead() ) + dimSize[i] = this->m_ImageIO->GetDimensions(i); else - dimSize[i] = output->GetRequestedRegion().GetSize()[i]; - } + dimSize[i] = output->GetRequestedRegion().GetSize()[i]; + } else - { + { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, and origin for the final (degenerate) dimensions. dimSize[i] = 1; - } } + } - for(unsigned int i = 0; i < dimSize.GetSizeDimension(); ++i) - { + for (unsigned int i = 0; i < dimSize.GetSizeDimension(); ++i) + { ioSize[i] = dimSize[i]; - } + } typedef typename TOutputImage::IndexType IndexType; IndexType start; - if( !this->m_ImageIO->CanStreamRead() ) start.Fill(0); + if ( !this->m_ImageIO->CanStreamRead() ) start.Fill(0); else start = output->GetRequestedRegion().GetIndex(); - for(unsigned int i = 0; i < start.GetIndexDimension(); ++i) - { + for (unsigned int i = 0; i < start.GetIndexDimension(); ++i) + { ioStart[i] = start[i]; - } + } ioRegion.SetSize(ioSize); ioRegion.SetIndex(ioStart); @@ -155,27 +155,27 @@ ImageFileReader<TOutputImage> typedef itk::DefaultConvertPixelTraits< ITK_TYPENAME TOutputImage::IOPixelType > ConvertPixelTraits; -otbMsgDevMacro(<< "ImageFileReader<TOutputImage>::GenerateData():"); -otbMsgDevMacro (<< "ioRegion: " << ioRegion); -otbMsgDevMacro(<< " => test conversion Pixel type: compare"); -otbMsgDevMacro(<< " compare"); -otbMsgDevMacro(<< " this->m_ImageIO->GetComponentTypeInfo(): "<<this->m_ImageIO->GetComponentTypeInfo().name()); -otbMsgDevMacro(<< " with typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType): "<<typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name()); -otbMsgDevMacro(<< " and this->m_ImageIO->GetNumberOfComponents(): "<<this->m_ImageIO->GetNumberOfComponents()); -otbMsgDevMacro(<< " with ConvertPixelTraits::GetNumberOfComponents(): "<<ConvertPixelTraits::GetNumberOfComponents()); + otbMsgDevMacro(<< "ImageFileReader<TOutputImage>::GenerateData():"); + otbMsgDevMacro (<< "ioRegion: " << ioRegion); + otbMsgDevMacro(<< " => test conversion Pixel type: compare"); + otbMsgDevMacro(<< " compare"); + otbMsgDevMacro(<< " this->m_ImageIO->GetComponentTypeInfo(): "<<this->m_ImageIO->GetComponentTypeInfo().name()); + otbMsgDevMacro(<< " with typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType): "<<typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name()); + otbMsgDevMacro(<< " and this->m_ImageIO->GetNumberOfComponents(): "<<this->m_ImageIO->GetNumberOfComponents()); + otbMsgDevMacro(<< " with ConvertPixelTraits::GetNumberOfComponents(): "<<ConvertPixelTraits::GetNumberOfComponents()); if ( this->m_ImageIO->GetComponentTypeInfo() == typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) && (this->m_ImageIO->GetNumberOfComponents() == ConvertPixelTraits::GetNumberOfComponents())) - { + { otbMsgDevMacro(<< "No buffer conversion required."); // allocate a buffer and have the ImageIO read directly into it this->m_ImageIO->Read(buffer); return; - } + } else // a type conversion is necessary - { + { // note: char is used here because the buffer is read in bytes // regardles of the actual type of the pixels. ImageRegionType region = output->GetBufferedRegion(); @@ -186,9 +186,9 @@ otbMsgDevMacro(<< " with ConvertPixelTraits::GetNumberOfComponents(): "<<Conv otbMsgDevMacro(<< "Buffer conversion required from: " - << this->m_ImageIO->GetComponentTypeInfo().name() - << " to: " - << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name() << " NbBytes"<<nbBytes<<" region.GetNumberOfPixels()"<<region.GetNumberOfPixels()); + << this->m_ImageIO->GetComponentTypeInfo().name() + << " to: " + << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name() << " NbBytes"<<nbBytes<<" region.GetNumberOfPixels()"<<region.GetNumberOfPixels()); char * loadBuffer = new char[nbBytes]; this->m_ImageIO->Read(loadBuffer); @@ -196,7 +196,7 @@ otbMsgDevMacro(<< " with ConvertPixelTraits::GetNumberOfComponents(): "<<Conv this->DoConvertBuffer(loadBuffer, region.GetNumberOfPixels()); delete [] loadBuffer; - } + } } @@ -210,21 +210,21 @@ ImageFileReader<TOutputImage> // the ImageIO object cannot stream, then set the RequestedRegion to the // LargestPossibleRegion if (!this->m_ImageIO->CanStreamRead()) - { + { if (out) - { + { out->SetRequestedRegion( out->GetLargestPossibleRegion() ); - } - else - { - throw itk::ImageFileReaderException(__FILE__, __LINE__, - "Invalid output object type"); - } } else { -otbMsgDevMacro( << " Streaming Image Read "); + throw itk::ImageFileReaderException(__FILE__, __LINE__, + "Invalid output object type"); } + } + else + { + otbMsgDevMacro( << " Streaming Image Read "); + } } @@ -241,17 +241,17 @@ ImageFileReader<TOutputImage> // Check to see if we can read the file given the name or prefix // if ( this->m_FileName == "" ) - { + { throw itk::ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified"); - } + } // Find real image file name // !!!! Update FileName std::string lFileName; bool found = GetGdalReadImageFileName(this->m_FileName,lFileName); - if( found == false ) + if ( found == false ) { - otbMsgDebugMacro( <<"Filename was NOT unknowed. May be reconize by a Image factory ! "); + otbMsgDebugMacro( <<"Filename was NOT unknowed. May be reconize by a Image factory ! "); } // Update FileName this->m_FileName = lFileName; @@ -265,31 +265,31 @@ ImageFileReader<TOutputImage> this->TestFileExistanceAndReadability(); if ( this->m_UserSpecifiedImageIO == false ) //try creating via factory - { + { this->m_ImageIO = ImageIOFactory::CreateImageIO( this->m_FileName.c_str(), itk::ImageIOFactory::ReadMode ); - } + } if ( this->m_ImageIO.IsNull() ) - { + { itk::ImageFileReaderException e(__FILE__, __LINE__); itk::OStringStream msg; msg << " Could not create IO object for file " - << this->m_FileName.c_str() << std::endl; + << this->m_FileName.c_str() << std::endl; msg << " Tried to create one of the following:" << std::endl; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); - for(std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { itk::ImageIOBase* io = dynamic_cast<itk::ImageIOBase*>(i->GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; - } + } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; - } + } // Got to allocate space for the image. Determine the characteristics of // the image. @@ -306,10 +306,10 @@ ImageFileReader<TOutputImage> typename TOutputImage::DirectionType direction; std::vector<double> axis; - for(unsigned int i=0; i<TOutputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TOutputImage::ImageDimension; i++) + { if ( i < this->m_ImageIO->GetNumberOfDimensions() ) - { + { dimSize[i] = this->m_ImageIO->GetDimensions(i); spacing[i] = this->m_ImageIO->GetSpacing(i); origin[i] = this->m_ImageIO->GetOrigin(i); @@ -317,19 +317,19 @@ ImageFileReader<TOutputImage> // direction matrix axis = this->m_ImageIO->GetDirection(i); for (unsigned j=0; j<TOutputImage::ImageDimension; j++) - { + { if (j < this->m_ImageIO->GetNumberOfDimensions()) - { + { direction[j][i] = axis[j]; - } + } else - { + { direction[j][i] = 0.0; - } } } + } else - { + { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, origin and direction for the final (degenerate) dimensions. @@ -337,18 +337,18 @@ ImageFileReader<TOutputImage> spacing[i] = 1.0; origin[i] = 0.0; for (unsigned j = 0; j < TOutputImage::ImageDimension; j++) - { + { if (i == j) - { + { direction[j][i] = 1.0; - } + } else - { + { direction[j][i] = 0.0; - } } } } + } output->SetSpacing( spacing ); // Set the image spacing output->SetOrigin( origin ); // Set the image origin @@ -362,12 +362,12 @@ ImageFileReader<TOutputImage> if (!handler) { - otbMsgDevMacro( <<"OSSIM Open Image FAILED ! "); + otbMsgDevMacro( <<"OSSIM Open Image FAILED ! "); } else { - otbMsgDevMacro( <<"OSSIM Open Image SUCCESS ! "); + otbMsgDevMacro( <<"OSSIM Open Image SUCCESS ! "); ossimKeywordlist geom_kwl, tmp_kwl, tmp_kwl2;// = new ossimKeywordlist(); // Read OSSIM Keyword List @@ -376,19 +376,19 @@ ImageFileReader<TOutputImage> if (!hasMetaData) { - otbMsgDebugMacro( <<"OSSIM MetaData not present ! "); + otbMsgDebugMacro( <<"OSSIM MetaData not present ! "); } else { - otbMsgDebugMacro( <<"OSSIM MetaData present ! "); + otbMsgDebugMacro( <<"OSSIM MetaData present ! "); otbMsgDevMacro( <<"Image keyword lists are :" << std::endl << geom_kwl); - // Update otb Keywordlist + // Update otb Keywordlist ImageKeywordlist otb_kwl; otb_kwl.SetKeywordlist( geom_kwl ); - // Update itk MetaData Dictionnary + // Update itk MetaData Dictionnary // otbMsgDebugMacro( <<"Start update ITK Dictionnary ? "); otb_kwl.convertToOSSIMKeywordlist(tmp_kwl); @@ -396,9 +396,9 @@ ImageFileReader<TOutputImage> itk::MetaDataDictionary& dico = this->m_ImageIO->GetMetaDataDictionary(); // otbMsgDebugMacro( <<"Before write ITK Dictionnary ? "); - itk::EncapsulateMetaData< ImageKeywordlist >(dico, - MetaDataKey::OSSIMKeywordlistKey, - otb_kwl); + itk::EncapsulateMetaData< ImageKeywordlist >(dico, + MetaDataKey::OSSIMKeywordlistKey, + otb_kwl); // otbMsgDebugMacro( <<"After write ITK Dictionnary ? "); // itk::ExposeMetaData< ImageKeywordlist >(dico, @@ -409,7 +409,7 @@ ImageFileReader<TOutputImage> // otb_tmp.convertToOSSIMKeywordlist(tmp_kwl2); // otbMsgDebugMacro( << " DEBUT THOMAS : Ossim key word list copy : "<<tmp_kwl2<<std::endl); - // otbMsgDebugMacro( <<"Image keyword lists in dictionnary are :" << std::endl << geom_tmp); + // otbMsgDebugMacro( <<"Image keyword lists in dictionnary are :" << std::endl << geom_tmp); } // Free memory @@ -434,11 +434,11 @@ ImageFileReader<TOutputImage> // THOMAS : ajout // If a VectorImage, this requires us to set the // VectorLength before allocate - if( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 ) - { + if ( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 ) + { typedef typename TOutputImage::AccessorFunctorType AccessorFunctorType; AccessorFunctorType::SetVectorLength( output, this->m_ImageIO->GetNumberOfComponents() ); - } + } output->SetLargestPossibleRegion(region); @@ -449,39 +449,39 @@ void ImageFileReader<TOutputImage> ::TestFileExistanceAndReadability() { - // Test if the file exists. - if( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) - { - itk::ImageFileReaderException e(__FILE__, __LINE__); + // Test if the file exists. + if ( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) + { + itk::ImageFileReaderException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg <<"The file doesn't exists. " + << std::endl << "Filename = " << this->m_FileName + << std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; + } + + // Test if the file can be open for reading access. + //Only if m_FileName speciy a filname (not a dirname) + if ( System::IsAFileName( this->m_FileName ) == true ) + { + std::ifstream readTester; + readTester.open( this->m_FileName.c_str() ); + if ( readTester.fail() ) + { + readTester.close(); itk::OStringStream msg; - msg <<"The file doesn't exists. " - << std::endl << "Filename = " << this->m_FileName - << std::endl; - e.SetDescription(msg.str().c_str()); + msg <<"The file couldn't be opened for reading. " + << std::endl << "Filename: " << this->m_FileName + << std::endl; + itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); throw e; return; - } - - // Test if the file can be open for reading access. - //Only if m_FileName speciy a filname (not a dirname) - if( System::IsAFileName( this->m_FileName ) == true ) - { - std::ifstream readTester; - readTester.open( this->m_FileName.c_str() ); - if( readTester.fail() ) - { - readTester.close(); - itk::OStringStream msg; - msg <<"The file couldn't be opened for reading. " - << std::endl << "Filename: " << this->m_FileName - << std::endl; - itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); - throw e; - return; - } - readTester.close(); } + readTester.close(); + } } template <class TOutputImage> @@ -489,53 +489,56 @@ bool ImageFileReader<TOutputImage> ::GetGdalReadImageFileName( const std::string & filename, std::string & GdalFileName ) { - std::vector<std::string> listFileSearch; - listFileSearch.push_back("DAT_01.001");listFileSearch.push_back("dat_01.001");// RADARSAT ou SAR_ERS2 - listFileSearch.push_back("IMAGERY.TIF");listFileSearch.push_back("imagery.tif");//For format SPOT5TIF + std::vector<std::string> listFileSearch; + listFileSearch.push_back("DAT_01.001"); + listFileSearch.push_back("dat_01.001");// RADARSAT ou SAR_ERS2 + listFileSearch.push_back("IMAGERY.TIF"); + listFileSearch.push_back("imagery.tif");//For format SPOT5TIF // Not recognised as a supported file format by GDAL. // listFileSearch.push_back("IMAGERY.BIL");listFileSearch.push_back("imagery.bil");//For format SPOT5BIL - listFileSearch.push_back("IMAG_01.DAT");listFileSearch.push_back("imag_01.dat");//For format SPOT4 - std::string str_FileName; - bool fic_trouve(false); - - // Si c'est un repertoire, on regarde le contenu pour voir si c'est pas du RADARSAT, ERS - std::vector<std::string> listFileFind; - listFileFind = System::Readdir(filename); - if( listFileFind.empty() == false ) - { - unsigned int cpt(0); + listFileSearch.push_back("IMAG_01.DAT"); + listFileSearch.push_back("imag_01.dat");//For format SPOT4 + std::string str_FileName; + bool fic_trouve(false); + + // Si c'est un repertoire, on regarde le contenu pour voir si c'est pas du RADARSAT, ERS + std::vector<std::string> listFileFind; + listFileFind = System::Readdir(filename); + if ( listFileFind.empty() == false ) + { + unsigned int cpt(0); while ( (cpt < listFileFind.size()) && (fic_trouve==false) ) - { + { str_FileName = std::string(listFileFind[cpt]); - for(unsigned int i = 0; i < listFileSearch.size(); i++) - { - if(str_FileName.compare(listFileSearch[i]) == 0) - { - GdalFileName = std::string(filename)+str_FileName;//listFileSearch[i]; - fic_trouve=true; - } - } - cpt++; - } - } - else + for (unsigned int i = 0; i < listFileSearch.size(); i++) + { + if (str_FileName.compare(listFileSearch[i]) == 0) { - std::string strFileName(filename); - - std::string extension = System::GetExtension(strFileName); - if( (extension=="HDR") || (extension=="hdr") ) - { - //Supprime l'extension - GdalFileName = System::GetRootName(strFileName); - } - - else - { - // Sinon le filename est le nom du fichier a ouvrir - GdalFileName = std::string(filename); - } - fic_trouve=true; + GdalFileName = std::string(filename)+str_FileName;//listFileSearch[i]; + fic_trouve=true; } + } + cpt++; + } + } + else + { + std::string strFileName(filename); + + std::string extension = System::GetExtension(strFileName); + if ( (extension=="HDR") || (extension=="hdr") ) + { + //Supprime l'extension + GdalFileName = System::GetRootName(strFileName); + } + + else + { + // Sinon le filename est le nom du fichier a ouvrir + GdalFileName = std::string(filename); + } + fic_trouve=true; + } otbMsgDevMacro(<<"lFileNameGdal : "<<GdalFileName.c_str()); otbMsgDevMacro(<<"fic_trouve : "<<fic_trouve); return( fic_trouve ); diff --git a/Code/IO/otbImageFileWriter.txx b/Code/IO/otbImageFileWriter.txx index 52a814cb1a2148f97abdf638cf2d65b07d8c41d0..aacfc7e14f10fbd480f0c330b419c658917a4153 100644 --- a/Code/IO/otbImageFileWriter.txx +++ b/Code/IO/otbImageFileWriter.txx @@ -35,8 +35,8 @@ namespace otb template <class TInputImage, unsigned int toto> ImageFileWriter<TInputImage,toto> ::ImageFileWriter() : itk::ImageFileWriter<TInputImage>(), - m_UserSpecifiedIORegion(false), - m_FactorySpecifiedImageIO(false) + m_UserSpecifiedIORegion(false), + m_FactorySpecifiedImageIO(false) { } @@ -63,64 +63,64 @@ ImageFileWriter<TInputImage,toto> // Make sure input is available if ( input == 0 ) - { + { itkExceptionMacro(<< "No input to writer!"); - } + } // Make sure that we can write the file given the name // std::string strFileName(this->GetFileName()); // this->GetFileName() return a const char * if ( strFileName == "" ) - { + { itkExceptionMacro(<<"No filename was specified"); - } + } // if ( this->GetImageIO()->IsNull() ) //try creating via factory if ( this->GetImageIO() == 0 ) //try creating via factory - { + { itkDebugMacro(<<"Attempting factory creation of ImageIO for file: " << this->GetFileName()); this->SetImageIO( ImageIOFactory::CreateImageIO( this->GetFileName(), - itk::ImageIOFactory::WriteMode ) ); + itk::ImageIOFactory::WriteMode ) ); m_FactorySpecifiedImageIO = true; - } + } else + { + if ( m_FactorySpecifiedImageIO && !this->GetImageIO()->CanWriteFile( this->GetFileName() ) ) { - if( m_FactorySpecifiedImageIO && !this->GetImageIO()->CanWriteFile( this->GetFileName() ) ) - { itkDebugMacro(<<"ImageIO exists but doesn't know how to write file:" << this->GetFileName() ); itkDebugMacro(<<"Attempting creation of ImageIO with a factory for file:" << this->GetFileName()); this->SetImageIO( ImageIOFactory::CreateImageIO( this->GetFileName(), - itk::ImageIOFactory::WriteMode ) ); + itk::ImageIOFactory::WriteMode ) ); m_FactorySpecifiedImageIO = true; - } } + } // if ( this->GetImageIO()->IsNull() ) if ( this->GetImageIO() == 0 ) - { + { itk::ImageFileWriterException e(__FILE__, __LINE__); itk::OStringStream msg; msg << " Could not create IO object for file " - << this->GetFileName() << std::endl; + << this->GetFileName() << std::endl; msg << " Tried to create one of the following:" << std::endl; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); - for(std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { itk::ImageIOBase* io = dynamic_cast<itk::ImageIOBase*>(i->GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; - } + } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; - } - // Notify start event observers + } + // Notify start event observers this->InvokeEvent( itk::StartEvent() ); // NOTE: this const_cast<> is due to the lack of const-correctness @@ -130,27 +130,27 @@ ImageFileWriter<TInputImage,toto> typedef typename TInputImage::RegionType RegionType; if ( ! m_UserSpecifiedIORegion ) - { + { // Make sure the data is up-to-date. - if( nonConstImage->GetSource() ) - { + if ( nonConstImage->GetSource() ) + { nonConstImage->GetSource()->UpdateLargestPossibleRegion(); - } + } // Write the whole image itk::ImageIORegion ioRegion(TInputImage::ImageDimension); RegionType region = input->GetLargestPossibleRegion(); - for(unsigned int i=0; i<TInputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TInputImage::ImageDimension; i++) + { ioRegion.SetSize(i,region.GetSize(i)); ioRegion.SetIndex(i,region.GetIndex(i)); - } - this->SetIORegion( ioRegion ); //used by GenerateData } + this->SetIORegion( ioRegion ); //used by GenerateData + } else - { + { nonConstImage->Update(); - } + } // Setup the ImageIO // @@ -160,27 +160,27 @@ ImageFileWriter<TInputImage,toto> const typename TInputImage::PointType& origin = input->GetOrigin(); const typename TInputImage::DirectionType& direction = input->GetDirection(); - for(unsigned int i=0; i<TInputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TInputImage::ImageDimension; i++) + { this->GetImageIO()->SetDimensions(i,region.GetSize(i)); this->GetImageIO()->SetSpacing(i,spacing[i]); this->GetImageIO()->SetOrigin(i,origin[i]); vnl_vector< double > axisDirection(TInputImage::ImageDimension); // Please note: direction cosines are stored as columns of the // direction matrix - for(unsigned int j=0; j<TInputImage::ImageDimension; j++) - { + for (unsigned int j=0; j<TInputImage::ImageDimension; j++) + { axisDirection[j] = direction[j][i]; - } - this->GetImageIO()->SetDirection( i, axisDirection ); } + this->GetImageIO()->SetDirection( i, axisDirection ); + } this->GetImageIO()->SetUseCompression(this->GetUseCompression()); this->GetImageIO()->SetIORegion(this->GetIORegion()); - if( this->GetUseInputMetaDataDictionary() ) - { + if ( this->GetUseInputMetaDataDictionary() ) + { this->GetImageIO()->SetMetaDataDictionary(input->GetMetaDataDictionary()); - } + } //otbMsgDevMacro( << this->GetFileName() ); // this->GetImageIO()->SetFileName( this->GetFileName() ); @@ -199,9 +199,9 @@ ImageFileWriter<TInputImage,toto> // Release upstream data if requested if ( input->ShouldIReleaseData() ) - { + { nonConstImage->ReleaseData(); - } + } } diff --git a/Code/IO/otbImageGeometryHandler.cxx b/Code/IO/otbImageGeometryHandler.cxx index 45a0f1730f68c2d8a4a55a656faef4bf8f18756f..bd73ff8e28fafcea0c8def67eaf40f0c21efb18c 100644 --- a/Code/IO/otbImageGeometryHandler.cxx +++ b/Code/IO/otbImageGeometryHandler.cxx @@ -28,8 +28,8 @@ namespace otb { /***************************/ - /* Constructeurs */ - /***************************/ +/* Constructeurs */ +/***************************/ // Constructeur par default ImageGeometryHandler::ImageGeometryHandler() @@ -47,37 +47,37 @@ ImageGeometryHandler::ImageGeometryHandler() // } // } - /***************************/ - /* Destructeurs */ - /***************************/ +/***************************/ +/* Destructeurs */ +/***************************/ ImageGeometryHandler::~ImageGeometryHandler() { //Not needed since we use the instance method //delete handler; } - /***************************/ - /* Methodes */ - /***************************/ +/***************************/ +/* Methodes */ +/***************************/ //Ouvrir le fichier: On specifie le nom de l'image en parametres //Encapsulation de la methode "open" void ImageGeometryHandler::SetFileName(char *src) { otbDebugMacro(<<"Creation handler... "); - handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(src)); - if(!handler) - { + handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(src)); + if (!handler) + { itkExceptionMacro(<< "Unable to open input image: " << src); - } + } } // Recuperation de la geometrie de l'image: //Encapsulation de la methode "getImageGeometry" ossimKeywordlist ImageGeometryHandler::GetGeometryKeywordlist() { -otbDebugMacro( << "Get geometry handler " ); -handler->getImageGeometry(m_geom_kwl); -return m_geom_kwl; + otbDebugMacro( << "Get geometry handler " ); + handler->getImageGeometry(m_geom_kwl); + return m_geom_kwl; } }//fin namespace diff --git a/Code/IO/otbImageGeometryHandler.h b/Code/IO/otbImageGeometryHandler.h index acee85dfa4feb52d4877abf95e488337cd0fe3b5..0baadbfa727e9cc5b88da4501779d4ced5be577e 100644 --- a/Code/IO/otbImageGeometryHandler.h +++ b/Code/IO/otbImageGeometryHandler.h @@ -64,21 +64,21 @@ public : static Pointer New() { - Pointer n = new Self; - n->UnRegister(); - return n; + Pointer n = new Self; + n->UnRegister(); + return n; } -itkTypeMacro( ImageGeometryHandler, Object); + itkTypeMacro( ImageGeometryHandler, Object); -/***********************************/ -/* Déclaration des méthodes */ -/***********************************/ + /***********************************/ + /* Déclaration des méthodes */ + /***********************************/ //Ouverture d'une image à partir d'un nom de fichier -void SetFileName(char *src); + void SetFileName(char *src); //Récupération de la keywordlist de l'image: -ossimKeywordlist GetGeometryKeywordlist(); + ossimKeywordlist GetGeometryKeywordlist(); // //Récupération du model de projection(spécifique à AdjMapModel): // const ossimMapProjection* ImageGeometryHandler::GetProjection() const; @@ -95,13 +95,13 @@ ossimKeywordlist GetGeometryKeywordlist(); // //Récupération du SpotDimapSupportData: protected: -ImageGeometryHandler(); + ImageGeometryHandler(); //ImageGeometryHandler(const char *src); -virtual ~ImageGeometryHandler(); + virtual ~ImageGeometryHandler(); -ossimImageHandler *handler; -ossimKeywordlist m_geom_kwl; -ossimFilename m_filename; + ossimImageHandler *handler; + ossimKeywordlist m_geom_kwl; + ossimFilename m_filename; };//Fin définition de la classe }//fin namespace diff --git a/Code/IO/otbImageIOFactory.cxx b/Code/IO/otbImageIOFactory.cxx index 0c0e33caf6f75290d411f595e01b0c9c4341d695..958a7c3babdc840f6c4610a8e07e0ab50d896c61 100644 --- a/Code/IO/otbImageIOFactory.cxx +++ b/Code/IO/otbImageIOFactory.cxx @@ -42,60 +42,60 @@ namespace otb { - itk::ImageIOBase::Pointer - ImageIOFactory::CreateImageIO(const char* path, FileModeType mode) - { - - RegisterBuiltInFactories(); - return (Superclass::CreateImageIO(path,mode) ); - - } - - void - ImageIOFactory::RegisterBuiltInFactories() - { - static bool firstTime = true; - - static itk::SimpleMutexLock mutex; - { - // This helper class makes sure the Mutex is unlocked - // in the event an exception is thrown. - itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder( mutex ); - if( firstTime ) - { +itk::ImageIOBase::Pointer +ImageIOFactory::CreateImageIO(const char* path, FileModeType mode) +{ + + RegisterBuiltInFactories(); + return (Superclass::CreateImageIO(path,mode) ); + +} + +void +ImageIOFactory::RegisterBuiltInFactories() +{ + static bool firstTime = true; + + static itk::SimpleMutexLock mutex; + { + // This helper class makes sure the Mutex is unlocked + // in the event an exception is thrown. + itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder( mutex ); + if ( firstTime ) + { // RAD Format for OTB - itk::ObjectFactoryBase::RegisterFactory( RADImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( RADImageIOFactory::New() ); // BSQ format for OTB - itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() ); // LUM format for OTB - itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() ); #ifdef OTB_COMPILE_JPEG2000 // JPEG2000 : New format for OTB - itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() ); #endif // GDAL : New format for OTB - itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() ); // MegaWave format for OTB itk::ObjectFactoryBase::RegisterFactory( MWImageIOFactory::New() ); // ONERA format for OTB - itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() ); // MSTAR Format for OTB - itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() ); #ifdef OTB_USE_CURL // TileMap : New format for OTB - itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() ); + itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() ); #endif - firstTime = false; - } - } + firstTime = false; + } + } - } +} } // end namespace otb diff --git a/Code/IO/otbJPEG2000ImageIO.cxx b/Code/IO/otbJPEG2000ImageIO.cxx index 588c22b574116eabad45b0bef47b08006fe4cd9c..8630975e47b1dcb17f8d00a359830258113cc52d 100644 --- a/Code/IO/otbJPEG2000ImageIO.cxx +++ b/Code/IO/otbJPEG2000ImageIO.cxx @@ -25,21 +25,24 @@ PURPOSE. See the above copyright notices for more information. /** sample error debug callback expecting no client object */ -void error_callback(const char *msg, void *client_data) { +void error_callback(const char *msg, void *client_data) +{ (void)client_data; itkGenericExceptionMacro(<<"OpenJpeg error: "<<msg); } /** sample warning debug callback expecting no client object */ -void warning_callback(const char *msg, void *client_data) { +void warning_callback(const char *msg, void *client_data) +{ (void)client_data; otbGenericMsgDebugMacro(<<"OpenJpeg warning: "<<msg); } /** sample debug callback expecting no client object */ -void info_callback(const char *msg, void *client_data) { +void info_callback(const char *msg, void *client_data) +{ (void)client_data; otbMsgDevMacro(<<"OpenJpeg info: "<<msg); } @@ -48,229 +51,229 @@ void info_callback(const char *msg, void *client_data) { namespace otb { - JPEG2000ImageIO::JPEG2000ImageIO() - { - // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); - m_PixelType = SCALAR; - m_ComponentType = UCHAR; - - // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; - // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; +JPEG2000ImageIO::JPEG2000ImageIO() +{ + // By default set number of dimensions to two. + this->SetNumberOfDimensions(2); + m_PixelType = SCALAR; + m_ComponentType = UCHAR; + + // Set default spacing to one + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; + // Set default origin to zero + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_NbOctetPixel = 1; - } + m_NbOctetPixel = 1; +} - JPEG2000ImageIO::~JPEG2000ImageIO() - {} +JPEG2000ImageIO::~JPEG2000ImageIO() +{} - bool JPEG2000ImageIO::CanReadFile( const char* filename ) +bool JPEG2000ImageIO::CanReadFile( const char* filename ) +{ + if (filename == NULL) { - if(filename == NULL) - { - return false; - } - - std::string lFileName(filename); - - // Creating a codec - opj_codec_t * codec = NULL; - - if(System::SetToLower(System::GetExtension(lFileName)) == "j2k") - { - otbMsgDebugMacro(<<"Jpeg2000ImageIO: Creating J2K codec."); - codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); - } - else if(System::SetToLower(System::GetExtension(lFileName)) == "jp2" - || System::SetToLower(System::GetExtension(lFileName)) == "jpx") - { - otbMsgDebugMacro(<<"Jpeg2000ImageIO: Creating JP2 codec."); - codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); - } - else - { - otbMsgDebugMacro(<<"Jpeg2000ImageIO: Extension not recognized."); - return false; - } + return false; + } - if(!codec) - { - otbMsgDebugMacro(<<"Impossible to create codec."); - return false; - } - otb_openjpeg_opj_set_info_handler(codec, info_callback,00); - otb_openjpeg_opj_set_warning_handler(codec, warning_callback,00); - otb_openjpeg_opj_set_error_handler(codec, error_callback,00); + std::string lFileName(filename); - // Setting default parameters - opj_dparameters_t parameters; - otb_openjpeg_opj_set_default_decoder_parameters(¶meters); + // Creating a codec + opj_codec_t * codec = NULL; - if(! otb_openjpeg_opj_setup_decoder(codec,¶meters)) - { - otbMsgDebugMacro(<<"Impossible to set parameter."); - otb_openjpeg_opj_destroy_codec(codec); - return false; - } + if (System::SetToLower(System::GetExtension(lFileName)) == "j2k") + { + otbMsgDebugMacro(<<"Jpeg2000ImageIO: Creating J2K codec."); + codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); + } + else if (System::SetToLower(System::GetExtension(lFileName)) == "jp2" + || System::SetToLower(System::GetExtension(lFileName)) == "jpx") + { + otbMsgDebugMacro(<<"Jpeg2000ImageIO: Creating JP2 codec."); + codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); + } + else + { + otbMsgDebugMacro(<<"Jpeg2000ImageIO: Extension not recognized."); + return false; + } - // Creating a file - FILE * file = fopen(filename,"rb"); - if(!file) - { - otbMsgDebugMacro(<<"Impossible to open file."); - otb_openjpeg_opj_destroy_codec(codec); - return false; - } - // Creating a file stream - opj_stream_t * stream = otb_openjpeg_opj_stream_create_default_file_stream(file,true); - if(!stream) - { - otbMsgDebugMacro(<<"Impossible to create stream."); - otb_openjpeg_opj_destroy_codec(codec); - fclose(file); - return false; - } + if (!codec) + { + otbMsgDebugMacro(<<"Impossible to create codec."); + return false; + } + otb_openjpeg_opj_set_info_handler(codec, info_callback,00); + otb_openjpeg_opj_set_warning_handler(codec, warning_callback,00); + otb_openjpeg_opj_set_error_handler(codec, error_callback,00); + // Setting default parameters + opj_dparameters_t parameters; + otb_openjpeg_opj_set_default_decoder_parameters(¶meters); - // trying to read image header - opj_image_t * image; - OPJ_INT32 tile_x0,tile_y0; - OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; - bool resp = otb_openjpeg_opj_read_header(codec, - &image, - &tile_x0, - &tile_y0, - &tile_width, - &tile_height, - &nb_tiles_x, - &nb_tiles_y, - stream); - // Destroy the codec - otb_openjpeg_opj_stream_destroy(stream); - fclose(file); + if (! otb_openjpeg_opj_setup_decoder(codec,¶meters)) + { + otbMsgDebugMacro(<<"Impossible to set parameter."); otb_openjpeg_opj_destroy_codec(codec); - otb_openjpeg_opj_image_destroy(image); - return resp; + return false; } - - // Used to print information about this object - void JPEG2000ImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const + // Creating a file + FILE * file = fopen(filename,"rb"); + if (!file) { - Superclass::PrintSelf(os, indent); + otbMsgDebugMacro(<<"Impossible to open file."); + otb_openjpeg_opj_destroy_codec(codec); + return false; } - - // Read a 3D image (or event more bands)... not implemented yet - void JPEG2000ImageIO::ReadVolume(void*) + // Creating a file stream + opj_stream_t * stream = otb_openjpeg_opj_stream_create_default_file_stream(file,true); + if (!stream) { + otbMsgDebugMacro(<<"Impossible to create stream."); + otb_openjpeg_opj_destroy_codec(codec); + fclose(file); + return false; } - // Read image - void JPEG2000ImageIO::Read(void* buffer) - { - // unsigned long step = this->GetNumberOfComponents(); - char * charstarbuffer = static_cast<char *>(buffer); - int buffer_size_y = this->GetIORegion().GetSize()[1]; - int buffer_size_x = this->GetIORegion().GetSize()[0]; - int buffer_y0 = this->GetIORegion().GetIndex()[1]; - int buffer_x0 = this->GetIORegion().GetIndex()[0]; + // trying to read image header + opj_image_t * image; + OPJ_INT32 tile_x0,tile_y0; + OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; + bool resp = otb_openjpeg_opj_read_header(codec, + &image, + &tile_x0, + &tile_y0, + &tile_width, + &tile_height, + &nb_tiles_x, + &nb_tiles_y, + stream); + // Destroy the codec + otb_openjpeg_opj_stream_destroy(stream); + fclose(file); + otb_openjpeg_opj_destroy_codec(codec); + otb_openjpeg_opj_image_destroy(image); + return resp; +} - otbMsgDevMacro( <<" JPEG2000ImageIO::Read() "); - otbMsgDevMacro( <<" ImageDimension : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" IORegion : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - otbMsgDevMacro(<<"IORegion: "<<this->GetIORegion()); - otbMsgDevMacro(<<"Area to read: "<<buffer_x0<<" "<<buffer_y0 <<" "<< buffer_x0+buffer_size_x-1 <<" "<<buffer_y0+buffer_size_y-1 ); - otbMsgDevMacro(<<"Component type: "<<this->GetComponentTypeAsString(this->GetComponentType())); +// Used to print information about this object +void JPEG2000ImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} - // Creating openjpeg objects - if(System::SetToLower(System::GetExtension(m_FileName)) == "j2k") - { - m_Codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); - } - else if(System::SetToLower(System::GetExtension(m_FileName)) == "jp2" - || System::SetToLower(System::GetExtension(m_FileName)) == "jpx") - { - m_Codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); - } +// Read a 3D image (or event more bands)... not implemented yet +void JPEG2000ImageIO::ReadVolume(void*) +{ +} - otb_openjpeg_opj_set_info_handler(m_Codec, info_callback,00); - otb_openjpeg_opj_set_warning_handler(m_Codec, warning_callback,00); - otb_openjpeg_opj_set_error_handler(m_Codec, error_callback,00); +// Read image +void JPEG2000ImageIO::Read(void* buffer) +{ + // unsigned long step = this->GetNumberOfComponents(); + char * charstarbuffer = static_cast<char *>(buffer); - if(!m_Codec) - { - itkExceptionMacro(<<"Failed to create openjpeg codec."); - } + int buffer_size_y = this->GetIORegion().GetSize()[1]; + int buffer_size_x = this->GetIORegion().GetSize()[0]; + int buffer_y0 = this->GetIORegion().GetIndex()[1]; + int buffer_x0 = this->GetIORegion().GetIndex()[0]; - // Create default parameters - otb_openjpeg_opj_set_default_decoder_parameters(&m_Parameters); - // Set the requested region - otb_openjpeg_opj_restrict_decoding(&m_Parameters,buffer_x0,buffer_y0,buffer_x0+buffer_size_x-1,buffer_y0+buffer_size_y-1); + otbMsgDevMacro( <<" JPEG2000ImageIO::Read() "); + otbMsgDevMacro( <<" ImageDimension : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" IORegion : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - if(!otb_openjpeg_opj_setup_decoder(m_Codec,&m_Parameters)) - { - itkExceptionMacro(<<"Failed to set up decoder parameters."); - } + otbMsgDevMacro(<<"IORegion: "<<this->GetIORegion()); + otbMsgDevMacro(<<"Area to read: "<<buffer_x0<<" "<<buffer_y0 <<" "<< buffer_x0+buffer_size_x-1 <<" "<<buffer_y0+buffer_size_y-1 ); + otbMsgDevMacro(<<"Component type: "<<this->GetComponentTypeAsString(this->GetComponentType())); - m_File = fopen(m_FileName.c_str(),"rb"); + // Creating openjpeg objects + if (System::SetToLower(System::GetExtension(m_FileName)) == "j2k") + { + m_Codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); + } + else if (System::SetToLower(System::GetExtension(m_FileName)) == "jp2" + || System::SetToLower(System::GetExtension(m_FileName)) == "jpx") + { + m_Codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); + } - if(!m_File) - { - itkExceptionMacro(<<"Failed to open file: "<<m_FileName); - } + otb_openjpeg_opj_set_info_handler(m_Codec, info_callback,00); + otb_openjpeg_opj_set_warning_handler(m_Codec, warning_callback,00); + otb_openjpeg_opj_set_error_handler(m_Codec, error_callback,00); - m_OpenJpegStream = otb_openjpeg_opj_stream_create_default_file_stream(m_File,true); + if (!m_Codec) + { + itkExceptionMacro(<<"Failed to create openjpeg codec."); + } - if(!m_OpenJpegStream) - { - itkExceptionMacro(<<"Failed to create file stream."); - } + // Create default parameters + otb_openjpeg_opj_set_default_decoder_parameters(&m_Parameters); + // Set the requested region + otb_openjpeg_opj_restrict_decoding(&m_Parameters,buffer_x0,buffer_y0,buffer_x0+buffer_size_x-1,buffer_y0+buffer_size_y-1); - OPJ_INT32 tile_x0,tile_y0; - OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; - - if(!otb_openjpeg_opj_read_header(m_Codec, - &m_OpenJpegImage, - &tile_x0, - &tile_y0, - &tile_width, - &tile_height, - &nb_tiles_x, - &nb_tiles_y, - m_OpenJpegStream)) - { - itkExceptionMacro(<<"Failed to read image header."); - } + if (!otb_openjpeg_opj_setup_decoder(m_Codec,&m_Parameters)) + { + itkExceptionMacro(<<"Failed to set up decoder parameters."); + } - OPJ_BYTE * tile_data; - OPJ_INT32 tile_x1,tile_y1; - OPJ_UINT32 data_size,nb_comps; - OPJ_UINT32 tile_index; - OPJ_BOOL goesOn = true; + m_File = fopen(m_FileName.c_str(),"rb"); - while(goesOn) - { - if(! otb_openjpeg_opj_read_tile_header(m_Codec, - &tile_index, - &data_size, - &tile_x0, - &tile_y0, - &tile_x1, - &tile_y1, - &nb_comps, - &goesOn, - m_OpenJpegStream)) + if (!m_File) + { + itkExceptionMacro(<<"Failed to open file: "<<m_FileName); + } + + m_OpenJpegStream = otb_openjpeg_opj_stream_create_default_file_stream(m_File,true); + + if (!m_OpenJpegStream) + { + itkExceptionMacro(<<"Failed to create file stream."); + } + + OPJ_INT32 tile_x0,tile_y0; + OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; + + if (!otb_openjpeg_opj_read_header(m_Codec, + &m_OpenJpegImage, + &tile_x0, + &tile_y0, + &tile_width, + &tile_height, + &nb_tiles_x, + &nb_tiles_y, + m_OpenJpegStream)) + { + itkExceptionMacro(<<"Failed to read image header."); + } + + OPJ_BYTE * tile_data; + OPJ_INT32 tile_x1,tile_y1; + OPJ_UINT32 data_size,nb_comps; + OPJ_UINT32 tile_index; + OPJ_BOOL goesOn = true; + + while (goesOn) + { + if (! otb_openjpeg_opj_read_tile_header(m_Codec, + &tile_index, + &data_size, + &tile_x0, + &tile_y0, + &tile_x1, + &tile_y1, + &nb_comps, + &goesOn, + m_OpenJpegStream)) { itkExceptionMacro(<<"Error while reading tile header."); } - if(goesOn) + if (goesOn) { otbMsgDebugMacro(<<"=========================="); otbMsgDebugMacro(<<"Tile index: "<<tile_index); @@ -284,10 +287,10 @@ namespace otb tile_data = new OPJ_BYTE[data_size]; - if(! otb_openjpeg_opj_decode_tile_data(m_Codec,tile_index,tile_data,data_size,m_OpenJpegStream)) - { - itkExceptionMacro(<<"Error while reading tile data."); - } + if (! otb_openjpeg_opj_decode_tile_data(m_Codec,tile_index,tile_data,data_size,m_OpenJpegStream)) + { + itkExceptionMacro(<<"Error while reading tile data."); + } std::streamsize tile_component_size = data_size/nb_comps; std::streamoff buffer_skip = std::max(0,tile_y0-buffer_y0)*buffer_size_x*nb_comps*m_NbOctetPixel; @@ -313,192 +316,192 @@ namespace otb std::streamoff buffer_pos,tile_pos; - for(unsigned int comp = 0;comp<nb_comps;++comp) - { - for(int line = 0; line<nb_lines;++line) + for (unsigned int comp = 0;comp<nb_comps;++comp) { - buffer_pos = buffer_skip + comp*m_NbOctetPixel + line*buffer_line_size + buffer_offset_begin; - tile_pos = comp *tile_component_size + tile_skip + line*tile_line_size + tile_offset_begin; + for (int line = 0; line<nb_lines;++line) + { + buffer_pos = buffer_skip + comp*m_NbOctetPixel + line*buffer_line_size + buffer_offset_begin; + tile_pos = comp *tile_component_size + tile_skip + line*tile_line_size + tile_offset_begin; - for(int cols = 0;cols<line_size;cols++) + for (int cols = 0;cols<line_size;cols++) { - for(unsigned int octet = 0;octet<m_NbOctetPixel;++octet) - { - charstarbuffer[buffer_pos + cols*buffer_step + octet]= tile_data[tile_pos + cols*m_NbOctetPixel + octet]; - } + for (unsigned int octet = 0;octet<m_NbOctetPixel;++octet) + { + charstarbuffer[buffer_pos + cols*buffer_step + octet]= tile_data[tile_pos + cols*m_NbOctetPixel + octet]; + } } - } } + } delete[] tile_data; } - } - otbMsgDebugMacro(<<"=========================="); + } + otbMsgDebugMacro(<<"=========================="); - otb_openjpeg_opj_stream_destroy(m_OpenJpegStream); - fclose(m_File); - otb_openjpeg_opj_destroy_codec(m_Codec); - otb_openjpeg_opj_image_destroy(m_OpenJpegImage); - } + otb_openjpeg_opj_stream_destroy(m_OpenJpegStream); + fclose(m_File); + otb_openjpeg_opj_destroy_codec(m_Codec); + otb_openjpeg_opj_image_destroy(m_OpenJpegImage); +} - void JPEG2000ImageIO::ReadImageInformation() +void JPEG2000ImageIO::ReadImageInformation() +{ + if ( m_FileName.empty() == true ) { - if( m_FileName.empty() == true ) - { - itkExceptionMacro(<<"JPEG2000ImageIO: empty image filename."); - } + itkExceptionMacro(<<"JPEG2000ImageIO: empty image filename."); + } - // Creating openjpeg objects - if(System::SetToLower(System::GetExtension(m_FileName)) == "j2k") - { - m_Codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); - } - else if(System::SetToLower(System::GetExtension(m_FileName)) == "jp2" - || System::SetToLower(System::GetExtension(m_FileName)) == "jpx") - { - m_Codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); - } + // Creating openjpeg objects + if (System::SetToLower(System::GetExtension(m_FileName)) == "j2k") + { + m_Codec = otb_openjpeg_opj_create_decompress(CODEC_J2K); + } + else if (System::SetToLower(System::GetExtension(m_FileName)) == "jp2" + || System::SetToLower(System::GetExtension(m_FileName)) == "jpx") + { + m_Codec = otb_openjpeg_opj_create_decompress(CODEC_JP2); + } - otb_openjpeg_opj_set_info_handler(m_Codec, info_callback,00); - otb_openjpeg_opj_set_warning_handler(m_Codec, warning_callback,00); - otb_openjpeg_opj_set_error_handler(m_Codec, error_callback,00); + otb_openjpeg_opj_set_info_handler(m_Codec, info_callback,00); + otb_openjpeg_opj_set_warning_handler(m_Codec, warning_callback,00); + otb_openjpeg_opj_set_error_handler(m_Codec, error_callback,00); - if(!m_Codec) - { - itkExceptionMacro(<<"Failed to create openjpeg codec."); - } + if (!m_Codec) + { + itkExceptionMacro(<<"Failed to create openjpeg codec."); + } - // Create default parameters - otb_openjpeg_opj_set_default_decoder_parameters(&m_Parameters); + // Create default parameters + otb_openjpeg_opj_set_default_decoder_parameters(&m_Parameters); - if(!otb_openjpeg_opj_setup_decoder(m_Codec,&m_Parameters)) - { - itkExceptionMacro(<<"Failed to set up decoder parameters."); - } + if (!otb_openjpeg_opj_setup_decoder(m_Codec,&m_Parameters)) + { + itkExceptionMacro(<<"Failed to set up decoder parameters."); + } - m_File = fopen(m_FileName.c_str(),"rb"); + m_File = fopen(m_FileName.c_str(),"rb"); - if(!m_File) - { - itkExceptionMacro(<<"Failed to open file: "<<m_FileName); - } + if (!m_File) + { + itkExceptionMacro(<<"Failed to open file: "<<m_FileName); + } - m_OpenJpegStream = otb_openjpeg_opj_stream_create_default_file_stream(m_File,true); + m_OpenJpegStream = otb_openjpeg_opj_stream_create_default_file_stream(m_File,true); - if(!m_OpenJpegStream) - { - itkExceptionMacro(<<"Failed to create file stream."); - } + if (!m_OpenJpegStream) + { + itkExceptionMacro(<<"Failed to create file stream."); + } - OPJ_INT32 tile_x0,tile_y0; - OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; - - if(!otb_openjpeg_opj_read_header(m_Codec, - &m_OpenJpegImage, - &tile_x0, - &tile_y0, - &tile_width, - &tile_height, - &nb_tiles_x, - &nb_tiles_y, - m_OpenJpegStream)) - { - itkExceptionMacro(<<"Failed to read image header."); - } + OPJ_INT32 tile_x0,tile_y0; + OPJ_UINT32 tile_width,tile_height,nb_tiles_x,nb_tiles_y; + + if (!otb_openjpeg_opj_read_header(m_Codec, + &m_OpenJpegImage, + &tile_x0, + &tile_y0, + &tile_width, + &tile_height, + &nb_tiles_x, + &nb_tiles_y, + m_OpenJpegStream)) + { + itkExceptionMacro(<<"Failed to read image header."); + } - m_Dimensions[0]=m_OpenJpegImage->x1 - m_OpenJpegImage->x0; - m_Dimensions[1]=m_OpenJpegImage->y1 - m_OpenJpegImage->y0; + m_Dimensions[0]=m_OpenJpegImage->x1 - m_OpenJpegImage->x0; + m_Dimensions[1]=m_OpenJpegImage->y1 - m_OpenJpegImage->y0; - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); - if(m_Dimensions[0] == 0 || m_Dimensions[1] == 0) - { - itkExceptionMacro(<<"Image size is null."); - } + if (m_Dimensions[0] == 0 || m_Dimensions[1] == 0) + { + itkExceptionMacro(<<"Image size is null."); + } - this->SetNumberOfComponents(m_OpenJpegImage->numcomps); + this->SetNumberOfComponents(m_OpenJpegImage->numcomps); - this->SetFileTypeToBinary(); + this->SetFileTypeToBinary(); - unsigned int precision = m_OpenJpegImage->comps->prec; - int isSigned = m_OpenJpegImage->comps->sgnd; + unsigned int precision = m_OpenJpegImage->comps->prec; + int isSigned = m_OpenJpegImage->comps->sgnd; - if(precision<=8) - { - m_NbOctetPixel = 1; - if(isSigned) + if (precision<=8) + { + m_NbOctetPixel = 1; + if (isSigned) { SetComponentType(CHAR); } - else + else { SetComponentType(UCHAR); } - } - else if(precision<=16) - { - m_NbOctetPixel = 2; - if(isSigned) + } + else if (precision<=16) + { + m_NbOctetPixel = 2; + if (isSigned) { SetComponentType(SHORT); } - else + else { SetComponentType(USHORT); } - } - else - { - m_NbOctetPixel = 4; - if(isSigned) + } + else + { + m_NbOctetPixel = 4; + if (isSigned) { SetComponentType(INT); } - else + else { SetComponentType(UINT); } - } - - if( this->GetNumberOfComponents() == 1 ) - { - this->SetPixelType(SCALAR); - } - else - { - this->SetPixelType(VECTOR); - } - - otbMsgDebugMacro(<<"=========================="); - otbMsgDebugMacro(<<"ReadImageInformation: "); - otbMsgDebugMacro(<<"Tile (x0,y0): "<<tile_x0<<" "<<tile_y0); - otbMsgDebugMacro(<<"Tile size: "<<tile_width<<" x "<<tile_height); - otbMsgDebugMacro(<<"Number of tiles: "<<nb_tiles_x<<" "<<nb_tiles_y); - otbMsgDebugMacro(<<"Precision: "<<precision); - otbMsgDebugMacro(<<"Signed: "<<isSigned); - otbMsgDebugMacro(<<"Number of octet per value: "<<m_NbOctetPixel); - otbMsgDebugMacro(<<"=========================="); - - - otbMsgDebugMacro( <<"Driver to read: JPEG2000"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType()); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + } - otb_openjpeg_opj_stream_destroy(m_OpenJpegStream); - fclose(m_File); - otb_openjpeg_opj_destroy_codec(m_Codec); - otb_openjpeg_opj_image_destroy(m_OpenJpegImage); + if ( this->GetNumberOfComponents() == 1 ) + { + this->SetPixelType(SCALAR); + } + else + { + this->SetPixelType(VECTOR); } + otbMsgDebugMacro(<<"=========================="); + otbMsgDebugMacro(<<"ReadImageInformation: "); + otbMsgDebugMacro(<<"Tile (x0,y0): "<<tile_x0<<" "<<tile_y0); + otbMsgDebugMacro(<<"Tile size: "<<tile_width<<" x "<<tile_height); + otbMsgDebugMacro(<<"Number of tiles: "<<nb_tiles_x<<" "<<nb_tiles_y); + otbMsgDebugMacro(<<"Precision: "<<precision); + otbMsgDebugMacro(<<"Signed: "<<isSigned); + otbMsgDebugMacro(<<"Number of octet per value: "<<m_NbOctetPixel); + otbMsgDebugMacro(<<"=========================="); + + + otbMsgDebugMacro( <<"Driver to read: JPEG2000"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType()); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + + otb_openjpeg_opj_stream_destroy(m_OpenJpegStream); + fclose(m_File); + otb_openjpeg_opj_destroy_codec(m_Codec); + otb_openjpeg_opj_image_destroy(m_OpenJpegImage); +} - bool JPEG2000ImageIO::CanWriteFile( const char* filename ) - { - return false; + +bool JPEG2000ImageIO::CanWriteFile( const char* filename ) +{ + return false; // std::string lFileName(filename); // if( System::IsADirName(lFileName) == true ) // { @@ -513,11 +516,11 @@ namespace otb // { // return false; // } - } +} - void JPEG2000ImageIO::Write(const void* buffer) - { - // char * charstarbuffer = static_cast<char *>(buffer); +void JPEG2000ImageIO::Write(const void* buffer) +{ + // char * charstarbuffer = static_cast<char *>(buffer); // m_NbBands = this->GetNumberOfComponents(); @@ -741,29 +744,29 @@ namespace otb // } - } +} - void JPEG2000ImageIO::WriteImageInformation() +void JPEG2000ImageIO::WriteImageInformation() +{ + if ( m_FileName == "" ) { - if ( m_FileName == "" ) - { - itkExceptionMacro(<<"A FileName must be specified."); - } - if( CanWriteFile(m_FileName.c_str()) == false) - { - itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a JPEG2000 file"); - } + itkExceptionMacro(<<"A FileName must be specified."); + } + if ( CanWriteFile(m_FileName.c_str()) == false) + { + itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a JPEG2000 file"); + } - otbMsgDebugMacro( <<"Driver to write: JPEG2000"); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType()); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to write: JPEG2000"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType()); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} } // end namespace otb diff --git a/Code/IO/otbJPEG2000ImageIO.h b/Code/IO/otbJPEG2000ImageIO.h index 147239a372130d1d853d72cd72dd47c3f3a6fbc2..fdcadb5e2592868b0b8237abcf7abd1b296c38cc 100644 --- a/Code/IO/otbJPEG2000ImageIO.h +++ b/Code/IO/otbJPEG2000ImageIO.h @@ -24,7 +24,8 @@ #define USE_OPJ_DEPRECATED #endif -extern "C" { +extern "C" +{ #include "otb_openjpeg.h" } @@ -62,7 +63,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -80,7 +84,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ diff --git a/Code/IO/otbKMLVectorDataIO.h b/Code/IO/otbKMLVectorDataIO.h index e84bf368eb1b4b188c896bf0459e47428103841b..6dd677dc40ecac067d188a83c4997314941d814b 100644 --- a/Code/IO/otbKMLVectorDataIO.h +++ b/Code/IO/otbKMLVectorDataIO.h @@ -42,8 +42,8 @@ namespace otb */ template <class TData> class ITK_EXPORT KMLVectorDataIO - : public VectorDataIOBase<TData> - { + : public VectorDataIOBase<TData> +{ public: /** Standard class typedefs. */ @@ -89,10 +89,13 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the VectorDataIO can stream read the specified file */ - virtual bool CanStreamRead(){ return false; }; + virtual bool CanStreamRead() + { + return false; + }; -/* /\** Set the spacing and dimention information for the set filename. *\/ */ -/* virtual void ReadVectorDataInformation(); */ + /* /\** Set the spacing and dimention information for the set filename. *\/ */ + /* virtual void ReadVectorDataInformation(); */ /** Reads the data from disk into the data structure provided. */ virtual void Read(VectorDataPointerType data); @@ -104,11 +107,14 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the VectorDataIO can stream write the specified file */ - virtual bool CanStreamWrite() { return false; }; + virtual bool CanStreamWrite() + { + return false; + }; -/* /\** Writes the spacing and dimentions of the image. */ -/* * Assumes SetFileName has been called with a valid file name. *\/ */ -/* virtual void WriteVectorDataInformation(); */ + /* /\** Writes the spacing and dimentions of the image. */ + /* * Assumes SetFileName has been called with a valid file name. *\/ */ + /* virtual void WriteVectorDataInformation(); */ /** Writes the data to disk from the data structure provided */ virtual void Write(VectorDataConstPointerType data); diff --git a/Code/IO/otbKMLVectorDataIO.txx b/Code/IO/otbKMLVectorDataIO.txx index 30ab76bb8dbf685fe55a6234c71054864e412ee7..a7366a153533d5761f69db5617fadcc80fe70156 100644 --- a/Code/IO/otbKMLVectorDataIO.txx +++ b/Code/IO/otbKMLVectorDataIO.txx @@ -61,683 +61,714 @@ using kmldom::InnerBoundaryIsPtr; namespace otb { - template<class TData> - KMLVectorDataIO<TData> - ::KMLVectorDataIO() +template<class TData> +KMLVectorDataIO<TData> +::KMLVectorDataIO() +{ +} +template<class TData> +KMLVectorDataIO<TData>::~KMLVectorDataIO() +{ +} +template<class TData> +bool +KMLVectorDataIO<TData>::CanReadFile( const char* filename ) +{ + std::string lFileName(filename); + if ( System::IsADirName(lFileName) == true ) { + return false; } - template<class TData> - KMLVectorDataIO<TData>::~KMLVectorDataIO() + if ( System::SetToLower(System::GetExtension(lFileName)) != "kml" ) { + return false; } - template<class TData> - bool - KMLVectorDataIO<TData>::CanReadFile( const char* filename ) + if ( kmlbase::File::Exists(lFileName) == false ) { - std::string lFileName(filename); - if( System::IsADirName(lFileName) == true ) - { - return false; - } - if( System::SetToLower(System::GetExtension(lFileName)) != "kml" ) - { - return false; - } - if( kmlbase::File::Exists(lFileName) == false ) - { - return false; - } + return false; + } - std::string kml; - return (kmlbase::File::ReadFileToString(lFileName, &kml) ); + std::string kml; + return (kmlbase::File::ReadFileToString(lFileName, &kml) ); +} + +// Get the features of the kml file, read into the root +template<class TData> +const FeaturePtr +KMLVectorDataIO<TData>::GetRootFeature(const ElementPtr& root) +{ + const KmlPtr kml = kmldom::AsKml(root); + if (kml && kml->has_feature()) + { + return kml->get_feature(); } + return kmldom::AsFeature(root); +} - // Get the features of the kml file, read into the root - template<class TData> - const FeaturePtr - KMLVectorDataIO<TData>::GetRootFeature(const ElementPtr& root) +// Print the selected feature +template<class TData> +void +KMLVectorDataIO<TData>::PrintIndented(std::string item, int depth) +{ + while (depth--) { - const KmlPtr kml = kmldom::AsKml(root); - if (kml && kml->has_feature()) { - return kml->get_feature(); - } - return kmldom::AsFeature(root); + std::cout << " "; } + std::cout << item <<std::endl; +} - // Print the selected feature - template<class TData> - void - KMLVectorDataIO<TData>::PrintIndented(std::string item, int depth) +template<class TData> +void +KMLVectorDataIO<TData>::WalkFeature(const FeaturePtr& feature, DataNodePointerType father) +{ + + DataNodePointerType node = NULL; + + if (feature) { - while (depth--) + if (const ContainerPtr container = kmldom::AsContainer(feature)) { - std::cout << " "; + WalkContainer(container,father); } - std::cout << item <<std::endl; + else if (const PlacemarkPtr placemark = kmldom::AsPlacemark(feature)) + { + WalkGeometry(placemark->get_geometry(),father); + } + + // The Read() method is not exhaustive it is possible to add the read of the "link", + // the style (iconStyle, LineStyle...). Then into the containers we also can find the fields : + // <visibility> <description> <LookAt>... cf. code.google.com/apis/kml/documentation/kmlelementssinmaps.html } + return; +} - template<class TData> - void - KMLVectorDataIO<TData>::WalkFeature(const FeaturePtr& feature, DataNodePointerType father) - { +template<class TData> +void +KMLVectorDataIO<TData>::WalkContainer(const ContainerPtr& container, DataNodePointerType father) +{ - DataNodePointerType node = NULL; + DataNodePointerType node = NULL; - if (feature) + for (size_t i = 0; i < container->get_feature_array_size(); ++i) + { + FeaturePtr feature = container->get_feature_array_at(i); + switch (feature->Type()) { - if (const ContainerPtr container = kmldom::AsContainer(feature)) + case kmldom::Type_Document: + { + DataNodePointerType document = DataNodeType::New(); + document->SetNodeType(DOCUMENT); + document->SetNodeId(feature->get_id()); + if (feature->has_name()) { - WalkContainer(container,father); + document->SetField("name",feature->get_name()); } - else if (const PlacemarkPtr placemark = kmldom::AsPlacemark(feature)) + m_Tree->Add(document,father); + WalkFeature(feature,document); + break; + } + case kmldom::Type_Folder: + { + DataNodePointerType folder = DataNodeType::New(); + folder->SetNodeType(FOLDER); + folder->SetNodeId(feature->get_id()); + if (feature->has_name()) { - WalkGeometry(placemark->get_geometry(),father); + folder->SetField("name",feature->get_name()); } - - // The Read() method is not exhaustive it is possible to add the read of the "link", - // the style (iconStyle, LineStyle...). Then into the containers we also can find the fields : - // <visibility> <description> <LookAt>... cf. code.google.com/apis/kml/documentation/kmlelementssinmaps.html + m_Tree->Add(folder,father); + WalkFeature(feature,folder); + break; + } + case kmldom::Type_GroundOverlay: + { + WalkFeature(feature,father); + break; + } + case kmldom::Type_NetworkLink: + { + WalkFeature(feature,father); + break; + } + case kmldom::Type_PhotoOverlay: + { + WalkFeature(feature,father); + break; + } + case kmldom::Type_Placemark: + { + // We just ignore placemarks + WalkFeature(feature,father); + break; + } + case kmldom::Type_ScreenOverlay: + { + WalkFeature(feature,father); + break; + } + default: + break; } - return; - } - template<class TData> - void - KMLVectorDataIO<TData>::WalkContainer(const ContainerPtr& container, DataNodePointerType father) - { + } + return; +} - DataNodePointerType node = NULL; +// Walk through a geometry and create a GeometryNode +template<class TData> +void +KMLVectorDataIO<TData>::WalkGeometry(const GeometryPtr& geometry, DataNodePointerType father) +{ - for (size_t i = 0; i < container->get_feature_array_size(); ++i) - { - FeaturePtr feature = container->get_feature_array_at(i); - switch (feature->Type()) - { - case kmldom::Type_Document: - { - DataNodePointerType document = DataNodeType::New(); - document->SetNodeType(DOCUMENT); - document->SetNodeId(feature->get_id()); - if (feature->has_name()) { - document->SetField("name",feature->get_name()); - } - m_Tree->Add(document,father); - WalkFeature(feature,document); - break; - } - case kmldom::Type_Folder: - { - DataNodePointerType folder = DataNodeType::New(); - folder->SetNodeType(FOLDER); - folder->SetNodeId(feature->get_id()); - if (feature->has_name()) { - folder->SetField("name",feature->get_name()); - } - m_Tree->Add(folder,father); - WalkFeature(feature,folder); - break; - } - case kmldom::Type_GroundOverlay: - { - WalkFeature(feature,father); - break; - } - case kmldom::Type_NetworkLink: - { - WalkFeature(feature,father); - break; - } - case kmldom::Type_PhotoOverlay: - { - WalkFeature(feature,father); - break; - } - case kmldom::Type_Placemark: - { - // We just ignore placemarks - WalkFeature(feature,father); - break; - } - case kmldom::Type_ScreenOverlay: - { - WalkFeature(feature,father); - break; - } - default: - break; - } + // Creation of a node + DataNodePointerType node = NULL; - } + if (!geometry) + { return; } - - // Walk through a geometry and create a GeometryNode - template<class TData> - void - KMLVectorDataIO<TData>::WalkGeometry(const GeometryPtr& geometry, DataNodePointerType father) + // Create a Node with the Geometry type. + switch (geometry->Type()) + { + case kmldom::Type_Point: + { + node = ConvertGeometryToPointNode(geometry); + m_Tree->Add(node,father); + break; + } + case kmldom::Type_LineString: + { + node = ConvertGeometryToLineStringNode(geometry); + m_Tree->Add(node,father); + break; + } + case kmldom::Type_LinearRing: + { + node = ConvertGeometryToLinearRingNode(geometry); + m_Tree->Add(node,father); + break; + } + case kmldom::Type_Polygon: + { + node = ConvertGeometryToPolygonNode(geometry); + m_Tree->Add(node,father); + break; + } + case kmldom::Type_MultiGeometry: { - - // Creation of a node - DataNodePointerType node = NULL; - - if (!geometry) - { - return; - } - // Create a Node with the Geometry type. - switch(geometry->Type()) - { - case kmldom::Type_Point: - { - node = ConvertGeometryToPointNode(geometry); - m_Tree->Add(node,father); - break; - } - case kmldom::Type_LineString: - { - node = ConvertGeometryToLineStringNode(geometry); - m_Tree->Add(node,father); - break; - } - case kmldom::Type_LinearRing: - { - node = ConvertGeometryToLinearRingNode(geometry); - m_Tree->Add(node,father); - break; - } - case kmldom::Type_Polygon: - { - node = ConvertGeometryToPolygonNode(geometry); - m_Tree->Add(node,father); - break; - } - case kmldom::Type_MultiGeometry: - { // this case is treated downer - break; - } - case kmldom::Type_Model: - { - break; - } - default: // KML has 6 types of Geometry. - break; - } + break; + } + case kmldom::Type_Model: + { + break; + } + default: // KML has 6 types of Geometry. + break; + } - // Recurse into <MultiGeometry>. - if (const MultiGeometryPtr multigeometry = kmldom::AsMultiGeometry(geometry)) + // Recurse into <MultiGeometry>. + if (const MultiGeometryPtr multigeometry = kmldom::AsMultiGeometry(geometry)) + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_COLLECTION); + m_Tree->Add(multi,father); + for (size_t i = 0; i < multigeometry->get_geometry_array_size(); ++i) { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_COLLECTION); - m_Tree->Add(multi,father); - for (size_t i = 0; i < multigeometry->get_geometry_array_size(); ++i) - { - WalkGeometry(multigeometry->get_geometry_array_at(i),multi); - } + WalkGeometry(multigeometry->get_geometry_array_at(i),multi); } - return; } + return; +} + +template<class TData> +typename KMLVectorDataIO<TData> +::DataNodePointerType +KMLVectorDataIO<TData> +::ConvertGeometryToPointNode(const GeometryPtr& geometry) +{ - template<class TData> - typename KMLVectorDataIO<TData> - ::DataNodePointerType - KMLVectorDataIO<TData> - ::ConvertGeometryToPointNode(const GeometryPtr& geometry) + if (geometry == NULL) { + itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to PointNode"); + } - if(geometry == NULL) - { - itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to PointNode"); - } + const PointPtr pt = kmldom::AsPoint(geometry); - const PointPtr pt = kmldom::AsPoint(geometry); + PointType otbPoint; + otbPoint.Fill(0); + otbPoint[0] = static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_longitude()); + otbPoint[1] = static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_latitude()); - PointType otbPoint; - otbPoint.Fill(0); - otbPoint[0] = static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_longitude()); - otbPoint[1] = static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_latitude()); + if (DataNodeType::Dimension > 2) + { + otbPoint[2]=static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_altitude()); + } - if(DataNodeType::Dimension > 2) - { - otbPoint[2]=static_cast<typename DataNodeType::PrecisionType>(pt->get_coordinates()->get_coordinates_array_at(0).get_altitude()); - } + DataNodePointerType node = DataNodeType::New(); + node->SetPoint(otbPoint); + return node; +} + +template<class TData> +typename KMLVectorDataIO<TData> +::DataNodePointerType +KMLVectorDataIO<TData> +::ConvertGeometryToLineStringNode(const GeometryPtr& geometry) +{ - DataNodePointerType node = DataNodeType::New(); - node->SetPoint(otbPoint); - return node; + if (geometry == NULL) + { + itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); } - template<class TData> - typename KMLVectorDataIO<TData> - ::DataNodePointerType - KMLVectorDataIO<TData> - ::ConvertGeometryToLineStringNode(const GeometryPtr& geometry) + const LineStringPtr ls = kmldom::AsLineString(geometry); + const CoordinatesPtr coords = ls->get_coordinates(); + int array_size = coords->get_coordinates_array_size(); + + LinePointerType line = LineType::New(); + for (int i=0;i<array_size;i++) { + typename LineType::VertexType vertex; + vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); + vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); - if(geometry == NULL) + if (DataNodeType::Dimension > 2) { - itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); + vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); } + line->AddVertex(vertex); + } - const LineStringPtr ls = kmldom::AsLineString(geometry); - const CoordinatesPtr coords = ls->get_coordinates(); - int array_size = coords->get_coordinates_array_size(); - - LinePointerType line = LineType::New(); - for(int i=0;i<array_size;i++) - { - typename LineType::VertexType vertex; - vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); - vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); + DataNodePointerType node = DataNodeType::New(); + node->SetLine(line); - if(DataNodeType::Dimension > 2) - { - vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); - } - line->AddVertex(vertex); - } + return node; +} - DataNodePointerType node = DataNodeType::New(); - node->SetLine(line); +template<class TData> +typename KMLVectorDataIO<TData> +::DataNodePointerType +KMLVectorDataIO<TData> +::ConvertGeometryToLinearRingNode(const GeometryPtr& geometry) +{ - return node; + if (geometry == NULL) + { + itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); } - template<class TData> - typename KMLVectorDataIO<TData> - ::DataNodePointerType - KMLVectorDataIO<TData> - ::ConvertGeometryToLinearRingNode(const GeometryPtr& geometry) + const LinearRingPtr lr = kmldom::AsLinearRing(geometry); + const CoordinatesPtr coords = lr->get_coordinates(); + int array_size = coords->get_coordinates_array_size(); + + LinePointerType line = LineType::New(); + for (int i=0;i<array_size;i++) { + typename LineType::VertexType vertex; + vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); + vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); - if(geometry == NULL) + if (DataNodeType::Dimension > 2) { - itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); + vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); } + line->AddVertex(vertex); + } - const LinearRingPtr lr = kmldom::AsLinearRing(geometry); - const CoordinatesPtr coords = lr->get_coordinates(); - int array_size = coords->get_coordinates_array_size(); - - LinePointerType line = LineType::New(); - for(int i=0;i<array_size;i++) - { - typename LineType::VertexType vertex; - vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); - vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); + DataNodePointerType node = DataNodeType::New(); + node->SetLine(line); - if(DataNodeType::Dimension > 2) - { - vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); - } - line->AddVertex(vertex); - } + return node; +} - DataNodePointerType node = DataNodeType::New(); - node->SetLine(line); +template<class TData> +typename KMLVectorDataIO<TData> +::DataNodePointerType +KMLVectorDataIO<TData> +::ConvertGeometryToPolygonNode(const GeometryPtr& geometry) +{ - return node; + if (geometry == NULL) + { + itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); } - template<class TData> - typename KMLVectorDataIO<TData> - ::DataNodePointerType - KMLVectorDataIO<TData> - ::ConvertGeometryToPolygonNode(const GeometryPtr& geometry) - { + // Get the polygon + const PolygonPtr polygonKml = kmldom::AsPolygon(geometry); + PolygonPointerType extRing = PolygonType::New(); + PolygonListPointerType intRings = PolygonListType::New(); - if(geometry == NULL) + // Read the outerboundaryis of the polygon + if ( polygonKml->has_outerboundaryis()) + { + const OuterBoundaryIsPtr outerboundaryis = polygonKml->get_outerboundaryis(); + if (outerboundaryis->has_linearring()) { - itkGenericExceptionMacro(<<"Failed to convert GeometryPtr to LineNode"); - } + const LinearRingPtr lr = outerboundaryis->get_linearring(); + const CoordinatesPtr coords = lr->get_coordinates(); + int array_size = coords->get_coordinates_array_size(); - // Get the polygon - const PolygonPtr polygonKml = kmldom::AsPolygon(geometry); - PolygonPointerType extRing = PolygonType::New(); - PolygonListPointerType intRings = PolygonListType::New(); - // Read the outerboundaryis of the polygon - if ( polygonKml->has_outerboundaryis()) - { - const OuterBoundaryIsPtr outerboundaryis = polygonKml->get_outerboundaryis(); - if(outerboundaryis->has_linearring()) + for (int i=0;i<array_size;i++) { - const LinearRingPtr lr = outerboundaryis->get_linearring(); - const CoordinatesPtr coords = lr->get_coordinates(); - int array_size = coords->get_coordinates_array_size(); - + typename PolygonType::VertexType vertex; + vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); + vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); - for(int i=0;i<array_size;i++) + if (DataNodeType::Dimension > 2) { - typename PolygonType::VertexType vertex; - vertex[0] = coords->get_coordinates_array_at(i).get_longitude(); - vertex[1] = coords->get_coordinates_array_at(i).get_latitude(); - - if(DataNodeType::Dimension > 2) - { - vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); - } - extRing->AddVertex(vertex); + vertex[2]= coords->get_coordinates_array_at(i).get_altitude(); } + extRing->AddVertex(vertex); } } + } - // Read the innerboundaryis of the polygon - for (unsigned int intRingIndex=0;intRingIndex<polygonKml->get_innerboundaryis_array_size();intRingIndex++) + // Read the innerboundaryis of the polygon + for (unsigned int intRingIndex=0;intRingIndex<polygonKml->get_innerboundaryis_array_size();intRingIndex++) + { + const InnerBoundaryIsPtr innerboundaryis = polygonKml->get_innerboundaryis_array_at(intRingIndex); + if (innerboundaryis->has_linearring()) { - const InnerBoundaryIsPtr innerboundaryis = polygonKml->get_innerboundaryis_array_at(intRingIndex); - if(innerboundaryis->has_linearring()) + const LinearRingPtr lr = innerboundaryis->get_linearring(); + const CoordinatesPtr coords = lr->get_coordinates(); + int array_size = coords->get_coordinates_array_size(); + PolygonPointerType ring = PolygonType::New(); + + for (int pIndex=0;pIndex<array_size;pIndex++) { - const LinearRingPtr lr = innerboundaryis->get_linearring(); - const CoordinatesPtr coords = lr->get_coordinates(); - int array_size = coords->get_coordinates_array_size(); - PolygonPointerType ring = PolygonType::New(); + typename PolygonType::VertexType vertex; + vertex[0] = coords->get_coordinates_array_at(pIndex).get_longitude(); + vertex[1] = coords->get_coordinates_array_at(pIndex).get_latitude(); - for(int pIndex=0;pIndex<array_size;pIndex++) + if (DataNodeType::Dimension > 2) { - typename PolygonType::VertexType vertex; - vertex[0] = coords->get_coordinates_array_at(pIndex).get_longitude(); - vertex[1] = coords->get_coordinates_array_at(pIndex).get_latitude(); - - if(DataNodeType::Dimension > 2) - { - vertex[2]= coords->get_coordinates_array_at(pIndex).get_altitude(); - } - ring->AddVertex(vertex); + vertex[2]= coords->get_coordinates_array_at(pIndex).get_altitude(); } - intRings->PushBack(ring); + ring->AddVertex(vertex); } + intRings->PushBack(ring); } + } - DataNodePointerType node = DataNodeType::New(); - node->SetPolygonExteriorRing(extRing); - node->SetPolygonInteriorRings(intRings); + DataNodePointerType node = DataNodeType::New(); + node->SetPolygonExteriorRing(extRing); + node->SetPolygonInteriorRings(intRings); - return node; - } + return node; +} + +// Used to print information about this object +template<class TData> +void +KMLVectorDataIO<TData>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +// Read vector data +template<class TData> +void +KMLVectorDataIO<TData> +::Read(VectorDataPointerType data) +{ - // Used to print information about this object - template<class TData> - void - KMLVectorDataIO<TData>::PrintSelf(std::ostream& os, itk::Indent indent) const + std::string kml; + bool status = kmlbase::File::ReadFileToString(this->m_FileName, &kml); + if ( status == false ) { - Superclass::PrintSelf(os, indent); + itkExceptionMacro(<<"Failed to open KML data file "<<this->m_FileName); } - // Read vector data - template<class TData> - void - KMLVectorDataIO<TData> - ::Read(VectorDataPointerType data) - { + std::cout<<this->m_FileName<<std::endl; - std::string kml; - bool status = kmlbase::File::ReadFileToString(this->m_FileName, &kml); - if( status == false ) - { - itkExceptionMacro(<<"Failed to open KML data file "<<this->m_FileName); - } + otbMsgDebugMacro( <<"Driver to read: KML"); + otbMsgDebugMacro( <<"Reading file: "<< this->m_FileName); - std::cout<<this->m_FileName<<std::endl; - otbMsgDebugMacro( <<"Driver to read: KML"); - otbMsgDebugMacro( <<"Reading file: "<< this->m_FileName); + // Parse the file. + std::string errors; + ElementPtr root = kmldom::Parse(kml, &errors); + if (!root) + { + itkExceptionMacro(<<"Failed to open KML data file "<<errors); + } - // Parse the file. - std::string errors; - ElementPtr root = kmldom::Parse(kml, &errors); + //Fill up projection information + //for KML files, this is geographic coordinates - if (!root) - { - itkExceptionMacro(<<"Failed to open KML data file "<<errors); - } + std::string projectionRef = "GEOGCS[\"GCS_WGS_1984\", DATUM[\"WGS_1984\", SPHEROID[\"WGS_1984\",6378137,298.257223563]], PRIMEM[\"Greenwich\",0], UNIT[\"Degree\",0.017453292519943295]]"; + itk::MetaDataDictionary & dict = data->GetMetaDataDictionary(); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); - //Fill up projection information - //for KML files, this is geographic coordinates + const FeaturePtr feature = GetRootFeature(root); + if (feature) + { - std::string projectionRef = "GEOGCS[\"GCS_WGS_1984\", DATUM[\"WGS_1984\", SPHEROID[\"WGS_1984\",6378137,298.257223563]], PRIMEM[\"Greenwich\",0], UNIT[\"Degree\",0.017453292519943295]]"; - itk::MetaDataDictionary & dict = data->GetMetaDataDictionary(); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); + // Retrieving root node + m_Tree = data->GetDataTree(); + DataNodePointerType rootNode = m_Tree->GetRoot()->Get(); - const FeaturePtr feature = GetRootFeature(root); - if (feature) { + DataNodePointerType document = DataNodeType::New(); + document->SetNodeType(DOCUMENT); + m_Tree->Add(document,rootNode); - // Retrieving root node - m_Tree = data->GetDataTree(); - DataNodePointerType rootNode = m_Tree->GetRoot()->Get(); + // Walk Feature (get the Placemarks... and walk into them) //ENGLISH ?? + WalkFeature(feature,document); - DataNodePointerType document = DataNodeType::New(); - document->SetNodeType(DOCUMENT); - m_Tree->Add(document,rootNode); + } + else + { + itkExceptionMacro(<<"No root feature"); + } - // Walk Feature (get the Placemarks... and walk into them) //ENGLISH ?? - WalkFeature(feature,document); + // std::cout<< m_Tree <<std::endl; +} - } else { - itkExceptionMacro(<<"No root feature"); - } - // std::cout<< m_Tree <<std::endl; +template<class TData> +bool KMLVectorDataIO<TData>::CanWriteFile( const char* filename ) +{ + std::string lFileName(filename); + if ( System::IsADirName(lFileName) == true ) + { + return false; + } + if ( System::SetToLower(System::GetExtension(lFileName)) != "kml" ) + { + return false; } + return true; +} + +template<class TData> +void KMLVectorDataIO<TData>::Write(const VectorDataConstPointerType data) +{ + // Retrieve data required for georeferencing - template<class TData> - bool KMLVectorDataIO<TData>::CanWriteFile( const char* filename ) + std::string projectionRefWkt = data->GetProjectionRef(); + OGRSpatialReference * oSRS = new OGRSpatialReference(projectionRefWkt.c_str()); + if ( !oSRS->IsGeographic() ) { - std::string lFileName(filename); - if( System::IsADirName(lFileName) == true ) - { - return false; - } - if( System::SetToLower(System::GetExtension(lFileName)) != "kml" ) - { - return false; - } - return true; + itkWarningMacro(<<"Vector data should be reprojected in geographic coordinates" + << " before saving to KML. Please use otbVectorDataProjectionFilter. " + << " The projection information is currently: " << projectionRefWkt + << "\n We assume that you know what you're doing and proceed to save the KML file."); } + delete oSRS; - template<class TData> - void KMLVectorDataIO<TData>::Write(const VectorDataConstPointerType data) + //Create the factory + KmlFactory* factory = KmlFactory::GetFactory(); + if (factory == NULL) { + itkExceptionMacro(<<"Impossible to create the KML Factory to write file "<<this->m_FileName); + } + + KmlPtr kml = factory->CreateKml(); + + // Retrieving root node + DataTreeConstPointerType tree = data->GetDataTree(); + DataNodePointerType root = tree->GetRoot()->Get(); + + typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; - // Retrieve data required for georeferencing + TreeIteratorType it(tree); + it.GoToBegin(); - std::string projectionRefWkt = data->GetProjectionRef(); - OGRSpatialReference * oSRS = new OGRSpatialReference(projectionRefWkt.c_str()); - if( !oSRS->IsGeographic() ) + DocumentPtr currentDocument = NULL; + FolderPtr currentFolder = NULL; + MultiGeometryPtr currentMultiGeometry = NULL; + PolygonPtr currentPolygon = NULL; + OuterBoundaryIsPtr outerboundaryis = NULL; + InnerBoundaryIsPtr innerboundaryis = NULL; + + + // Note that we force a precise structure when we write a kml file. + // We will necessary have a <document> that will contain a <folder>. + // And in a folder there automatically will be one or several <placemark>. + while (!it.IsAtEnd()) + { + switch (it.Get()->GetNodeType()) { - itkWarningMacro(<<"Vector data should be reprojected in geographic coordinates" - << " before saving to KML. Please use otbVectorDataProjectionFilter. " - << " The projection information is currently: " << projectionRefWkt - << "\n We assume that you know what you're doing and proceed to save the KML file."); + case ROOT: + { + break; } - delete oSRS; - - //Create the factory - KmlFactory* factory = KmlFactory::GetFactory(); - if(factory == NULL) + case DOCUMENT: { - itkExceptionMacro(<<"Impossible to create the KML Factory to write file "<<this->m_FileName); + DocumentPtr document = factory->CreateDocument(); + if (it.Get()->HasField("name")) + { + std::string fieldname = it.Get()->GetField("name"); + document->set_name(fieldname); + } + kml->set_feature(document); + currentDocument = document; + break; } + case FOLDER: + { + FolderPtr folder = factory->CreateFolder(); + std::string fieldname = it.Get()->GetField("name"); + folder->set_name(fieldname); + currentDocument->add_feature(folder); + currentFolder = folder; + break; + } + case FEATURE_POINT: + { + // Create <coordinates> + CoordinatesPtr coordinates = factory->CreateCoordinates(); + PointType pointCoord = it.Get()->GetPoint(); + if (DataNodeType::Dimension>2) + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]); + } + else + { + coordinates->add_latlng(pointCoord[1],pointCoord[0]); + } - KmlPtr kml = factory->CreateKml(); + // Create <Point> and give it <coordinates>. + PointPtr point = factory->CreatePoint(); + point->set_coordinates(coordinates); - // Retrieving root node - DataTreeConstPointerType tree = data->GetDataTree(); - DataNodePointerType root = tree->GetRoot()->Get(); + if (currentMultiGeometry != NULL) + { + currentMultiGeometry->add_geometry(point); + } + else + { - typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; + PlacemarkPtr placemark = factory->CreatePlacemark(); + placemark->set_geometry(point); + if (currentFolder!= NULL) + { + currentFolder->add_feature(placemark); + } + else + { + currentDocument->add_feature(placemark); + } - TreeIteratorType it(tree); - it.GoToBegin(); + } + break; + } + case FEATURE_LINE: + { - DocumentPtr currentDocument = NULL; - FolderPtr currentFolder = NULL; - MultiGeometryPtr currentMultiGeometry = NULL; - PolygonPtr currentPolygon = NULL; - OuterBoundaryIsPtr outerboundaryis = NULL; - InnerBoundaryIsPtr innerboundaryis = NULL; + VertexListConstPointerType vertexList = it.Get()->GetLine()->GetVertexList(); + // Create <coordinates> + CoordinatesPtr coordinates = factory->CreateCoordinates(); + LineStringPtr line = factory->CreateLineString(); - // Note that we force a precise structure when we write a kml file. - // We will necessary have a <document> that will contain a <folder>. - // And in a folder there automatically will be one or several <placemark>. - while(!it.IsAtEnd()) - { - switch(it.Get()->GetNodeType()) + typename VertexListType::ConstIterator vIt = vertexList->Begin(); + + while (vIt != vertexList->End()) { - case ROOT: + VertexType pointCoord = vIt.Value(); + if (DataNodeType::Dimension>2) { - break; + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]); } - case DOCUMENT: + else { - DocumentPtr document = factory->CreateDocument(); - if(it.Get()->HasField("name")) - { - std::string fieldname = it.Get()->GetField("name"); - document->set_name(fieldname); - } - kml->set_feature(document); - currentDocument = document; - break; + coordinates->add_latlng(pointCoord[1],pointCoord[0]); } - case FOLDER: + line->set_coordinates(coordinates); + ++vIt; + } + + if (currentMultiGeometry != NULL) + { + currentMultiGeometry->add_geometry(line); + } + else + { + PlacemarkPtr placemark = factory->CreatePlacemark(); + placemark->set_geometry(line); + if (currentFolder!= NULL) { - FolderPtr folder = factory->CreateFolder(); - std::string fieldname = it.Get()->GetField("name"); - folder->set_name(fieldname); - currentDocument->add_feature(folder); - currentFolder = folder; - break; + currentFolder->add_feature(placemark); } - case FEATURE_POINT: + else { - // Create <coordinates> - CoordinatesPtr coordinates = factory->CreateCoordinates(); - PointType pointCoord = it.Get()->GetPoint(); - if(DataNodeType::Dimension>2) - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]); - } - else - { - coordinates->add_latlng(pointCoord[1],pointCoord[0]); - } - - // Create <Point> and give it <coordinates>. - PointPtr point = factory->CreatePoint(); - point->set_coordinates(coordinates); - - if (currentMultiGeometry != NULL) - { - currentMultiGeometry->add_geometry(point); - } - else - { - - PlacemarkPtr placemark = factory->CreatePlacemark(); - placemark->set_geometry(point); - if (currentFolder!= NULL) - { - currentFolder->add_feature(placemark); - } - else - { - currentDocument->add_feature(placemark); - } - - } - break; + currentDocument->add_feature(placemark); } - case FEATURE_LINE: - { + } + break; + } + case FEATURE_POLYGON: + {//TODO refine the solution of drawing the polygon 1m above the ground + // In a polygon we just can find any LinearRings + LinearRingPtr line = factory->CreateLinearRing(); + PolygonPtr polygon = factory->CreatePolygon(); - VertexListConstPointerType vertexList = it.Get()->GetLine()->GetVertexList(); + polygon->set_extrude(true); + polygon->set_altitudemode(1);//ALTITUDEMODE_RELATIVETOGROUND - // Create <coordinates> - CoordinatesPtr coordinates = factory->CreateCoordinates(); - LineStringPtr line = factory->CreateLineString(); + CoordinatesPtr coordinates = factory->CreateCoordinates(); + OuterBoundaryIsPtr outerboundaryis = factory->CreateOuterBoundaryIs(); + InnerBoundaryIsPtr innerboundaryis = factory->CreateInnerBoundaryIs(); - typename VertexListType::ConstIterator vIt = vertexList->Begin(); + VertexListConstPointerType vertexList = it.Get()->GetPolygonExteriorRing()->GetVertexList(); - while(vIt != vertexList->End()) - { - VertexType pointCoord = vIt.Value(); - if(DataNodeType::Dimension>2) - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]); - } - else - { - coordinates->add_latlng(pointCoord[1],pointCoord[0]); - } - line->set_coordinates(coordinates); - ++vIt; - } + typename VertexListType::ConstIterator vIt = vertexList->Begin(); - if (currentMultiGeometry != NULL) - { - currentMultiGeometry->add_geometry(line); - } - else - { - PlacemarkPtr placemark = factory->CreatePlacemark(); - placemark->set_geometry(line); - if (currentFolder!= NULL) - { - currentFolder->add_feature(placemark); - } - else - { - currentDocument->add_feature(placemark); - } - } - break; + if (vIt == vertexList->End()) + { + itkExceptionMacro(<<"Polygon is empty"); + } + + while (vIt != vertexList->End()) + { + VertexType pointCoord = vIt.Value(); + if (DataNodeType::Dimension>2) + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues + } + else + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues } - case FEATURE_POLYGON: - {//TODO refine the solution of drawing the polygon 1m above the ground - // In a polygon we just can find any LinearRings - LinearRingPtr line = factory->CreateLinearRing(); - PolygonPtr polygon = factory->CreatePolygon(); - polygon->set_extrude(true); - polygon->set_altitudemode(1);//ALTITUDEMODE_RELATIVETOGROUND + line->set_coordinates(coordinates); + ++vIt; + } - CoordinatesPtr coordinates = factory->CreateCoordinates(); - OuterBoundaryIsPtr outerboundaryis = factory->CreateOuterBoundaryIs(); - InnerBoundaryIsPtr innerboundaryis = factory->CreateInnerBoundaryIs(); + //Adding the first point again to close the polygon + vIt = vertexList->Begin(); + VertexType pointCoord = vIt.Value(); + if (DataNodeType::Dimension>2) + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues + } + else + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues + } + line->set_coordinates(coordinates); - VertexListConstPointerType vertexList = it.Get()->GetPolygonExteriorRing()->GetVertexList(); + outerboundaryis->set_linearring(line); + polygon->set_outerboundaryis(outerboundaryis); - typename VertexListType::ConstIterator vIt = vertexList->Begin(); + // Retrieving internal rings as well + for (typename PolygonListType::Iterator pIt = it.Get()->GetPolygonInteriorRings()->Begin(); + pIt!=it.Get()->GetPolygonInteriorRings()->End();++pIt) + { - if (vIt == vertexList->End()) - { - itkExceptionMacro(<<"Polygon is empty"); - } + vertexList = pIt.Get()->GetVertexList(); + vIt = vertexList->Begin(); - while(vIt != vertexList->End()) - { - VertexType pointCoord = vIt.Value(); - if(DataNodeType::Dimension>2) - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - else - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - - line->set_coordinates(coordinates); - ++vIt; - } - - //Adding the first point again to close the polygon + while (vIt != vertexList->End()) + { vIt = vertexList->Begin(); VertexType pointCoord = vIt.Value(); - if(DataNodeType::Dimension>2) + if (DataNodeType::Dimension>2) { coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues } @@ -745,113 +776,88 @@ namespace otb { coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues } + line->set_coordinates(coordinates); + ++vIt; + } + + //Adding the first point again to close the polygon + vIt = vertexList->Begin(); + VertexType pointCoord = vIt.Value(); + if (DataNodeType::Dimension>2) + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues + } + else + { + coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues + } - outerboundaryis->set_linearring(line); - polygon->set_outerboundaryis(outerboundaryis); + line->set_coordinates(coordinates); + ++vIt; - // Retrieving internal rings as well - for(typename PolygonListType::Iterator pIt = it.Get()->GetPolygonInteriorRings()->Begin(); - pIt!=it.Get()->GetPolygonInteriorRings()->End();++pIt) - { - vertexList = pIt.Get()->GetVertexList(); - vIt = vertexList->Begin(); - - while(vIt != vertexList->End()) - { - vIt = vertexList->Begin(); - VertexType pointCoord = vIt.Value(); - if(DataNodeType::Dimension>2) - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - else - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - - line->set_coordinates(coordinates); - ++vIt; - } - - //Adding the first point again to close the polygon - vIt = vertexList->Begin(); - VertexType pointCoord = vIt.Value(); - if(DataNodeType::Dimension>2) - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],pointCoord[2]+1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - else - { - coordinates->add_latlngalt(pointCoord[1],pointCoord[0],1);//Drawing polygon 1m above ground to avoid z-buffer issues - } - - line->set_coordinates(coordinates); - ++vIt; - - - innerboundaryis->set_linearring(line); - polygon->add_innerboundaryis(innerboundaryis); - innerboundaryis->clear_linearring(); - } + innerboundaryis->set_linearring(line); + polygon->add_innerboundaryis(innerboundaryis); + innerboundaryis->clear_linearring(); + } - if (currentMultiGeometry != NULL) - { - currentMultiGeometry->add_geometry(polygon); - } - else - { - PlacemarkPtr placemark = factory->CreatePlacemark(); - placemark->set_geometry(polygon); - if (currentFolder!= NULL) - { - currentFolder->add_feature(placemark); - } - else - { - currentDocument->add_feature(placemark); - } - } - break; + if (currentMultiGeometry != NULL) + { + currentMultiGeometry->add_geometry(polygon); + } + else + { + PlacemarkPtr placemark = factory->CreatePlacemark(); + placemark->set_geometry(polygon); + if (currentFolder!= NULL) + { + currentFolder->add_feature(placemark); } - // MultiGeometry - case FEATURE_COLLECTION: + else { - MultiGeometryPtr multi = factory->CreateMultiGeometry(); - currentMultiGeometry = multi; - PlacemarkPtr placemark = factory->CreatePlacemark(); - placemark->set_geometry(multi); - if (currentFolder!= NULL) - { - currentFolder->add_feature(placemark); - } - else - { - currentDocument->add_feature(placemark); - } - break; + currentDocument->add_feature(placemark); } - default : - break; + } + break; + } + // MultiGeometry + case FEATURE_COLLECTION: + { + MultiGeometryPtr multi = factory->CreateMultiGeometry(); + currentMultiGeometry = multi; + PlacemarkPtr placemark = factory->CreatePlacemark(); + placemark->set_geometry(multi); + if (currentFolder!= NULL) + { + currentFolder->add_feature(placemark); + } + else + { + currentDocument->add_feature(placemark); + } + break; + } + default : + break; - } // end switch - ++it; - } // end while + } // end switch + ++it; + } // end while - // Serialize to XML - std::string xml = kmldom::SerializePretty(kml); + // Serialize to XML + std::string xml = kmldom::SerializePretty(kml); - // Write it - kmlbase::File::WriteStringToFile(xml,this->m_FileName); + // Write it + kmlbase::File::WriteStringToFile(xml,this->m_FileName); - // Eventually print it - //std::cout << xml; + // Eventually print it + //std::cout << xml; - otbMsgDevMacro( <<" KMLVectorDataIO::Write() "); + otbMsgDevMacro( <<" KMLVectorDataIO::Write() "); - } +} } // end namespace otb diff --git a/Code/IO/otbLUMImageIO.cxx b/Code/IO/otbLUMImageIO.cxx index 3b0448e6bf1f59cc68a0fed65295c0a57a0e37d9..61f8f3ce9d40770326a4f9acc07f8eec73199a67 100644 --- a/Code/IO/otbLUMImageIO.cxx +++ b/Code/IO/otbLUMImageIO.cxx @@ -29,521 +29,521 @@ namespace otb { - LUMImageIO::LUMImageIO() - { +LUMImageIO::LUMImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); - m_PixelType = SCALAR; - m_ComponentType = UCHAR; - if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) - { - m_ByteOrder = LittleEndian; - } - else - { - m_ByteOrder = BigEndian; - } + this->SetNumberOfDimensions(2); + m_PixelType = SCALAR; + m_ComponentType = UCHAR; + if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) + { + m_ByteOrder = LittleEndian; + } + else + { + m_ByteOrder = BigEndian; + } - m_FileByteOrder = BigEndian; + m_FileByteOrder = BigEndian; // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_FlagWriteImageInformation = true; + m_FlagWriteImageInformation = true; //Definition of CAI image type - m_CaiLumTyp.clear(); - m_CaiLumTyp.push_back("BI"); - m_CaiLumTyp.push_back("LI"); - m_CaiLumTyp.push_back("BU"); - m_CaiLumTyp.push_back("LU"); - m_CaiLumTyp.push_back("FLOA"); - m_CaiLumTyp.push_back("FLOL"); - m_CaiLumTyp.push_back("R8B"); - m_CaiLumTyp.push_back("R8L"); + m_CaiLumTyp.clear(); + m_CaiLumTyp.push_back("BI"); + m_CaiLumTyp.push_back("LI"); + m_CaiLumTyp.push_back("BU"); + m_CaiLumTyp.push_back("LU"); + m_CaiLumTyp.push_back("FLOA"); + m_CaiLumTyp.push_back("FLOL"); + m_CaiLumTyp.push_back("R8B"); + m_CaiLumTyp.push_back("R8L"); - } +} - LUMImageIO::~LUMImageIO() +LUMImageIO::~LUMImageIO() +{ + if ( m_File.is_open() ) { - if( m_File.is_open() ) - { - m_File.close(); - } + m_File.close(); } +} - bool LUMImageIO::CanReadFile( const char* filename ) - { - std::string lFileName(filename); +bool LUMImageIO::CanReadFile( const char* filename ) +{ + std::string lFileName(filename); // Test the extension - std::string extension = System::GetExtension(filename); - if ((extension!="LUM")&&(extension!="lum")) - { - return false; - } - if( System::IsADirName(lFileName) == true ) - { - return false; - } - if( m_File.is_open() ) - { - m_File.close(); - } + std::string extension = System::GetExtension(filename); + if ((extension!="LUM")&&(extension!="lum")) + { + return false; + } + if ( System::IsADirName(lFileName) == true ) + { + return false; + } + if ( m_File.is_open() ) + { + m_File.close(); + } - std::fstream header_file; - header_file.open( filename, std::ios::in | std::ios::binary ); - if( header_file.fail() ) - { - otbMsgDevMacro(<<"LUMImageIO::CanReadFile() failed header open ! " ); - return false; - } + std::fstream header_file; + header_file.open( filename, std::ios::in | std::ios::binary ); + if ( header_file.fail() ) + { + otbMsgDevMacro(<<"LUMImageIO::CanReadFile() failed header open ! " ); + return false; + } //Read header informations - bool lResult = InternalReadHeaderInformation(header_file,false); - header_file.close(); - return (lResult); - } + bool lResult = InternalReadHeaderInformation(header_file,false); + header_file.close(); + return (lResult); +} // Used to print information about this object - void LUMImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } +void LUMImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} // Read a 3D image (or event more bands)... not implemented yet - void LUMImageIO::ReadVolume(void*) - { - } +void LUMImageIO::ReadVolume(void*) +{ +} // Read image - void LUMImageIO::Read(void* buffer) - { - char * p = static_cast<char *>(buffer); - - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] - - otbMsgDevMacro( <<" LUMImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - - std::streamoff headerLength = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); - std::streamoff numberOfBytesPerLines = headerLength; - std::streamoff offset; - std::streamsize numberOfBytesToBeRead = static_cast<std::streamsize>(this->GetComponentSize() * lNbColumns); - std::streamsize numberOfBytesRead; - std::streamsize cpt = 0; - for(int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); - m_File.seekg(offset, std::ios::beg); - m_File.read( static_cast<char *>( p + cpt ), numberOfBytesToBeRead ); - numberOfBytesRead = m_File.gcount(); +void LUMImageIO::Read(void* buffer) +{ + char * p = static_cast<char *>(buffer); + + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + + otbMsgDevMacro( <<" LUMImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + + std::streamoff headerLength = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); + std::streamoff numberOfBytesPerLines = headerLength; + std::streamoff offset; + std::streamsize numberOfBytesToBeRead = static_cast<std::streamsize>(this->GetComponentSize() * lNbColumns); + std::streamsize numberOfBytesRead; + std::streamsize cpt = 0; + for (int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); + m_File.seekg(offset, std::ios::beg); + m_File.read( static_cast<char *>( p + cpt ), numberOfBytesToBeRead ); + numberOfBytesRead = m_File.gcount(); #ifdef __APPLE_CC__ - // fail() is broken in the Mac. It returns true when reaches eof(). - if ( numberOfBytesRead != numberOfBytesToBeRead ) + // fail() is broken in the Mac. It returns true when reaches eof(). + if ( numberOfBytesRead != numberOfBytesToBeRead ) #else - if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_File.fail() ) + if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_File.fail() ) #endif - { - itkExceptionMacro(<<"LUMImageIO::Read() Can Read the specified Region"); // read failed - } - cpt += numberOfBytesToBeRead; - } - - unsigned long numberOfPixelsPerLines = lNbLines * lNbColumns; - // Swap bytes if necessary - if ( 0 ) {} - otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerLines ) - otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsPerLines ) - else { - itkExceptionMacro(<<"LUMImageIO::Read() undefined component type! " ); + itkExceptionMacro(<<"LUMImageIO::Read() Can Read the specified Region"); // read failed } + cpt += numberOfBytesToBeRead; + } + + unsigned long numberOfPixelsPerLines = lNbLines * lNbColumns; + // Swap bytes if necessary + if ( 0 ) {} + otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerLines ) + otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsPerLines ) + else + { + itkExceptionMacro(<<"LUMImageIO::Read() undefined component type! " ); } +} - void LUMImageIO::ReadImageInformation() +void LUMImageIO::ReadImageInformation() +{ + if ( m_File.is_open() ) { - if( m_File.is_open() ) - { - m_File.close(); - } + m_File.close(); + } - m_File.open( m_FileName.c_str(), std::ios::in | std::ios::binary ); - if( m_File.fail() ) - { - itkExceptionMacro(<<"LUMImageIO::ReadImageInformation() failed header open ! " ); - } + m_File.open( m_FileName.c_str(), std::ios::in | std::ios::binary ); + if ( m_File.fail() ) + { + itkExceptionMacro(<<"LUMImageIO::ReadImageInformation() failed header open ! " ); + } - //Read header informations - InternalReadHeaderInformation(m_File,true); + //Read header informations + InternalReadHeaderInformation(m_File,true); - otbMsgDebugMacro( <<"Driver to read: LUM"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to read: LUM"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} - bool LUMImageIO::InternalReadHeaderInformation(std::fstream & file, const bool reportError) - { +bool LUMImageIO::InternalReadHeaderInformation(std::fstream & file, const bool reportError) +{ - std::string lStrTypeImage; - std::string lStrCodePix; - std::string lStrTypeMachine; - int lNbBits(-1); - char TypeCode[5]; - file.seekg(8, std::ios::beg ); - file.read((char*)(TypeCode),4); - int lTaille = CaiGetTypeLum( TypeCode, - lStrTypeImage, - lNbBits, - lStrCodePix); - if (lTaille == -1) - { - if( reportError == true ) - { - itkExceptionMacro(<< "LUM : bad read of header informations"); - } - else - { - return false; - } - } - //Set file byte order - if( lStrTypeImage == "BE" ) + std::string lStrTypeImage; + std::string lStrCodePix; + std::string lStrTypeMachine; + int lNbBits(-1); + char TypeCode[5]; + file.seekg(8, std::ios::beg ); + file.read((char*)(TypeCode),4); + int lTaille = CaiGetTypeLum( TypeCode, + lStrTypeImage, + lNbBits, + lStrCodePix); + if (lTaille == -1) + { + if ( reportError == true ) { - m_FileByteOrder = BigEndian; + itkExceptionMacro(<< "LUM : bad read of header informations"); } else { - m_FileByteOrder = LittleEndian; + return false; } + } + //Set file byte order + if ( lStrTypeImage == "BE" ) + { + m_FileByteOrder = BigEndian; + } + else + { + m_FileByteOrder = LittleEndian; + } - if(lStrCodePix == "OCT") - { - SetComponentType(CHAR); - } - else if(lStrCodePix == "UOCT") - { - SetComponentType(UCHAR); - } - else if(lStrCodePix == "I2") - { - SetComponentType(SHORT); - } - else if(lStrCodePix == "UI2") - { - SetComponentType(USHORT); - } - else if(lStrCodePix == "I4") - { - SetComponentType(INT); - } - else if(lStrCodePix == "UI4") - { - SetComponentType(UINT); - } - else if(lStrCodePix == "R4") - { - SetComponentType(FLOAT); - } - else if(lStrCodePix == "R8") + if (lStrCodePix == "OCT") + { + SetComponentType(CHAR); + } + else if (lStrCodePix == "UOCT") + { + SetComponentType(UCHAR); + } + else if (lStrCodePix == "I2") + { + SetComponentType(SHORT); + } + else if (lStrCodePix == "UI2") + { + SetComponentType(USHORT); + } + else if (lStrCodePix == "I4") + { + SetComponentType(INT); + } + else if (lStrCodePix == "UI4") + { + SetComponentType(UINT); + } + else if (lStrCodePix == "R4") + { + SetComponentType(FLOAT); + } + else if (lStrCodePix == "R8") + { + SetComponentType(DOUBLE); + } + else + { + if ( reportError == true ) { - SetComponentType(DOUBLE); + itkExceptionMacro(<< "LUM : impossible to determine CodePix information of the image"); } else { - if( reportError == true ) - { - itkExceptionMacro(<< "LUM : impossible to determine CodePix information of the image"); - } - else - { - return false; - } + return false; } + } - int NbCol(-1); - int NbLig(-1); + int NbCol(-1); + int NbLig(-1); - //Read image dimensions - file.seekg(0, std::ios::beg ); - file.read((char*)(&NbCol),4); - file.read((char*)(&NbLig),4); + //Read image dimensions + file.seekg(0, std::ios::beg ); + file.read((char*)(&NbCol),4); + file.read((char*)(&NbLig),4); - //Swapp if necessary - otbSwappFileOrderToSystemOrderMacro(int,&NbCol,1); - otbSwappFileOrderToSystemOrderMacro(int,&NbLig,1); + //Swapp if necessary + otbSwappFileOrderToSystemOrderMacro(int,&NbCol,1); + otbSwappFileOrderToSystemOrderMacro(int,&NbLig,1); - //Initialisation of image informations - m_Dimensions[0] = NbCol; - m_Dimensions[1] = NbLig; - this->SetNumberOfComponents(1); - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); - return(true); - } + //Initialisation of image informations + m_Dimensions[0] = NbCol; + m_Dimensions[1] = NbLig; + this->SetNumberOfComponents(1); + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); + return(true); +} - bool LUMImageIO::CanWriteFile( const char* filename ) +bool LUMImageIO::CanWriteFile( const char* filename ) +{ + std::string lFileName(filename); + std::string extension = System::GetExtension(filename); + if ((extension!="LUM")&&(extension!="lum")) { - std::string lFileName(filename); - std::string extension = System::GetExtension(filename); - if ((extension!="LUM")&&(extension!="lum")) - { - return false; - } - if( System::IsADirName(lFileName) == true ) - { - return false; - } - const std::string Extension = System::GetExtension(filename); - if( (Extension == "lum") || (Extension == "LUM") ) - { - return true; - } - else - { - return false; - } + return false; + } + if ( System::IsADirName(lFileName) == true ) + { + return false; } + const std::string Extension = System::GetExtension(filename); + if ( (Extension == "lum") || (Extension == "LUM") ) + { + return true; + } + else + { + return false; + } +} - void LUMImageIO::Write(const void* buffer) +void LUMImageIO::Write(const void* buffer) +{ + if ( m_FlagWriteImageInformation == true ) { - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } - unsigned long lNbLines = this->GetIORegion().GetSize()[1]; - unsigned long lNbColumns = this->GetIORegion().GetSize()[0]; - unsigned long lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + unsigned long lNbLines = this->GetIORegion().GetSize()[1]; + unsigned long lNbColumns = this->GetIORegion().GetSize()[0]; + unsigned long lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] // Cas particuliers : on controle que si la r�gion � �crire est de la m�me dimension que l'image enti�re, // on commence l'offset � 0 (lorsque que l'on est pas en "Streaming") - if( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) - { - otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); - lFirstLine = 0; - lFirstColumn = 0; - } + if ( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) + { + otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); + lFirstLine = 0; + lFirstColumn = 0; + } - otbMsgDevMacro( <<" LUMImageIO::Write() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); + otbMsgDevMacro( <<" LUMImageIO::Write() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); - std::streamoff numberOfBytesPerLines = this->GetComponentSize() * m_Dimensions[0]; - std::streamoff headerLength = numberOfBytesPerLines; - std::streamoff offset; - std::streamsize numberOfBytesToBeWrite = this->GetComponentSize() * lNbColumns; - std::streamsize cpt = 0; + std::streamoff numberOfBytesPerLines = this->GetComponentSize() * m_Dimensions[0]; + std::streamoff headerLength = numberOfBytesPerLines; + std::streamoff offset; + std::streamsize numberOfBytesToBeWrite = this->GetComponentSize() * lNbColumns; + std::streamsize cpt = 0; - const char * p = static_cast<const char *>(buffer); + const char * p = static_cast<const char *>(buffer); - for(unsigned long LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); - m_File.seekp(offset, std::ios::beg); - m_File.write( static_cast<const char *>( p + cpt ), numberOfBytesToBeWrite ); - cpt += numberOfBytesToBeWrite; - } + for (unsigned long LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lFirstColumn); + m_File.seekp(offset, std::ios::beg); + m_File.write( static_cast<const char *>( p + cpt ), numberOfBytesToBeWrite ); + cpt += numberOfBytesToBeWrite; } +} - void LUMImageIO::WriteImageInformation() - { +void LUMImageIO::WriteImageInformation() +{ - if ( m_FileName == "" ) - { - itkExceptionMacro(<<"A FileName must be specified."); - } - if( CanWriteFile(m_FileName.c_str()) == false) - { - itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a LUM file"); - } - // Close file from any previous image - if ( m_File.is_open() ) - { - m_File.close(); - } + if ( m_FileName == "" ) + { + itkExceptionMacro(<<"A FileName must be specified."); + } + if ( CanWriteFile(m_FileName.c_str()) == false) + { + itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a LUM file"); + } + // Close file from any previous image + if ( m_File.is_open() ) + { + m_File.close(); + } - // Open the new file for writing - // Actually open the file - m_File.open( m_FileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); - if( m_File.fail() ) - { - itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); - } + // Open the new file for writing + // Actually open the file + m_File.open( m_FileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); + if ( m_File.fail() ) + { + itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); + } - //Writing header information - std::streamsize headerLength = static_cast<std::streamsize>(this->GetComponentSize() * m_Dimensions[0]); + //Writing header information + std::streamsize headerLength = static_cast<std::streamsize>(this->GetComponentSize() * m_Dimensions[0]); - m_File.seekp(0, std::ios::beg ); - char* value = new char[headerLength]; - //Write Header line and all file (whitout information) - for(unsigned int numLigne=0; numLigne<(m_Dimensions[1]+1); numLigne++) - { - m_File.write(value,headerLength); - } - delete [] value; - value = NULL; - //Set m_TypeLum - if( 0 ) {} - otbSetTypeLumMacro( CHAR, "08BI", "08LI") - otbSetTypeLumMacro( UCHAR, "08BU", "08LU") - otbSetTypeLumMacro( SHORT, "16BI", "16LI") - otbSetTypeLumMacro( USHORT, "16BU", "16LU") - otbSetTypeLumMacro( INT, "32BI", "32LI" ) - otbSetTypeLumMacro( UINT, "32BU", "32LU" ) - otbSetTypeLumMacro( FLOAT, "FLOA", "FLOL" ) - otbSetTypeLumMacro( DOUBLE, "R8B ", "R8L ") - if( (this->GetComponentType() == LONG) || (this->GetComponentType() == ULONG) ) - { - itkExceptionMacro(<< "LUM format doesn't accept LONG or ULONG data type"); - } + m_File.seekp(0, std::ios::beg ); + char* value = new char[headerLength]; + //Write Header line and all file (whitout information) + for (unsigned int numLigne=0; numLigne<(m_Dimensions[1]+1); numLigne++) + { + m_File.write(value,headerLength); + } + delete [] value; + value = NULL; + //Set m_TypeLum + if ( 0 ) {} + otbSetTypeLumMacro( CHAR, "08BI", "08LI") + otbSetTypeLumMacro( UCHAR, "08BU", "08LU") + otbSetTypeLumMacro( SHORT, "16BI", "16LI") + otbSetTypeLumMacro( USHORT, "16BU", "16LU") + otbSetTypeLumMacro( INT, "32BI", "32LI" ) + otbSetTypeLumMacro( UINT, "32BU", "32LU" ) + otbSetTypeLumMacro( FLOAT, "FLOA", "FLOL" ) + otbSetTypeLumMacro( DOUBLE, "R8B ", "R8L ") + if ( (this->GetComponentType() == LONG) || (this->GetComponentType() == ULONG) ) + { + itkExceptionMacro(<< "LUM format doesn't accept LONG or ULONG data type"); + } - m_File.seekp(0, std::ios::beg ); - //Write image size - m_File.write((char*)(&(m_Dimensions[0])),4); - m_File.write((char*)(&(m_Dimensions[1])),4); - m_File.write((char*)(m_TypeLum.data()),4); + m_File.seekp(0, std::ios::beg ); + //Write image size + m_File.write((char*)(&(m_Dimensions[0])),4); + m_File.write((char*)(&(m_Dimensions[1])),4); + m_File.write((char*)(m_TypeLum.data()),4); - otbMsgDebugMacro( <<"Driver to write: LUM"); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" Type Lum : "<<m_TypeLum); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to write: LUM"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" Type Lum : "<<m_TypeLum); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} - int LUMImageIO::CaiGetTypeLum( const char * type_code, - std::string & str_sens_code, - int & inbbits, - std::string & str_cod_pix) +int LUMImageIO::CaiGetTypeLum( const char * type_code, + std::string & str_sens_code, + int & inbbits, + std::string & str_cod_pix) +{ + unsigned int ind; /* indice de boucle sur les types reconnus */ + int trouve,icr,taille; /* indice pour la recherche */ + int mod2; /* modulo2 */ + char* pch0; + char sens_code[3]; /* type code+ordre rangement octets dans entete*/ + char cod_pix[5]; + sens_code[0]='\0'; + cod_pix[0]='\0'; + + /* Initialisations diverses */ + trouve = -1; + taille = -1; + int nbbits=-1; + ind = 0; + pch0=NULL; + + std::string str_type_code(type_code); + + while ((trouve==-1)&&(ind< m_CaiLumTyp.size())) { - unsigned int ind; /* indice de boucle sur les types reconnus */ - int trouve,icr,taille; /* indice pour la recherche */ - int mod2; /* modulo2 */ - char* pch0; - char sens_code[3]; /* type code+ordre rangement octets dans entete*/ - char cod_pix[5]; - sens_code[0]='\0'; - cod_pix[0]='\0'; + if ( (str_type_code.find(m_CaiLumTyp[ind]) >= 0 ) && + (str_type_code.find(m_CaiLumTyp[ind]) <= str_type_code.size() ) ) - /* Initialisations diverses */ - trouve = -1; - taille = -1; - int nbbits=-1; - ind = 0; - pch0=NULL; + { + trouve=ind; + } + else + { + ind=ind+1; + } + } - std::string str_type_code(type_code); + //CAI source code + if (trouve !=-1) + { + mod2=ind%2; + if (mod2==0) sprintf(sens_code,"BE"); + else sprintf(sens_code,"LE"); - while ((trouve==-1)&&(ind< m_CaiLumTyp.size())) + if (ind < 4) { - if ( (str_type_code.find(m_CaiLumTyp[ind]) >= 0 ) && - (str_type_code.find(m_CaiLumTyp[ind]) <= str_type_code.size() ) ) - - { - trouve=ind; - } + icr=sscanf(type_code,"%d",&nbbits); + if (icr ==0) nbbits=-1; else { - ind=ind+1; + trouve =(int)(nbbits/8); + if ((nbbits%8)!=0) taille =trouve+1; + else taille = trouve; } - } - - //CAI source code - if (trouve !=-1) - { - mod2=ind%2; - if (mod2==0) sprintf(sens_code,"BE"); - else sprintf(sens_code,"LE"); - - if (ind < 4) + pch0 = const_cast<char *>(strstr(type_code,"U")); + if (taille == 1) { - icr=sscanf(type_code,"%d",&nbbits); - if (icr ==0) nbbits=-1; - else - { - trouve =(int)(nbbits/8); - if ((nbbits%8)!=0) taille =trouve+1; - else taille = trouve; - } - pch0 = const_cast<char *>(strstr(type_code,"U")); - if (taille == 1) - { - if (pch0==NULL) sprintf(cod_pix,"OCT"); - else sprintf(cod_pix,"UOCT"); - } - else if (taille == 2) - { - if (pch0==NULL) sprintf(cod_pix,"I2"); - else sprintf(cod_pix,"UI2"); - } - else if (taille == 4) - { - if (pch0==NULL) sprintf(cod_pix,"I4"); - else sprintf(cod_pix,"UI4"); - } - else taille=-1; + if (pch0==NULL) sprintf(cod_pix,"OCT"); + else sprintf(cod_pix,"UOCT"); } - else if ((ind ==4)||(ind==5) ) + else if (taille == 2) { - taille=4; - nbbits = 32; - sprintf(cod_pix,"R4"); - + if (pch0==NULL) sprintf(cod_pix,"I2"); + else sprintf(cod_pix,"UI2"); } - else if ((ind ==6)||(ind==7) ) + else if (taille == 4) { - taille=8; - nbbits = 64; - sprintf(cod_pix,"R8"); + if (pch0==NULL) sprintf(cod_pix,"I4"); + else sprintf(cod_pix,"UI4"); } + else taille=-1; } + else if ((ind ==4)||(ind==5) ) + { + taille=4; + nbbits = 32; + sprintf(cod_pix,"R4"); - str_cod_pix = std::string(cod_pix); - str_sens_code = std::string(sens_code); - - inbbits = nbbits; - return(taille); + } + else if ((ind ==6)||(ind==7) ) + { + taille=8; + nbbits = 64; + sprintf(cod_pix,"R8"); + } } + str_cod_pix = std::string(cod_pix); + str_sens_code = std::string(sens_code); + + inbbits = nbbits; + return(taille); +} + } // end namespace otb diff --git a/Code/IO/otbLUMImageIO.h b/Code/IO/otbLUMImageIO.h index 9819796f189de24c9f600a27f8239eb044689619..a7180a20b6b6579d24a6881eb7ca1accfdf25a07 100644 --- a/Code/IO/otbLUMImageIO.h +++ b/Code/IO/otbLUMImageIO.h @@ -61,7 +61,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -79,7 +82,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ @@ -114,9 +120,9 @@ private: bool InternalReadHeaderInformation(std::fstream & file, const bool reportError); /** This method get the LUM type */ int CaiGetTypeLum( const char * type_code, - std::string & str_sens_code, - int & inbbits, - std::string & str_cod_pix); + std::string & str_sens_code, + int & inbbits, + std::string & str_cod_pix); #define otbSwappFileOrderToSystemOrderMacro(StrongType, buffer, buffer_size) \ diff --git a/Code/IO/otbMSTARImageIO.cxx b/Code/IO/otbMSTARImageIO.cxx index a7ad44bea833dcc1f0b814a819abfe40da01a22a..5a6712a61d2c2ce9d12aab6edb3dfa3ac97b7843 100644 --- a/Code/IO/otbMSTARImageIO.cxx +++ b/Code/IO/otbMSTARImageIO.cxx @@ -49,142 +49,147 @@ namespace otb { - /** Constructor */ - MSTARImageIO::MSTARImageIO() - { - m_ByteOrder = BigEndian; - this->SetNumberOfDimensions(2); - m_PixelType = SCALAR; - m_ComponentType = UCHAR; - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; +/** Constructor */ +MSTARImageIO::MSTARImageIO() +{ + m_ByteOrder = BigEndian; + this->SetNumberOfDimensions(2); + m_PixelType = SCALAR; + m_ComponentType = UCHAR; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_NbOctetPixel = 0; + m_NbOctetPixel = 0; - MSTARfp=NULL; /* Input FILE ptr to MSTAR image file */ - HDRfp=NULL; /* Output FILE ptr to MSTAR header file */ + MSTARfp=NULL; /* Input FILE ptr to MSTAR image file */ + HDRfp=NULL; /* Output FILE ptr to MSTAR header file */ - MSTARname=NULL; /* Input MSTAR filename */ + MSTARname=NULL; /* Input MSTAR filename */ - tptr=NULL; /* Temp buffer ptr */ - phdr=NULL; /* Ptr to buffer to hold Phoenix header */ + tptr=NULL; /* Temp buffer ptr */ + phdr=NULL; /* Ptr to buffer to hold Phoenix header */ - FSCENEdata=NULL; /* Ptr to Fullscene data buffer */ - CHIPdata=NULL; /* Ptr to CHIp data buffer */ + FSCENEdata=NULL; /* Ptr to Fullscene data buffer */ + CHIPdata=NULL; /* Ptr to CHIp data buffer */ - } +} - /** Destructor */ - MSTARImageIO::~MSTARImageIO() +/** Destructor */ +MSTARImageIO::~MSTARImageIO() +{ + if ( phdr != NULL) { - if ( phdr != NULL) - { - free(phdr); - phdr = NULL; - } + free(phdr); + phdr = NULL; } +} - bool MSTARImageIO::CanReadFile( const char* filename ) +bool MSTARImageIO::CanReadFile( const char* filename ) +{ + // First check the filename extension + std::string fname = filename; + if ( fname == "" ) { - // First check the filename extension - std::string fname = filename; - if ( fname == "" ) - { - itkDebugMacro(<< "Fichier image non specifie."); - } + itkDebugMacro(<< "Fichier image non specifie."); + } - int NbLignes; /* Nombre de lignes de l'image */ - int NbColonnes; /* Nombre de colonnes de l'image */ + int NbLignes; /* Nombre de lignes de l'image */ + int NbColonnes; /* Nombre de colonnes de l'image */ - MSTARname = filename; + MSTARname = filename; - MSTARfp = fopen(MSTARname,"rb"); - if (MSTARfp == NULL) - { - otbMsgDevMacro(<<"\nError: Unable to open ["<<MSTARname<<"] for reading!\n"); - return false; - } + MSTARfp = fopen(MSTARname,"rb"); + if (MSTARfp == NULL) + { + otbMsgDevMacro(<<"\nError: Unable to open ["<<MSTARname<<"] for reading!\n"); + return false; + } -/**************************************************** - * Read first 512 bytes to figure out some header * - * parameters.... * - ****************************************************/ + /**************************************************** + * Read first 512 bytes to figure out some header * + * parameters.... * + ****************************************************/ - fread(tbuff, sizeof(char), 1024, MSTARfp); - rewind(MSTARfp); + fread(tbuff, sizeof(char), 1024, MSTARfp); + rewind(MSTARfp); - /* Extract Phoenix Summary header length */ - tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); - if (tptr == (char *) NULL) - { + /* Extract Phoenix Summary header length */ + tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); + if (tptr == (char *) NULL) + { // fprintf(stderr,"Can not determine Phoenix header length!\n"); - fclose(MSTARfp); - return false; - } else - { - sscanf((tptr+20), "%d", &phlen); - } + fclose(MSTARfp); + return false; + } + else + { + sscanf((tptr+20), "%d", &phlen); + } - /* Check for and extract native header length */ - tptr = (char *) strstr(tbuff,"native_header_length= "); - if (tptr == (char *) NULL) - { + /* Check for and extract native header length */ + tptr = (char *) strstr(tbuff,"native_header_length= "); + if (tptr == (char *) NULL) + { // fprintf(stderr,"Can not determine native header length!\n"); - fclose(MSTARfp); - return false; - } else - { - sscanf((tptr+21), "%d", &nhlen); - } + fclose(MSTARfp); + return false; + } + else + { + sscanf((tptr+21), "%d", &nhlen); + } - /* Extract MSTAR column width */ - tptr = (char *) strstr(tbuff,"NumberOfColumns= "); - if (tptr == (char *) NULL) - { - otbMsgDevMacro(<<"Error: Can not determine MSTAR image width"); - fclose(MSTARfp); - return false; - } else - { - sscanf((tptr+16), "%d", &numcols); - NbColonnes = static_cast<int>(numcols); - } + /* Extract MSTAR column width */ + tptr = (char *) strstr(tbuff,"NumberOfColumns= "); + if (tptr == (char *) NULL) + { + otbMsgDevMacro(<<"Error: Can not determine MSTAR image width"); + fclose(MSTARfp); + return false; + } + else + { + sscanf((tptr+16), "%d", &numcols); + NbColonnes = static_cast<int>(numcols); + } - /* Extract MSTAR row height */ - tptr = (char *) strstr(tbuff,"NumberOfRows= "); - if (tptr == (char *) NULL) - { - otbMsgDevMacro(<<"Error: Can not determine MSTAR image height!"); - fclose(MSTARfp); - return false; - } else - { - sscanf((tptr+13), "%d",&numrows); - NbLignes = static_cast<int>(numrows); - } + /* Extract MSTAR row height */ + tptr = (char *) strstr(tbuff,"NumberOfRows= "); + if (tptr == (char *) NULL) + { + otbMsgDevMacro(<<"Error: Can not determine MSTAR image height!"); + fclose(MSTARfp); + return false; + } + else + { + sscanf((tptr+13), "%d",&numrows); + NbLignes = static_cast<int>(numrows); + } - /* Set MSTAR image type */ - if (nhlen == 0) - {/* Implies FLOAT MSTAR chip image */ - mstartype = CHIP_IMAGE; - } else - { - mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ - } + /* Set MSTAR image type */ + if (nhlen == 0) + {/* Implies FLOAT MSTAR chip image */ + mstartype = CHIP_IMAGE; + } + else + { + mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ + } -/******************************************************* - * Allocate memory to header buffer, read Phoenix hdr, * - * and write out to output file... * - *******************************************************/ + /******************************************************* + * Allocate memory to header buffer, read Phoenix hdr, * + * and write out to output file... * + *******************************************************/ - // /* Allocate memory to Phoenix header buffer */ + // /* Allocate memory to Phoenix header buffer */ // phdr = (char *) malloc(phlen+1); // if (phdr == (char *) NULL) // { @@ -194,7 +199,7 @@ namespace otb // return 0; // } - // /* Read Phoenix header into buffer */ + // /* Read Phoenix header into buffer */ // n = fread(phdr, sizeof(char), phlen, MSTARfp); // if (n != phlen) // { @@ -206,508 +211,518 @@ namespace otb // return 0; // } - // /* Write Phoenix header to output header file */ + // /* Write Phoenix header to output header file */ // free(phdr); - fclose(MSTARfp); - otbMsgDevMacro(<< "Can read MSTAR"); - return bool(true); - } + fclose(MSTARfp); + otbMsgDevMacro(<< "Can read MSTAR"); + return bool(true); +} + +bool MSTARImageIO::CanWriteFile( const char * filename ) +{ + bool formatFound = false; + std::string fname = filename; - bool MSTARImageIO::CanWriteFile( const char * filename ) + if ( fname == "" ) { - bool formatFound = false; - std::string fname = filename; + itkDebugMacro(<< "Fichier image non specifie."); + } - if ( fname == "" ) - { - itkDebugMacro(<< "Fichier image non specifie."); - } + if ( formatFound == false ) + { + std::string identificationErreur; + identificationErreur = "Format MSTAR non detecte dans l'extension du fichier."; + itkDebugMacro(<<identificationErreur.c_str()); + } - if( formatFound == false ) - { - std::string identificationErreur; - identificationErreur = "Format MSTAR non detecte dans l'extension du fichier."; - itkDebugMacro(<<identificationErreur.c_str()); - } + return formatFound; - return formatFound; +} - } +void MSTARImageIO::Read(void* buffer) +{ - void MSTARImageIO::Read(void* buffer) + MSTARfp = fopen(MSTARname,"rb"); + if (MSTARfp == NULL) { + itkExceptionMacro(<< "Error: Unable to open file for reading!\n\n " << m_FileName.c_str() <<")."); + } - MSTARfp = fopen(MSTARname,"rb"); - if (MSTARfp == NULL) - { - itkExceptionMacro(<< "Error: Unable to open file for reading!\n\n " << m_FileName.c_str() <<")."); - } - -/**************************************************** - * Read first 512 bytes to figure out some header * - * parameters.... * - ****************************************************/ + /**************************************************** + * Read first 512 bytes to figure out some header * + * parameters.... * + ****************************************************/ - fread(tbuff, sizeof(char), 1024, MSTARfp); - rewind(MSTARfp); + fread(tbuff, sizeof(char), 1024, MSTARfp); + rewind(MSTARfp); - /* Extract Phoenix Summary header length */ - tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<< "Error: Can not determine Phoenix header length!" ); + /* Extract Phoenix Summary header length */ + tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<< "Error: Can not determine Phoenix header length!" ); - fclose(MSTARfp); - } else - { - sscanf((tptr+20), "%d", &phlen); - } + fclose(MSTARfp); + } + else + { + sscanf((tptr+20), "%d", &phlen); + } - /* Check for and extract native header length */ - tptr = (char *) strstr(tbuff,"native_header_length= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Can not determine native header length!\n"); - fclose(MSTARfp); - } else - { - sscanf((tptr+21), "%d", &nhlen); - } + /* Check for and extract native header length */ + tptr = (char *) strstr(tbuff,"native_header_length= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Can not determine native header length!\n"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+21), "%d", &nhlen); + } - /* Extract MSTAR column width */ - tptr = (char *) strstr(tbuff,"NumberOfColumns= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Error: Can not determine MSTAR image width"); - fclose(MSTARfp); - } else - { - sscanf((tptr+16), "%d", &numcols); - m_Dimensions[0] = static_cast<int>(numcols); - } + /* Extract MSTAR column width */ + tptr = (char *) strstr(tbuff,"NumberOfColumns= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Error: Can not determine MSTAR image width"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+16), "%d", &numcols); + m_Dimensions[0] = static_cast<int>(numcols); + } - /* Extract MSTAR row height */ - tptr = (char *) strstr(tbuff,"NumberOfRows= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Error: Can not determine MSTAR image height!"); - fclose(MSTARfp); - } else - { - sscanf((tptr+13), "%d",&numrows); - m_Dimensions[1] = static_cast<int>(numrows); - } + /* Extract MSTAR row height */ + tptr = (char *) strstr(tbuff,"NumberOfRows= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Error: Can not determine MSTAR image height!"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+13), "%d",&numrows); + m_Dimensions[1] = static_cast<int>(numrows); + } - /* Set MSTAR image type */ - if (nhlen == 0) - {/* Implies FLOAT MSTAR chip image */ - mstartype = CHIP_IMAGE; - otbMsgDevMacro(<< " Chip type "); - } else - { - mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ - otbMsgDevMacro( << " Scene type " ); - } + /* Set MSTAR image type */ + if (nhlen == 0) + {/* Implies FLOAT MSTAR chip image */ + mstartype = CHIP_IMAGE; + otbMsgDevMacro(<< " Chip type "); + } + else + { + mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ + otbMsgDevMacro( << " Scene type " ); + } - unsigned long step = this->GetNumberOfComponents() * (unsigned long)(m_NbOctetPixel);; - float * p = static_cast<float *>(buffer); + unsigned long step = this->GetNumberOfComponents() * (unsigned long)(m_NbOctetPixel);; + float * p = static_cast<float *>(buffer); - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; - unsigned long lNbPixels = (unsigned long)(lNbColumns*lNbLines); - unsigned long lTailleBuffer = (unsigned long)(m_NbOctetPixel)*lNbPixels; + unsigned long lNbPixels = (unsigned long)(lNbColumns*lNbLines); + unsigned long lTailleBuffer = (unsigned long)(m_NbOctetPixel)*lNbPixels; - unsigned char* value = new unsigned char[lTailleBuffer]; + unsigned char* value = new unsigned char[lTailleBuffer]; - otbMsgDevMacro( << "MSTARImageIO::Read() IORegion Start["<<this->GetIORegion().GetIndex()[0]<<","<<this->GetIORegion().GetIndex()[1]<<"] Size ["<<this->GetIORegion().GetSize()[0]<<","<<this->GetIORegion().GetSize()[1]<<"] on Image size ["<<m_Dimensions[0]<<","<<m_Dimensions[1]<<"]"); + otbMsgDevMacro( << "MSTARImageIO::Read() IORegion Start["<<this->GetIORegion().GetIndex()[0]<<","<<this->GetIORegion().GetIndex()[1]<<"] Size ["<<this->GetIORegion().GetSize()[0]<<","<<this->GetIORegion().GetSize()[1]<<"] on Image size ["<<m_Dimensions[0]<<","<<m_Dimensions[1]<<"]"); -/****************************************************** - * Set up location to point to MSTAR magnitude data.. * - ******************************************************/ - switch (mstartype) - { - case CHIP_IMAGE: - magloc = phlen; - fseek(MSTARfp, magloc, 0); - nchunks = numrows * numcols; - break; - case FSCENE_IMAGE: - magloc = phlen + nhlen; /* nhlen = 512 */ - fseek(MSTARfp, magloc, 0); - nchunks = numrows * numcols; - break; - } + /****************************************************** + * Set up location to point to MSTAR magnitude data.. * + ******************************************************/ + switch (mstartype) + { + case CHIP_IMAGE: + magloc = phlen; + fseek(MSTARfp, magloc, 0); + nchunks = numrows * numcols; + break; + case FSCENE_IMAGE: + magloc = phlen + nhlen; /* nhlen = 512 */ + fseek(MSTARfp, magloc, 0); + nchunks = numrows * numcols; + break; + } -/****************************************************** - * Check byte-order, swap bytes if necessary... * - * Allocate memory, read data, & convert to 8-bit * - * based on 'mstartype' * - ******************************************************/ + /****************************************************** + * Check byte-order, swap bytes if necessary... * + * Allocate memory, read data, & convert to 8-bit * + * based on 'mstartype' * + ******************************************************/ - /* Check byteorder */ - byteorder = (int) CheckByteOrder(); - switch (byteorder) - { - case LSB_FIRST: - printf("==> Little-Endian CPU detected: Will byteswap before scaling data!\n"); - break; - case MSB_FIRST: - printf("==> Big-Endian CPU detected: No byteswap needed!\n"); - break; - } + /* Check byteorder */ + byteorder = (int) CheckByteOrder(); + switch (byteorder) + { + case LSB_FIRST: + printf("==> Little-Endian CPU detected: Will byteswap before scaling data!\n"); + break; + case MSB_FIRST: + printf("==> Big-Endian CPU detected: No byteswap needed!\n"); + break; + } -/****************************************************** - * Allocate memory, read data, & write out based on * - * type of MSTAR image...and which data to write out * - * * - * NOTE: For Chip data, I allocate all of the memory * - * needed (magnitude+phase), read and then write* - * all of it out... * - * * - * For fullscene data, because of the size of * - * memory needed, I allocate only enough to * - * grab the magnitude or the phase. I then * - * process first the magnitude and then the * - * phase using the same buffer pointer.... * - * * - * The code will read & write out ONLY the MAG * - * image data if so specified by the user... * - ******************************************************/ - - /* Open output file for writing... */ - switch (mstartype) - { - case CHIP_IMAGE: - otbMsgDevMacro(<< " Chip and all "); - totchunks = nchunks * 2; - bytesPerImage = totchunks * sizeof(float); - CHIPdata = (float *) malloc(bytesPerImage); + /****************************************************** + * Allocate memory, read data, & write out based on * + * type of MSTAR image...and which data to write out * + * * + * NOTE: For Chip data, I allocate all of the memory * + * needed (magnitude+phase), read and then write* + * all of it out... * + * * + * For fullscene data, because of the size of * + * memory needed, I allocate only enough to * + * grab the magnitude or the phase. I then * + * process first the magnitude and then the * + * phase using the same buffer pointer.... * + * * + * The code will read & write out ONLY the MAG * + * image data if so specified by the user... * + ******************************************************/ + + /* Open output file for writing... */ + switch (mstartype) + { + case CHIP_IMAGE: + otbMsgDevMacro(<< " Chip and all "); + totchunks = nchunks * 2; + bytesPerImage = totchunks * sizeof(float); + CHIPdata = (float *) malloc(bytesPerImage); - if (CHIPdata == (float *) NULL) - { - fclose(MSTARfp); - itkExceptionMacro("Error: Unable to malloc CHIP memory!\n"); + if (CHIPdata == (float *) NULL) + { + fclose(MSTARfp); + itkExceptionMacro("Error: Unable to malloc CHIP memory!\n"); - } + } - switch (byteorder) - { - case LSB_FIRST: /* Little-endian..do byteswap */ + switch (byteorder) + { + case LSB_FIRST: /* Little-endian..do byteswap */ - otbMsgDevMacro(<<"Performing auto-byteswap...\n"); - for (i = 0; i < totchunks; i++) - { - fread(bigfloatbuf, sizeof(char), 4, MSTARfp); - littlefloatval = byteswap_SR_IR(bigfloatbuf); - CHIPdata[i] = littlefloatval; - } - break; + otbMsgDevMacro(<<"Performing auto-byteswap...\n"); + for (i = 0; i < totchunks; i++) + { + fread(bigfloatbuf, sizeof(char), 4, MSTARfp); + littlefloatval = byteswap_SR_IR(bigfloatbuf); + CHIPdata[i] = littlefloatval; + } + break; - case MSB_FIRST: /* Big-endian..no swap */ + case MSB_FIRST: /* Big-endian..no swap */ - numgot = fread(CHIPdata, sizeof(float), totchunks, MSTARfp); - break; - } + numgot = fread(CHIPdata, sizeof(float), totchunks, MSTARfp); + break; + } - /* Writes ALL data or MAG only data based on totchunks */ - //n = fwrite(CHIPdata, sizeof(float), totchunks, RAWfp); + /* Writes ALL data or MAG only data based on totchunks */ + //n = fwrite(CHIPdata, sizeof(float), totchunks, RAWfp); - // Recopie dans le buffer + // Recopie dans le buffer - for(int ci=0; ci<nchunks; ci++) - { - p[ci*2]=CHIPdata[ci]; //magnitude - p[ci*2+1]=CHIPdata[nchunks+ci]; //phase - } + for (int ci=0; ci<nchunks; ci++) + { + p[ci*2]=CHIPdata[ci]; //magnitude + p[ci*2+1]=CHIPdata[nchunks+ci]; //phase + } - /* Cleanup: Close file..free memory */ - free(CHIPdata); - break; /* End of CHIP_IMAGE case */ + /* Cleanup: Close file..free memory */ + free(CHIPdata); + break; /* End of CHIP_IMAGE case */ - case FSCENE_IMAGE: - bytesPerImage = nchunks * sizeof(short); - FSCENEdata = (unsigned short *) malloc( bytesPerImage ); - if (FSCENEdata == (unsigned short *) NULL) - { - fclose(MSTARfp); - itkExceptionMacro(<<"Error: Unable to malloc fullscene memory!\n"); - } + case FSCENE_IMAGE: + bytesPerImage = nchunks * sizeof(short); + FSCENEdata = (unsigned short *) malloc( bytesPerImage ); + if (FSCENEdata == (unsigned short *) NULL) + { + fclose(MSTARfp); + itkExceptionMacro(<<"Error: Unable to malloc fullscene memory!\n"); + } - otbMsgDevMacro(<<"Reading MSTAR fullscene magnitude data from ["<<MSTARname<<"]."); + otbMsgDevMacro(<<"Reading MSTAR fullscene magnitude data from ["<<MSTARname<<"]."); - switch (byteorder) - { - case LSB_FIRST: /* Little-endian..do byteswap */ - otbMsgDevMacro(<<"Performing auto-byteswap..."); - for (i = 0; i < nchunks; i++) - { - fread(bigushortbuf, sizeof(char), 2, MSTARfp); - littleushortval = byteswap_SUS_IUS(bigushortbuf); - FSCENEdata[i] = littleushortval; - } - break; + switch (byteorder) + { + case LSB_FIRST: /* Little-endian..do byteswap */ + otbMsgDevMacro(<<"Performing auto-byteswap..."); + for (i = 0; i < nchunks; i++) + { + fread(bigushortbuf, sizeof(char), 2, MSTARfp); + littleushortval = byteswap_SUS_IUS(bigushortbuf); + FSCENEdata[i] = littleushortval; + } + break; + + case MSB_FIRST: /* Big-endian..no swap */ + numgot = fread(FSCENEdata, sizeof(short), nchunks, MSTARfp); + break; + } - case MSB_FIRST: /* Big-endian..no swap */ - numgot = fread(FSCENEdata, sizeof(short), nchunks, MSTARfp); - break; - } + otbMsgDevMacro(<<"Writing MSTAR fullscene magnitude data to ["<<RAWname<<"]."); + //n = fwrite(FSCENEdata, sizeof(short), nchunks, RAWfp); + for ( int nbComponents = 0; nbComponents < 1; nbComponents++) + { + // Recopie dans le buffer - otbMsgDevMacro(<<"Writing MSTAR fullscene magnitude data to ["<<RAWname<<"]."); - //n = fwrite(FSCENEdata, sizeof(short), nchunks, RAWfp); - for ( int nbComponents = 0; nbComponents < 1; nbComponents++) - { - // Recopie dans le buffer + unsigned long cpt(0); + cpt = (unsigned long )(nbComponents)* (unsigned long)(m_NbOctetPixel); + for ( unsigned long i=0; i < lTailleBuffer; i = i+m_NbOctetPixel ) + { + memcpy((void*)(&(p[cpt])),(const void*)(&(FSCENEdata[i])),(size_t)(m_NbOctetPixel)); + cpt += step; + } - unsigned long cpt(0); - cpt = (unsigned long )(nbComponents)* (unsigned long)(m_NbOctetPixel); - for ( unsigned long i=0; i < lTailleBuffer; i = i+m_NbOctetPixel ) - { - memcpy((void*)(&(p[cpt])),(const void*)(&(FSCENEdata[i])),(size_t)(m_NbOctetPixel)); - cpt += step; - } + } - } + if (n != nchunks) + { + fclose(MSTARfp); + itkExceptionMacro(<< "Error: in writing MSTAR Fullscene data!"); + } - if (n != nchunks) - { - fclose(MSTARfp); - itkExceptionMacro(<< "Error: in writing MSTAR Fullscene data!"); - } + otbMsgDevMacro(<<"Reading MSTAR fullscene phase data from ["<<MSTARname<<"]."); - otbMsgDevMacro(<<"Reading MSTAR fullscene phase data from ["<<MSTARname<<"]."); + switch (byteorder) + { + case LSB_FIRST: /* Little-endian..do byteswap */ + otbMsgDevMacro(<<"Performing auto-byteswap..."); + for (i = 0; i < nchunks; i++) + { + fread(bigushortbuf, sizeof(char), 2, MSTARfp); + littleushortval = byteswap_SUS_IUS(bigushortbuf); + FSCENEdata[i] = littleushortval; + } + break; + + case MSB_FIRST: /* Big-endian..no swap */ + numgot = fread(FSCENEdata, sizeof(short), nchunks, MSTARfp); + break; + } - switch (byteorder) - { - case LSB_FIRST: /* Little-endian..do byteswap */ - otbMsgDevMacro(<<"Performing auto-byteswap..."); - for (i = 0; i < nchunks; i++) - { - fread(bigushortbuf, sizeof(char), 2, MSTARfp); - littleushortval = byteswap_SUS_IUS(bigushortbuf); - FSCENEdata[i] = littleushortval; - } - break; - - case MSB_FIRST: /* Big-endian..no swap */ - numgot = fread(FSCENEdata, sizeof(short), nchunks, MSTARfp); - break; - } - - otbMsgDevMacro(<<"Writing MSTAR fullscene phase data to ["<<RAWname<<"]."); + otbMsgDevMacro(<<"Writing MSTAR fullscene phase data to ["<<RAWname<<"]."); // n = fwrite(FSCENEdata, sizeof(short), nchunks, RAWfp); - for ( unsigned int nbComponents = 1; nbComponents < this->GetNumberOfComponents(); nbComponents++) - { - // Recopie dans le buffer - - unsigned long cpt(0); - cpt = (unsigned long )(nbComponents)* (unsigned long)(m_NbOctetPixel); - for ( unsigned long i=0; i < lTailleBuffer; i = i+m_NbOctetPixel ) - { - memcpy((void*)(&(p[cpt])),(const void*)(&(CHIPdata[i])),(size_t)(m_NbOctetPixel)); - cpt += step; - } - + for ( unsigned int nbComponents = 1; nbComponents < this->GetNumberOfComponents(); nbComponents++) + { + // Recopie dans le buffer - } + unsigned long cpt(0); + cpt = (unsigned long )(nbComponents)* (unsigned long)(m_NbOctetPixel); + for ( unsigned long i=0; i < lTailleBuffer; i = i+m_NbOctetPixel ) + { + memcpy((void*)(&(p[cpt])),(const void*)(&(CHIPdata[i])),(size_t)(m_NbOctetPixel)); + cpt += step; + } - if (n != nchunks) - { - fclose(MSTARfp); - itkExceptionMacro(<<"Error: in writing MSTAR Fullscene Phase data!"); - } - /* Cleanup: free memory */ - free(FSCENEdata); + } + if (n != nchunks) + { + fclose(MSTARfp); + itkExceptionMacro(<<"Error: in writing MSTAR Fullscene Phase data!"); + } + /* Cleanup: free memory */ + free(FSCENEdata); - break; /* End of FSCENE_IMAGE case */ - } /* End of 'mstartype' switch */ + break; /* End of FSCENE_IMAGE case */ - /* Cleanup: close files */ - fclose(MSTARfp); + } /* End of 'mstartype' switch */ + /* Cleanup: close files */ + fclose(MSTARfp); - delete [] value; - } - void MSTARImageIO::ReadImageInformation() - { - int NbLignes; /* Nombre de lignes de l'image */ - int NbColonnes; /* Nombre de colonnes de l'image */ - int NbOctetPixel = sizeof(float); /* Nombre octets/pixel l'image */ - MSTARname = m_FileName.c_str(); - MSTARfp = fopen(MSTARname,"rb"); - if (MSTARfp == NULL) - { - itkExceptionMacro(<< "Error: Unable to open file for reading!\n\n " << m_FileName.c_str() ); - } + delete [] value; +} +void MSTARImageIO::ReadImageInformation() +{ + int NbLignes; /* Nombre de lignes de l'image */ + int NbColonnes; /* Nombre de colonnes de l'image */ + int NbOctetPixel = sizeof(float); /* Nombre octets/pixel l'image */ -/**************************************************** - * Read first 512 bytes to figure out some header * - * parameters.... * - ****************************************************/ + MSTARname = m_FileName.c_str(); + MSTARfp = fopen(MSTARname,"rb"); + if (MSTARfp == NULL) + { + itkExceptionMacro(<< "Error: Unable to open file for reading!\n\n " << m_FileName.c_str() ); + } - fread(tbuff, sizeof(char), 1024, MSTARfp); - rewind(MSTARfp); - /* Extract Phoenix Summary header length */ - tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<< "Error: Can not determine Phoenix header length!" ); + /**************************************************** + * Read first 512 bytes to figure out some header * + * parameters.... * + ****************************************************/ - fclose(MSTARfp); - } else - { - sscanf((tptr+20), "%d", &phlen); - } + fread(tbuff, sizeof(char), 1024, MSTARfp); + rewind(MSTARfp); - /* Check for and extract native header length */ - tptr = (char *) strstr(tbuff,"native_header_length= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Can not determine native header length!\n"); - fclose(MSTARfp); - } else - { - sscanf((tptr+21), "%d", &nhlen); - } + /* Extract Phoenix Summary header length */ + tptr = (char *) strstr(tbuff,"PhoenixHeaderLength= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<< "Error: Can not determine Phoenix header length!" ); - /* Extract MSTAR column width */ - tptr = (char *) strstr(tbuff,"NumberOfColumns= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Error: Can not determine MSTAR image width"); - fclose(MSTARfp); - } else - { - sscanf((tptr+16), "%d", &numcols); - NbColonnes = static_cast<int>(numcols); - } + fclose(MSTARfp); + } + else + { + sscanf((tptr+20), "%d", &phlen); + } - /* Extract MSTAR row height */ - tptr = (char *) strstr(tbuff,"NumberOfRows= "); - if (tptr == (char *) NULL) - { - itkExceptionMacro(<<"Error: Can not determine MSTAR image height!"); - fclose(MSTARfp); - } else - { - sscanf((tptr+13), "%d",&numrows); - NbLignes = static_cast<int>(numrows); - } + /* Check for and extract native header length */ + tptr = (char *) strstr(tbuff,"native_header_length= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Can not determine native header length!\n"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+21), "%d", &nhlen); + } - /* Set MSTAR image type */ - if (nhlen == 0) - {/* Implies FLOAT MSTAR chip image */ - mstartype = CHIP_IMAGE; - } else - { - mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ - } + /* Extract MSTAR column width */ + tptr = (char *) strstr(tbuff,"NumberOfColumns= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Error: Can not determine MSTAR image width"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+16), "%d", &numcols); + NbColonnes = static_cast<int>(numcols); + } - otbMsgDebugMacro( << "Driver: MSTAR - "); + /* Extract MSTAR row height */ + tptr = (char *) strstr(tbuff,"NumberOfRows= "); + if (tptr == (char *) NULL) + { + itkExceptionMacro(<<"Error: Can not determine MSTAR image height!"); + fclose(MSTARfp); + } + else + { + sscanf((tptr+13), "%d",&numrows); + NbLignes = static_cast<int>(numrows); + } - this->SetNumberOfComponents(2); - this->SetNumberOfDimensions(2); - m_Dimensions[0] = NbColonnes; - m_Dimensions[1] = NbLignes; - m_NbOctetPixel = NbOctetPixel; - otbMsgDebugMacro( <<"Image size cree : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + /* Set MSTAR image type */ + if (nhlen == 0) + {/* Implies FLOAT MSTAR chip image */ + mstartype = CHIP_IMAGE; + } + else + { + mstartype = FSCENE_IMAGE; /* UnShort Fullscene */ + } - m_PixelType = VECTOR; + otbMsgDebugMacro( << "Driver: MSTAR - "); + this->SetNumberOfComponents(2); + this->SetNumberOfDimensions(2); + m_Dimensions[0] = NbColonnes; + m_Dimensions[1] = NbLignes; + m_NbOctetPixel = NbOctetPixel; + otbMsgDebugMacro( <<"Image size cree : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - /* Cleanup: close files */ - fclose(MSTARfp); + m_PixelType = VECTOR; - this->SetComponentType( FLOAT ); - } + /* Cleanup: close files */ + fclose(MSTARfp); - /** The write function is not implemented */ - void MSTARImageIO::WriteImageInformation(void) - { + this->SetComponentType( FLOAT ); - } +} - /** The write function is not implemented */ - void MSTARImageIO::Write( const void* buffer) - { +/** The write function is not implemented */ +void MSTARImageIO::WriteImageInformation(void) +{ - } +} - /** Print Self Method */ - void MSTARImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const - { +/** The write function is not implemented */ +void MSTARImageIO::Write( const void* buffer) +{ +} - } +/** Print Self Method */ +void MSTARImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ - float MSTARImageIO::byteswap_SR_IR(unsigned char *pointer) - { - float *temp; - unsigned char iarray[4], *charptr; - iarray[0] = *(pointer + 3); - iarray[1] = *(pointer + 2); - iarray[2] = *(pointer + 1); - iarray[3] = *(pointer ); - charptr = iarray; - temp = (float *) charptr; - return *(temp); - } +} - unsigned short MSTARImageIO::byteswap_SUS_IUS(unsigned char *pointer) - { - unsigned short *temp; - unsigned char iarray[2], *charptr; +float MSTARImageIO::byteswap_SR_IR(unsigned char *pointer) +{ + float *temp; + unsigned char iarray[4], *charptr; + + iarray[0] = *(pointer + 3); + iarray[1] = *(pointer + 2); + iarray[2] = *(pointer + 1); + iarray[3] = *(pointer ); + charptr = iarray; + temp = (float *) charptr; + return *(temp); +} + +unsigned short MSTARImageIO::byteswap_SUS_IUS(unsigned char *pointer) +{ + unsigned short *temp; + unsigned char iarray[2], *charptr; - iarray[0] = *(pointer + 1); - iarray[1] = *(pointer ); - charptr = iarray; - temp = (unsigned short *) charptr; - return *(temp); - } + iarray[0] = *(pointer + 1); + iarray[1] = *(pointer ); + charptr = iarray; + temp = (unsigned short *) charptr; + return *(temp); +} - int MSTARImageIO::CheckByteOrder(void) - { - short w = 0x0001; - char *b = (char *) &w; +int MSTARImageIO::CheckByteOrder(void) +{ + short w = 0x0001; + char *b = (char *) &w; - return(b[0] ? LSB_FIRST : MSB_FIRST); - } + return(b[0] ? LSB_FIRST : MSB_FIRST); +} diff --git a/Code/IO/otbMSTARImageIO.h b/Code/IO/otbMSTARImageIO.h index 4eb6bbb0f5686651c581ab3f9e86527f0ca35106..57f7bce695137a9ab1506e9f53b1b474e5a51be7 100644 --- a/Code/IO/otbMSTARImageIO.h +++ b/Code/IO/otbMSTARImageIO.h @@ -61,7 +61,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimension information for the set filename. */ virtual void ReadImageInformation(); @@ -76,7 +79,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Set the spacing and dimension information for the set filename. */ virtual void WriteImageInformation(); diff --git a/Code/IO/otbMWImageIO.cxx b/Code/IO/otbMWImageIO.cxx index 3e2a2c88405ed019ff5c29a0de62e5fdc41658d2..8b9628a4d14265d198d1c8721cedf4c00faddfad 100644 --- a/Code/IO/otbMWImageIO.cxx +++ b/Code/IO/otbMWImageIO.cxx @@ -37,11 +37,11 @@ MWImageIO::MWImageIO() m_ComponentType = UCHAR; if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) { - m_ByteOrder = LittleEndian; + m_ByteOrder = LittleEndian; } else { - m_ByteOrder = BigEndian; + m_ByteOrder = BigEndian; } m_FileByteOrder = BigEndian; @@ -60,31 +60,31 @@ MWImageIO::MWImageIO() MWImageIO::~MWImageIO() { - if( m_File.is_open() ) - { + if ( m_File.is_open() ) + { m_File.close(); - } + } } bool MWImageIO::CanReadFile( const char* filename ) { - std::string lFileName(filename); + std::string lFileName(filename); // Test the extension std::string extension = GetExtension(filename); - if((extension!="img")&&(extension!="")&&(extension!="mw")) - return false; - if( System::IsADirName(lFileName) == true ) - return false; - if( m_File.is_open() ) - m_File.close(); + if ((extension!="img")&&(extension!="")&&(extension!="mw")) + return false; + if ( System::IsADirName(lFileName) == true ) + return false; + if ( m_File.is_open() ) + m_File.close(); std::fstream header_file; header_file.open( filename, std::ios::in | std::ios::binary ); - if( header_file.fail() ) - { - otbMsgDevMacro(<<"MWImageIO::CanReadFile() failed header open ! " ); - return false; - } + if ( header_file.fail() ) + { + otbMsgDevMacro(<<"MWImageIO::CanReadFile() failed header open ! " ); + return false; + } //Read header informations bool lResult = InternalReadHeaderInformation(header_file,false); @@ -107,77 +107,77 @@ void MWImageIO::ReadVolume(void*) // Read image void MWImageIO::Read(void* buffer) { - char * p = static_cast<char *>(buffer); + char * p = static_cast<char *>(buffer); - int lNbLignes = this->GetIORegion().GetSize()[1]; - int lNbColonnes = this->GetIORegion().GetSize()[0]; - int lPremiereLigne = this->GetIORegion().GetIndex()[1]; // [1... ] - int lPremiereColonne = this->GetIORegion().GetIndex()[0]; // [1... ] + int lNbLignes = this->GetIORegion().GetSize()[1]; + int lNbColonnes = this->GetIORegion().GetSize()[0]; + int lPremiereLigne = this->GetIORegion().GetIndex()[1]; // [1... ] + int lPremiereColonne = this->GetIORegion().GetIndex()[0]; // [1... ] -otbMsgDevMacro( <<" MWImageIO::Read() "); -otbMsgDevMacro( <<" Dimensions de l'image : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); -otbMsgDevMacro( <<" Region lue (IORegion) : "<<this->GetIORegion()); -otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" MWImageIO::Read() "); + otbMsgDevMacro( <<" Dimensions de l'image : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region lue (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - std::streamoff headerLength = static_cast<std::streamoff> (64*sizeof(char)) + static_cast<std::streamoff> (m_Ncom*sizeof(char)); + std::streamoff headerLength = static_cast<std::streamoff> (64*sizeof(char)) + static_cast<std::streamoff> (m_Ncom*sizeof(char)); std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(this->GetComponentSize() * m_Dimensions[0]); - std::streamoff offset; - std::streamsize numberOfBytesToBeRead = static_cast<std::streamsize>(this->GetComponentSize() * lNbColonnes); - std::streamsize numberOfBytesRead; - std::streamsize cpt = 0; - for(int LineNo = lPremiereLigne;LineNo <lPremiereLigne + lNbLignes; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lPremiereColonne); - m_File.seekg(offset, std::ios::beg); - m_File.read( static_cast<char *>( p + cpt ), numberOfBytesToBeRead ); - numberOfBytesRead = m_File.gcount(); + std::streamoff offset; + std::streamsize numberOfBytesToBeRead = static_cast<std::streamsize>(this->GetComponentSize() * lNbColonnes); + std::streamsize numberOfBytesRead; + std::streamsize cpt = 0; + for (int LineNo = lPremiereLigne;LineNo <lPremiereLigne + lNbLignes; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lPremiereColonne); + m_File.seekg(offset, std::ios::beg); + m_File.read( static_cast<char *>( p + cpt ), numberOfBytesToBeRead ); + numberOfBytesRead = m_File.gcount(); #ifdef __APPLE_CC__ - // fail() is broken in the Mac. It returns true when reaches eof(). - if ( numberOfBytesRead != numberOfBytesToBeRead ) + // fail() is broken in the Mac. It returns true when reaches eof(). + if ( numberOfBytesRead != numberOfBytesToBeRead ) #else - if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_File.fail() ) + if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_File.fail() ) #endif - { - itkExceptionMacro(<<"MWImageIO::Read() Can Read the specified Region"); // read failed - } - cpt += numberOfBytesToBeRead; - } - - unsigned long numberOfPixelsPerLines = lNbLignes * lNbColonnes; - // Swap bytes if necessary - if ( 0 ) {} - otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerLines ) - else - { - itkExceptionMacro(<<"MWImageIO::Read() undefined component type! " ); - } + { + itkExceptionMacro(<<"MWImageIO::Read() Can Read the specified Region"); // read failed + } + cpt += numberOfBytesToBeRead; + } + + unsigned long numberOfPixelsPerLines = lNbLignes * lNbColonnes; + // Swap bytes if necessary + if ( 0 ) {} + otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerLines ) + else + { + itkExceptionMacro(<<"MWImageIO::Read() undefined component type! " ); + } } void MWImageIO::ReadImageInformation() { - if( m_File.is_open() ) - { - m_File.close(); - } - - m_File.open( m_FileName.c_str(), std::ios::in | std::ios::binary ); - if( m_File.fail() ) - { - itkExceptionMacro(<<"MWImageIO::ReadImageInformation() failed header open ! " ); - } - - //Read header informations - InternalReadHeaderInformation(m_File,true); - -otbMsgDebugMacro( <<"Driver to read: MW"); -otbMsgDebugMacro( <<" Read file : "<< m_FileName); -otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); -otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); -otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); -otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); -otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + if ( m_File.is_open() ) + { + m_File.close(); + } + + m_File.open( m_FileName.c_str(), std::ios::in | std::ios::binary ); + if ( m_File.fail() ) + { + itkExceptionMacro(<<"MWImageIO::ReadImageInformation() failed header open ! " ); + } + + //Read header informations + InternalReadHeaderInformation(m_File,true); + + otbMsgDebugMacro( <<"Driver to read: MW"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); } @@ -186,146 +186,146 @@ bool MWImageIO::InternalReadHeaderInformation(std::fstream & file, const bool re { char * headerInformation = new char[64]; - file.seekg(0, std::ios::beg ); - file.read(headerInformation,64); + file.seekg(0, std::ios::beg ); + file.read(headerInformation,64); unsigned short NbCol(0); unsigned short NbLig(0); unsigned short Nbcom(0); - //Set file byte order - if( headerInformation[0] == *("R") || headerInformation[1] == *("I") ) - { - m_FileByteOrder = BigEndian; + //Set file byte order + if ( headerInformation[0] == *("R") || headerInformation[1] == *("I") ) + { + m_FileByteOrder = BigEndian; //Read image dimensions Nbcom = (static_cast<unsigned int>(headerInformation[3])<<8) + static_cast<unsigned char> (headerInformation[2]); m_Ncom = Nbcom; - NbCol = (static_cast<unsigned int>(headerInformation[5])<<8) + static_cast<unsigned char> (headerInformation[4]); - NbLig = (static_cast<unsigned int>(headerInformation[7])<<8) + static_cast<unsigned char> (headerInformation[6]); - } - else if( headerInformation[0] == *("I") || headerInformation[1] == *("R") ) - { - m_FileByteOrder = LittleEndian; + NbCol = (static_cast<unsigned int>(headerInformation[5])<<8) + static_cast<unsigned char> (headerInformation[4]); + NbLig = (static_cast<unsigned int>(headerInformation[7])<<8) + static_cast<unsigned char> (headerInformation[6]); + } + else if ( headerInformation[0] == *("I") || headerInformation[1] == *("R") ) + { + m_FileByteOrder = LittleEndian; //Read image dimensions - Nbcom = ((static_cast<unsigned int>(headerInformation[2]))<<8) + static_cast<unsigned char> (headerInformation[3]); + Nbcom = ((static_cast<unsigned int>(headerInformation[2]))<<8) + static_cast<unsigned char> (headerInformation[3]); m_Ncom = Nbcom; - NbCol = ((static_cast<unsigned int>(headerInformation[4]))<<8) + static_cast<unsigned char> (headerInformation[5]); - NbLig = ((static_cast<unsigned int>(headerInformation[6]))<<8) + static_cast<unsigned char> (headerInformation[7]); + NbCol = ((static_cast<unsigned int>(headerInformation[4]))<<8) + static_cast<unsigned char> (headerInformation[5]); + NbLig = ((static_cast<unsigned int>(headerInformation[6]))<<8) + static_cast<unsigned char> (headerInformation[7]); } else { - if( reportError == true ) + if ( reportError == true ) { - itkExceptionMacro(<< "MW : impossible to determine CodePix information of the image"); + itkExceptionMacro(<< "MW : impossible to determine CodePix information of the image"); } return false; } - SetComponentType(FLOAT); + SetComponentType(FLOAT); //Initialisation of image informations - m_Dimensions[0] = NbCol; - m_Dimensions[1] = NbLig; - this->SetNumberOfComponents(1); - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); + m_Dimensions[0] = NbCol; + m_Dimensions[1] = NbLig; + this->SetNumberOfComponents(1); + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); delete[] headerInformation; - return(true); + return(true); } bool MWImageIO::CanWriteFile( const char* filename ) { - std::string lFileName(filename); + std::string lFileName(filename); std::string extension = GetExtension(filename); if (extension!="mw") - return false; - if( System::IsADirName(lFileName) == true ) - return false; + return false; + if ( System::IsADirName(lFileName) == true ) + return false; - return true; - } + return true; +} void MWImageIO::Write(const void* buffer) { - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } + if ( m_FlagWriteImageInformation == true ) + { + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } - unsigned long lNbLignes = this->GetIORegion().GetSize()[1]; - unsigned long lNbColonnes = this->GetIORegion().GetSize()[0]; - unsigned long lPremiereLigne = this->GetIORegion().GetIndex()[1]; // [1... ] - int lPremiereColonne = this->GetIORegion().GetIndex()[0]; // [1... ] + unsigned long lNbLignes = this->GetIORegion().GetSize()[1]; + unsigned long lNbColonnes = this->GetIORegion().GetSize()[0]; + unsigned long lPremiereLigne = this->GetIORegion().GetIndex()[1]; // [1... ] + int lPremiereColonne = this->GetIORegion().GetIndex()[0]; // [1... ] // Cas particuliers : on controle que si la r�gion � �crire est de la m�me dimension que l'image enti�re, // on commence l'offset � 0 (lorsque que l'on est pas en "Streaming") - if( (lNbLignes == m_Dimensions[1]) && (lNbColonnes == m_Dimensions[0])) + if ( (lNbLignes == m_Dimensions[1]) && (lNbColonnes == m_Dimensions[0])) { - otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); + otbMsgDevMacro(<<"Force l'offset de l'IORegion � 0"); lPremiereLigne = 0; lPremiereColonne = 0; } -otbMsgDevMacro( <<" MWImageIO::Write() "); -otbMsgDevMacro( <<" Dimensions de l'image : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); -otbMsgDevMacro( <<" Region lue (IORegion) : "<<this->GetIORegion()); -otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); -otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); + otbMsgDevMacro( <<" MWImageIO::Write() "); + otbMsgDevMacro( <<" Dimensions de l'image : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region lue (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); - std::streamoff numberOfBytesPerLines = this->GetComponentSize() * m_Dimensions[0]; + std::streamoff numberOfBytesPerLines = this->GetComponentSize() * m_Dimensions[0]; std::streamoff headerLength = static_cast<std::streamoff> (64*sizeof(char)) + static_cast<std::streamoff> (m_Ncom*sizeof(char)); - std::streamoff offset; - std::streamsize numberOfBytesToBeWrite = this->GetComponentSize() * lNbColonnes; - std::streamsize cpt = 0; - - const char * p = static_cast<const char *>(buffer); - - for(unsigned long LineNo = lPremiereLigne;LineNo <lPremiereLigne + lNbLignes; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(this->GetComponentSize() * lPremiereColonne); - m_File.seekp(offset, std::ios::beg); - m_File.write( static_cast<const char *>( p + cpt ), numberOfBytesToBeWrite ); - cpt += numberOfBytesToBeWrite; - } + std::streamoff offset; + std::streamsize numberOfBytesToBeWrite = this->GetComponentSize() * lNbColonnes; + std::streamsize cpt = 0; + + const char * p = static_cast<const char *>(buffer); + + for (unsigned long LineNo = lPremiereLigne;LineNo <lPremiereLigne + lNbLignes; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(this->GetComponentSize() * lPremiereColonne); + m_File.seekp(offset, std::ios::beg); + m_File.write( static_cast<const char *>( p + cpt ), numberOfBytesToBeWrite ); + cpt += numberOfBytesToBeWrite; + } } void MWImageIO::WriteImageInformation() { - if ( m_FileName == "" ) - { - itkExceptionMacro(<<"A FileName must be specified."); - } - if( CanWriteFile(m_FileName.c_str()) == false) - { - itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a MW file"); - } - // Close file from any previous image - if ( m_File.is_open() ) - { - m_File.close(); - } - - // Open the new file for writing - // Actually open the file - m_File.open( m_FileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); - if( m_File.fail() ) - { - itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); - } - - //Writing header information - if( 0 ) {} - if( (this->GetComponentType() != FLOAT) ) + if ( m_FileName == "" ) + { + itkExceptionMacro(<<"A FileName must be specified."); + } + if ( CanWriteFile(m_FileName.c_str()) == false) + { + itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a MW file"); + } + // Close file from any previous image + if ( m_File.is_open() ) + { + m_File.close(); + } + + // Open the new file for writing + // Actually open the file + m_File.open( m_FileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); + if ( m_File.fail() ) + { + itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); + } + + //Writing header information + if ( 0 ) {} + if ( (this->GetComponentType() != FLOAT) ) { itkExceptionMacro(<< "MegaWave fimage format only accepts FLOAT32 data type"); } - m_File.seekp(0, std::ios::beg ); + m_File.seekp(0, std::ios::beg ); char header[64]; std::string comments("Image written with otb mw_IO_factory"); @@ -333,7 +333,7 @@ void MWImageIO::WriteImageInformation() //Initialization to 0 for (unsigned int i =0; i<64; i++) header[i] = static_cast<unsigned char>(0); - //Write image size and other information + //Write image size and other information unsigned short lNbComments = m_Ncom; unsigned short lNbLignes = static_cast<unsigned short>(this->GetIORegion().GetSize()[1]); unsigned short lNbColonnes =static_cast<unsigned short>( this->GetIORegion().GetSize()[0]); @@ -382,20 +382,20 @@ void MWImageIO::WriteImageInformation() m_File.write(comments.data(),36); -otbMsgDebugMacro( <<"Driver to write: MW"); -otbMsgDebugMacro( <<" Write file : "<< m_FileName); -otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); -otbMsgDebugMacro( <<" Type Mw : "<<m_TypeMW); -otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); -otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); -otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); -otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to write: MW"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" Type Mw : "<<m_TypeMW); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); } std::string MWImageIO::GetExtension( const std::string& filename ) { - // This assumes that the final '.' in a file name is the delimiter + // This assumes that the final '.' in a file name is the delimiter // for the file's extension type const std::string::size_type it = filename.find_last_of( "." ); @@ -412,7 +412,7 @@ std::string MWImageIO::GetExtension( const std::string& filename ) return( fileExt3 ); } - return( fileExt ); + return( fileExt ); } diff --git a/Code/IO/otbMWImageIO.h b/Code/IO/otbMWImageIO.h index 8f66b466c070547155195eceb5c1227e29905a7a..cdb18108427cd76f94879e020f7bc3a7dcc5ae02 100644 --- a/Code/IO/otbMWImageIO.h +++ b/Code/IO/otbMWImageIO.h @@ -61,7 +61,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -79,7 +82,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ @@ -116,7 +122,8 @@ private: /** Internal method to read header informations */ bool InternalReadHeaderInformation(std::fstream & file, const bool reportError); - inline void ByteSplitting(unsigned short a, unsigned short &low, unsigned short &high){ + inline void ByteSplitting(unsigned short a, unsigned short &low, unsigned short &high) + { unsigned short b = 255; low = a & b; high = (a>>8) & b; diff --git a/Code/IO/otbMetaDataKey.cxx b/Code/IO/otbMetaDataKey.cxx index 2312bf89d49058b66718988f8f45915c876c9ba5..54d0f7eb42c64a4f884b82aa542fcc8c18a98e60 100644 --- a/Code/IO/otbMetaDataKey.cxx +++ b/Code/IO/otbMetaDataKey.cxx @@ -75,25 +75,25 @@ const std::string MetaDataKey::OSSIMKeywordlistDelimiterKey = "OSSIMKeywordlistD }; */ const MetaDataKey::KeyTypeDef Types[] = - { - MetaDataKey::KeyTypeDef(MetaDataKey::DriverShortNameKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::DriverLongNameKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::ProjectionRefKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::GCPProjectionKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::GCPParametersKey , MetaDataKey::TOTB_GCP), - MetaDataKey::KeyTypeDef(MetaDataKey::GCPCountKey, MetaDataKey::TENTIER), - MetaDataKey::KeyTypeDef(MetaDataKey::GeoTransformKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::MetadataKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::UpperLeftCornerKey, MetaDataKey::TVECTOR), - MetaDataKey::KeyTypeDef(MetaDataKey::UpperRightCornerKey, MetaDataKey::TVECTOR), - MetaDataKey::KeyTypeDef(MetaDataKey::LowerLeftCornerKey, MetaDataKey::TVECTOR), - MetaDataKey::KeyTypeDef(MetaDataKey::LowerRightCornerKey, MetaDataKey::TVECTOR), - MetaDataKey::KeyTypeDef(MetaDataKey::ColorTableNameKey, MetaDataKey::TSTRING), - MetaDataKey::KeyTypeDef(MetaDataKey::ColorEntryCountKey, MetaDataKey::TENTIER), - MetaDataKey::KeyTypeDef(MetaDataKey::ColorEntryAsRGBKey, MetaDataKey::TVECTOR), - MetaDataKey::KeyTypeDef(MetaDataKey::OSSIMKeywordlistKey, MetaDataKey::TOSSIMKEYWORDLIST), - MetaDataKey::KeyTypeDef(MetaDataKey::OSSIMKeywordlistDelimiterKey,MetaDataKey::TSTRING) - }; +{ + MetaDataKey::KeyTypeDef(MetaDataKey::DriverShortNameKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::DriverLongNameKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::ProjectionRefKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::GCPProjectionKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::GCPParametersKey , MetaDataKey::TOTB_GCP), + MetaDataKey::KeyTypeDef(MetaDataKey::GCPCountKey, MetaDataKey::TENTIER), + MetaDataKey::KeyTypeDef(MetaDataKey::GeoTransformKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::MetadataKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::UpperLeftCornerKey, MetaDataKey::TVECTOR), + MetaDataKey::KeyTypeDef(MetaDataKey::UpperRightCornerKey, MetaDataKey::TVECTOR), + MetaDataKey::KeyTypeDef(MetaDataKey::LowerLeftCornerKey, MetaDataKey::TVECTOR), + MetaDataKey::KeyTypeDef(MetaDataKey::LowerRightCornerKey, MetaDataKey::TVECTOR), + MetaDataKey::KeyTypeDef(MetaDataKey::ColorTableNameKey, MetaDataKey::TSTRING), + MetaDataKey::KeyTypeDef(MetaDataKey::ColorEntryCountKey, MetaDataKey::TENTIER), + MetaDataKey::KeyTypeDef(MetaDataKey::ColorEntryAsRGBKey, MetaDataKey::TVECTOR), + MetaDataKey::KeyTypeDef(MetaDataKey::OSSIMKeywordlistKey, MetaDataKey::TOSSIMKEYWORDLIST), + MetaDataKey::KeyTypeDef(MetaDataKey::OSSIMKeywordlistDelimiterKey,MetaDataKey::TSTRING) +}; MetaDataKey::KeyType MetaDataKey::GetKeyType(std::string name) @@ -106,7 +106,7 @@ MetaDataKey::KeyType MetaDataKey::GetKeyType(std::string name) if ( (name.find(Types[i].keyname) >= 0 ) && - (name.find(Types[i].keyname) <= name.size() ) ) + (name.find(Types[i].keyname) <= name.size() ) ) { ktype = Types[i].type; break; diff --git a/Code/IO/otbMetaDataKey.h b/Code/IO/otbMetaDataKey.h index f3b228280aef46fb9cb2059ab153be2461583d47..bfe3c154618c5c4d86a9d0bd623bb1f76bff4326 100644 --- a/Code/IO/otbMetaDataKey.h +++ b/Code/IO/otbMetaDataKey.h @@ -44,8 +44,8 @@ public: typedef MetaDataKey Self; - MetaDataKey(){}; - virtual ~MetaDataKey(){}; + MetaDataKey() {}; + virtual ~MetaDataKey() {}; static const std::string DriverShortNameKey; static const std::string DriverLongNameKey; @@ -73,7 +73,8 @@ public: static const std::string OSSIMKeywordlistKey; static const std::string OSSIMKeywordlistDelimiterKey; - enum KeyType { + enum KeyType + { TSTRING, TENTIER, TDOUBLE, @@ -123,73 +124,73 @@ private: */ class ITK_EXPORT OTB_GCP { - public: - +public: - /** Unique identifier, often numeric */ - std::string m_Id; - /** Informational message or "" */ - std::string m_Info; + /** Unique identifier, often numeric */ + std::string m_Id; - /** Pixel (x) location of GCP on raster */ - double m_GCPCol; + /** Informational message or "" */ + std::string m_Info; - /** Line (y) location of GCP on raster */ - double m_GCPRow; + /** Pixel (x) location of GCP on raster */ + double m_GCPCol; - /** X position of GCP in georeferenced space */ - double m_GCPX; + /** Line (y) location of GCP on raster */ + double m_GCPRow; - /** Y position of GCP in georeferenced space */ - double m_GCPY; + /** X position of GCP in georeferenced space */ + double m_GCPX; - /** Elevation of GCP, or zero if not known */ - double m_GCPZ; + /** Y position of GCP in georeferenced space */ + double m_GCPY; + /** Elevation of GCP, or zero if not known */ + double m_GCPZ; - OTB_GCP(){}; - OTB_GCP( const GDAL_GCP * psGCP ) - { - m_Id = std::string(psGCP->pszId); - m_Info = std::string(psGCP->pszInfo); - m_GCPRow = psGCP->dfGCPLine; - m_GCPCol = psGCP->dfGCPPixel; - m_GCPX = psGCP->dfGCPX; - m_GCPY = psGCP->dfGCPY; - m_GCPZ = psGCP->dfGCPZ; - } - virtual ~OTB_GCP(){}; - OTB_GCP(const OTB_GCP& pGcp) - { - m_Id = pGcp.m_Id; - m_Info = pGcp.m_Info; - m_GCPCol = pGcp.m_GCPCol; - m_GCPRow = pGcp.m_GCPRow; - m_GCPX = pGcp.m_GCPX; - m_GCPY = pGcp.m_GCPY; - m_GCPZ = pGcp.m_GCPZ; - } - - void operator=(const OTB_GCP& pGcp) - { - m_Id = pGcp.m_Id; - m_Info = pGcp.m_Info; - m_GCPCol = pGcp.m_GCPCol; - m_GCPRow = pGcp.m_GCPRow; - m_GCPX = pGcp.m_GCPX; - m_GCPY = pGcp.m_GCPY; - m_GCPZ = pGcp.m_GCPZ; - } - - void Print(std::ostream& os)const - { - os << " GCP Id = " << this->m_Id << std::endl; - os << " GCP Info = " << this->m_Info << std::endl; - os << " GCP (Row,Col) = (" << this->m_GCPRow << "," << this->m_GCPCol << ")" << std::endl; - os << " GCP (X,Y,Z) = (" << this->m_GCPX << "," << this->m_GCPY << "," << this->m_GCPZ << ")" << std::endl; - } + OTB_GCP() {}; + OTB_GCP( const GDAL_GCP * psGCP ) + { + m_Id = std::string(psGCP->pszId); + m_Info = std::string(psGCP->pszInfo); + m_GCPRow = psGCP->dfGCPLine; + m_GCPCol = psGCP->dfGCPPixel; + m_GCPX = psGCP->dfGCPX; + m_GCPY = psGCP->dfGCPY; + m_GCPZ = psGCP->dfGCPZ; + } + virtual ~OTB_GCP() {}; + + OTB_GCP(const OTB_GCP& pGcp) + { + m_Id = pGcp.m_Id; + m_Info = pGcp.m_Info; + m_GCPCol = pGcp.m_GCPCol; + m_GCPRow = pGcp.m_GCPRow; + m_GCPX = pGcp.m_GCPX; + m_GCPY = pGcp.m_GCPY; + m_GCPZ = pGcp.m_GCPZ; + } + + void operator=(const OTB_GCP& pGcp) + { + m_Id = pGcp.m_Id; + m_Info = pGcp.m_Info; + m_GCPCol = pGcp.m_GCPCol; + m_GCPRow = pGcp.m_GCPRow; + m_GCPX = pGcp.m_GCPX; + m_GCPY = pGcp.m_GCPY; + m_GCPZ = pGcp.m_GCPZ; + } + + void Print(std::ostream& os)const + { + os << " GCP Id = " << this->m_Id << std::endl; + os << " GCP Info = " << this->m_Info << std::endl; + os << " GCP (Row,Col) = (" << this->m_GCPRow << "," << this->m_GCPCol << ")" << std::endl; + os << " GCP (X,Y,Z) = (" << this->m_GCPX << "," << this->m_GCPY << "," << this->m_GCPZ << ")" << std::endl; + } }; diff --git a/Code/IO/otbONERAImageIO.cxx b/Code/IO/otbONERAImageIO.cxx index 513b74e7eb1a20cec67e07c7705a572076d64dbf..e5edcfc36f7ed50eaccea2adf7e3da6b299f3e24 100644 --- a/Code/IO/otbONERAImageIO.cxx +++ b/Code/IO/otbONERAImageIO.cxx @@ -34,580 +34,580 @@ namespace otb { - ONERAImageIO::ONERAImageIO() - { +ONERAImageIO::ONERAImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); - m_PixelType = COMPLEX; - m_ComponentType = FLOAT; - m_NbOctetPixel = 4; + this->SetNumberOfDimensions(2); + m_PixelType = COMPLEX; + m_ComponentType = FLOAT; + m_NbOctetPixel = 4; // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_FlagWriteImageInformation = true; + m_FlagWriteImageInformation = true; - if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) - { - m_ByteOrder = LittleEndian; - } - else - { - m_ByteOrder = BigEndian; - } + if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) + { + m_ByteOrder = LittleEndian; + } + else + { + m_ByteOrder = BigEndian; + } - m_FileByteOrder = BigEndian; + m_FileByteOrder = BigEndian; - } +} - ONERAImageIO::~ONERAImageIO() +ONERAImageIO::~ONERAImageIO() +{ + if ( m_Datafile.is_open() ) { - if( m_Datafile.is_open() ) - { - m_Datafile.close(); - } - if( m_Headerfile.is_open() ) - { - m_Headerfile.close(); - } + m_Datafile.close(); } - - bool ONERAImageIO::CanReadFile( const char* FileNameToRead ) + if ( m_Headerfile.is_open() ) { + m_Headerfile.close(); + } +} - std::string filename(FileNameToRead); - std::string ext; - if( m_Datafile.is_open() ) - { - m_Datafile.close(); - } - if( m_Headerfile.is_open() ) - { - m_Headerfile.close(); - } +bool ONERAImageIO::CanReadFile( const char* FileNameToRead ) +{ - if( System::IsADirName(filename) == true ) - { - return false; - } + std::string filename(FileNameToRead); + std::string ext; + if ( m_Datafile.is_open() ) + { + m_Datafile.close(); + } + if ( m_Headerfile.is_open() ) + { + m_Headerfile.close(); + } - const std::string HeaderFileName = System::GetRootName(filename)+".ent"; - const std::string DataFileName = System::GetRootName(filename)+".dat"; + if ( System::IsADirName(filename) == true ) + { + return false; + } - m_Headerfile.open( HeaderFileName.c_str(), std::ios::in ); - if( m_Headerfile.fail() ) - { - otbMsgDevMacro(<<"ONERAImageIO::CanReadFile() failed header open ! " ); - return false; - } - m_Datafile.open( DataFileName.c_str(), std::ios::in ); - if( m_Datafile.fail() ) - { - otbMsgDevMacro(<<"ONERAImageIO::CanReadFile() failed data open ! " ); - return false; - } + const std::string HeaderFileName = System::GetRootName(filename)+".ent"; + const std::string DataFileName = System::GetRootName(filename)+".dat"; + + m_Headerfile.open( HeaderFileName.c_str(), std::ios::in ); + if ( m_Headerfile.fail() ) + { + otbMsgDevMacro(<<"ONERAImageIO::CanReadFile() failed header open ! " ); + return false; + } + m_Datafile.open( DataFileName.c_str(), std::ios::in ); + if ( m_Datafile.fail() ) + { + otbMsgDevMacro(<<"ONERAImageIO::CanReadFile() failed data open ! " ); + return false; + } // Check magic_number - int magicNumber; - m_Datafile.seekg(0, std::ios::beg ); - m_Datafile.read((char*)(&magicNumber),4); + int magicNumber; + m_Datafile.seekg(0, std::ios::beg ); + m_Datafile.read((char*)(&magicNumber),4); - if( magicNumber == ONERA_MAGIC_NUMBER ) + if ( magicNumber == ONERA_MAGIC_NUMBER ) + { + m_FileByteOrder = m_ByteOrder; + } + else + { + if ( m_ByteOrder == LittleEndian ) { - m_FileByteOrder = m_ByteOrder; + m_FileByteOrder = BigEndian; } - else + else if ( m_ByteOrder == BigEndian ) { - if ( m_ByteOrder == LittleEndian ) - { - m_FileByteOrder = BigEndian; - } - else if ( m_ByteOrder == BigEndian ) - { - m_FileByteOrder = LittleEndian; - } + m_FileByteOrder = LittleEndian; } + } // Swap if necessary - otbSwappFileOrderToSystemOrderMacro(int, &magicNumber, 1); - - m_Headerfile.close(); - m_Datafile.close(); + otbSwappFileOrderToSystemOrderMacro(int, &magicNumber, 1); - if( magicNumber == ONERA_MAGIC_NUMBER ) - { - return true; - } - else - { - return false; - } + m_Headerfile.close(); + m_Datafile.close(); + if ( magicNumber == ONERA_MAGIC_NUMBER ) + { + return true; + } + else + { + return false; } +} + // Used to print information about this object - void ONERAImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } +void ONERAImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} // Read a 3D image (or event more bands)... not implemented yet - void ONERAImageIO::ReadVolume(void*) - { - } +void ONERAImageIO::ReadVolume(void*) +{ +} // Read image - void ONERAImageIO::Read(void* buffer) +void ONERAImageIO::Read(void* buffer) +{ + unsigned int dim; + const unsigned int dimensions = this->GetNumberOfDimensions(); + unsigned long numberOfPixels = 1; + for (dim=0; dim< dimensions; dim++ ) { - unsigned int dim; - const unsigned int dimensions = this->GetNumberOfDimensions(); - unsigned long numberOfPixels = 1; - for(dim=0; dim< dimensions; dim++ ) - { - numberOfPixels *= m_Dimensions[ dim ]; - } + numberOfPixels *= m_Dimensions[ dim ]; + } - unsigned char * p = static_cast<unsigned char *>(buffer); + unsigned char * p = static_cast<unsigned char *>(buffer); - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] - otbMsgDevMacro( <<" ONERAImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" ONERAImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); //read header information file: - if ( ! this->OpenOneraDataFileForReading(m_FileName.c_str()) ) - { - itkExceptionMacro(<< "Cannot read requested file"); - } + if ( ! this->OpenOneraDataFileForReading(m_FileName.c_str()) ) + { + itkExceptionMacro(<< "Cannot read requested file"); + } - std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(2 * m_width * m_NbOctetPixel); - std::streamoff headerLength = ONERA_HEADER_LENGTH + numberOfBytesPerLines; - std::streamoff offset; - std::streamsize numberOfBytesToBeRead = 2 * m_NbOctetPixel *lNbColumns; - std::streamsize numberOfBytesRead; + std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(2 * m_width * m_NbOctetPixel); + std::streamoff headerLength = ONERA_HEADER_LENGTH + numberOfBytesPerLines; + std::streamoff offset; + std::streamsize numberOfBytesToBeRead = 2 * m_NbOctetPixel *lNbColumns; + std::streamsize numberOfBytesRead; - char* value = new char[numberOfBytesToBeRead]; - std::streamsize cpt = 0; + char* value = new char[numberOfBytesToBeRead]; + std::streamsize cpt = 0; - for(int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); - m_Datafile.seekg(offset, std::ios::beg); - m_Datafile.read( static_cast<char *>( value ), numberOfBytesToBeRead ); - numberOfBytesRead = m_Datafile.gcount(); + for (int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + { + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); + m_Datafile.seekg(offset, std::ios::beg); + m_Datafile.read( static_cast<char *>( value ), numberOfBytesToBeRead ); + numberOfBytesRead = m_Datafile.gcount(); #ifdef __APPLE_CC__ - // fail() is broken in the Mac. It returns true when reaches eof(). - if ( numberOfBytesRead != numberOfBytesToBeRead ) + // fail() is broken in the Mac. It returns true when reaches eof(). + if ( numberOfBytesRead != numberOfBytesToBeRead ) #else - if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_Datafile.fail() ) + if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_Datafile.fail() ) #endif - { - itkExceptionMacro(<<"ONERAImageIO::Read() Can Read the specified Region"); // read failed - } - - memcpy((void*)(&(p[cpt])),(const void*)(value),(size_t)( numberOfBytesToBeRead)); - cpt += numberOfBytesToBeRead; + { + itkExceptionMacro(<<"ONERAImageIO::Read() Can Read the specified Region"); // read failed } + memcpy((void*)(&(p[cpt])),(const void*)(value),(size_t)( numberOfBytesToBeRead)); + cpt += numberOfBytesToBeRead; + } + //byte swapping depending on pixel type: - unsigned long numberOfPixelsPerRegion = lNbLines * lNbColumns * 2; - // Swap bytes if necessary - if ( 0 ) {} - otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerRegion ) - otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsPerRegion ) - else - { - itkExceptionMacro(<<"ONERAImageIO::Read() undefined component type! " ); - } + unsigned long numberOfPixelsPerRegion = lNbLines * lNbColumns * 2; + // Swap bytes if necessary + if ( 0 ) {} + otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsPerRegion ) + otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsPerRegion ) + else + { + itkExceptionMacro(<<"ONERAImageIO::Read() undefined component type! " ); + } - delete [] value; - value = NULL; + delete [] value; + value = NULL; - } +} - bool ONERAImageIO::OpenOneraDataFileForReading(const char* filename) - { +bool ONERAImageIO::OpenOneraDataFileForReading(const char* filename) +{ // Make sure that we have a file to - std::string lFileName(filename); - if ( lFileName.empty() ) - { - itkExceptionMacro(<<"A FileName must be specified."); - return false; - } + std::string lFileName(filename); + if ( lFileName.empty() ) + { + itkExceptionMacro(<<"A FileName must be specified."); + return false; + } // Close file from any previous image - if ( m_Datafile.is_open() ) - { - m_Datafile.close(); - } - const std::string DataFileName = System::GetRootName(filename)+".dat"; + if ( m_Datafile.is_open() ) + { + m_Datafile.close(); + } + const std::string DataFileName = System::GetRootName(filename)+".dat"; // Open the new file for reading - m_Datafile.open( DataFileName.c_str(), std::ios::in | std::ios::binary ); - if( m_Datafile.fail() ) - { - otbMsgDebugMacro(<<"ONERAImageIO::CanReadFile() failed data open ! " ); - return false; - } - return true; + m_Datafile.open( DataFileName.c_str(), std::ios::in | std::ios::binary ); + if ( m_Datafile.fail() ) + { + otbMsgDebugMacro(<<"ONERAImageIO::CanReadFile() failed data open ! " ); + return false; } + return true; +} - bool ONERAImageIO::OpenOneraHeaderFileForReading(const char* filename) - { +bool ONERAImageIO::OpenOneraHeaderFileForReading(const char* filename) +{ // Make sure that we have a file to - std::string lFileName(filename); - if ( lFileName.empty() ) - { - itkExceptionMacro(<<"A FileName must be specified."); - return false; - } + std::string lFileName(filename); + if ( lFileName.empty() ) + { + itkExceptionMacro(<<"A FileName must be specified."); + return false; + } // Close file from any previous image - if ( m_Headerfile.is_open() ) - { - m_Headerfile.close(); - } - const std::string HeaderFileName = System::GetRootName(filename)+".ent"; + if ( m_Headerfile.is_open() ) + { + m_Headerfile.close(); + } + const std::string HeaderFileName = System::GetRootName(filename)+".ent"; // Open the new file for reading // Actually open the file - m_Headerfile.open( HeaderFileName.c_str(), std::ios::in ); - if( m_Headerfile.fail() ) - { - otbMsgDebugMacro(<<"ONERAImageIO::CanReadFile() failed header open ! " ); - return false; - } - return true; - } - - void ONERAImageIO::ReadImageInformation() + m_Headerfile.open( HeaderFileName.c_str(), std::ios::in ); + if ( m_Headerfile.fail() ) { - this->InternalReadImageInformation(); + otbMsgDebugMacro(<<"ONERAImageIO::CanReadFile() failed header open ! " ); + return false; } + return true; +} +void ONERAImageIO::ReadImageInformation() +{ + this->InternalReadImageInformation(); +} - void ONERAImageIO::InternalReadImageInformation() - { +void ONERAImageIO::InternalReadImageInformation() +{ - if ( ! this->OpenOneraDataFileForReading(m_FileName.c_str()) ) - { - itkExceptionMacro(<< "Cannot read ONERA data file "<<m_FileName ); - } - if ( ! this->OpenOneraHeaderFileForReading(m_FileName.c_str()) ) - { - itkExceptionMacro(<< "Cannot read ONERA header file "<<m_FileName); - } + if ( ! this->OpenOneraDataFileForReading(m_FileName.c_str()) ) + { + itkExceptionMacro(<< "Cannot read ONERA data file "<<m_FileName ); + } + + if ( ! this->OpenOneraHeaderFileForReading(m_FileName.c_str()) ) + { + itkExceptionMacro(<< "Cannot read ONERA header file "<<m_FileName); + } // check "Format_valeurs_look" - char* sHeader = new char[1024]; + char* sHeader = new char[1024]; // skip 2 lines - m_Headerfile.getline(sHeader,1024); - m_Headerfile.getline(sHeader,1024); - m_Headerfile.getline(sHeader,1024); - std::string sPixelType(sHeader); + m_Headerfile.getline(sHeader,1024); + m_Headerfile.getline(sHeader,1024); + m_Headerfile.getline(sHeader,1024); + std::string sPixelType(sHeader); - if ( sPixelType.compare("cmplx_real_4") ) - { - m_NbBands = 1; - this->SetFileTypeToBinary(); - this->SetNumberOfComponents(2); - this->SetPixelType(COMPLEX); - m_ComponentType = FLOAT; - m_NbOctetPixel = 4; - } - else - { - itkExceptionMacro(<< "data format not supported by OTB (only 'complex_real_4' is available)"); - } + if ( sPixelType.compare("cmplx_real_4") ) + { + m_NbBands = 1; + this->SetFileTypeToBinary(); + this->SetNumberOfComponents(2); + this->SetPixelType(COMPLEX); + m_ComponentType = FLOAT; + m_NbOctetPixel = 4; + } + else + { + itkExceptionMacro(<< "data format not supported by OTB (only 'complex_real_4' is available)"); + } // Check magic_number - int magicNumber; - m_Datafile.seekg(0, std::ios::beg ); - m_Datafile.read((char*)(&magicNumber),4); - if( magicNumber == ONERA_MAGIC_NUMBER ) + int magicNumber; + m_Datafile.seekg(0, std::ios::beg ); + m_Datafile.read((char*)(&magicNumber),4); + if ( magicNumber == ONERA_MAGIC_NUMBER ) + { + m_FileByteOrder = m_ByteOrder; + } + else + { + if ( m_ByteOrder == LittleEndian ) { - m_FileByteOrder = m_ByteOrder; + m_FileByteOrder = BigEndian; } - else + else if ( m_ByteOrder == BigEndian ) { - if ( m_ByteOrder == LittleEndian ) - { - m_FileByteOrder = BigEndian; - } - else if ( m_ByteOrder == BigEndian ) - { - m_FileByteOrder = LittleEndian; - } + m_FileByteOrder = LittleEndian; } - otbSwappFileOrderToSystemOrderMacro(int, &magicNumber, 1); + } + otbSwappFileOrderToSystemOrderMacro(int, &magicNumber, 1); // Find info.. : Number of Row , Nb of Columns - short NbCol; + short NbCol; - m_Datafile.seekg(ONERA_HEADER_LENGTH + 2, std::ios::beg ); - m_Datafile.read((char*)(&NbCol),2); - otbSwappFileOrderToSystemOrderMacro(short, &NbCol, 1); + m_Datafile.seekg(ONERA_HEADER_LENGTH + 2, std::ios::beg ); + m_Datafile.read((char*)(&NbCol),2); + otbSwappFileOrderToSystemOrderMacro(short, &NbCol, 1); - m_Datafile.seekg(0, std::ios::end); - long gcountHead = static_cast<long>(ONERA_HEADER_LENGTH + 2*4*NbCol); - long gcount = static_cast<long>(m_Datafile.tellg()); + m_Datafile.seekg(0, std::ios::end); + long gcountHead = static_cast<long>(ONERA_HEADER_LENGTH + 2*4*NbCol); + long gcount = static_cast<long>(m_Datafile.tellg()); // Defining the image size: - m_width = static_cast<int> ( NbCol ); - m_height = static_cast<int> ( (gcount-gcountHead) / (4 * 2 * NbCol) ); + m_width = static_cast<int> ( NbCol ); + m_height = static_cast<int> ( (gcount-gcountHead) / (4 * 2 * NbCol) ); - if( (m_width==0) || (m_height==0)) - { - itkExceptionMacro(<<"Unknown image dimension"); - } - else - { - // Set image dimensions into IO - m_Dimensions[0] = m_width; - m_Dimensions[1] = m_height; - } + if ( (m_width==0) || (m_height==0)) + { + itkExceptionMacro(<<"Unknown image dimension"); + } + else + { + // Set image dimensions into IO + m_Dimensions[0] = m_width; + m_Dimensions[1] = m_height; + } - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); - otbMsgDebugMacro( <<"Driver to read: ONERA"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" PixelType : "<<this->GetPixelTypeAsString(this->GetPixelType())); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentTypeAsString(this->GetComponentType())); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" NbOctetPixel : "<<m_NbOctetPixel); - otbMsgDebugMacro( <<" Host byte order : "<<this->GetByteOrderAsString(m_ByteOrder)); - otbMsgDebugMacro( <<" File byte order : "<<this->GetByteOrderAsString(m_FileByteOrder)); + otbMsgDebugMacro( <<"Driver to read: ONERA"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" PixelType : "<<this->GetPixelTypeAsString(this->GetPixelType())); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentTypeAsString(this->GetComponentType())); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" NbOctetPixel : "<<m_NbOctetPixel); + otbMsgDebugMacro( <<" Host byte order : "<<this->GetByteOrderAsString(m_ByteOrder)); + otbMsgDebugMacro( <<" File byte order : "<<this->GetByteOrderAsString(m_FileByteOrder)); - } +} - bool ONERAImageIO::OpenOneraDataFileForWriting(const char* filename) - { +bool ONERAImageIO::OpenOneraDataFileForWriting(const char* filename) +{ // Make sure that we have a file to - std::string lFileName(filename); - if ( lFileName.empty() ) - { - itkExceptionMacro(<<"A FileName must be specified."); - return false; - } + std::string lFileName(filename); + if ( lFileName.empty() ) + { + itkExceptionMacro(<<"A FileName must be specified."); + return false; + } // Close file from any previous image - if ( m_Datafile.is_open() ) - { - m_Datafile.close(); - } - const std::string DataFileName = System::GetRootName(filename)+".dat"; + if ( m_Datafile.is_open() ) + { + m_Datafile.close(); + } + const std::string DataFileName = System::GetRootName(filename)+".dat"; // Open the new file for reading // Actually open the file - m_Datafile.open( DataFileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); - if( m_Datafile.fail() ) - { - otbMsgDebugMacro(<<"ONERAImageIO::OpenOneraDataFileForWriting() failed data open ! " ); - return false; - } - return true; + m_Datafile.open( DataFileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); + if ( m_Datafile.fail() ) + { + otbMsgDebugMacro(<<"ONERAImageIO::OpenOneraDataFileForWriting() failed data open ! " ); + return false; } + return true; +} - bool ONERAImageIO::OpenOneraHeaderFileForWriting(const char* filename) - { +bool ONERAImageIO::OpenOneraHeaderFileForWriting(const char* filename) +{ // Make sure that we have a file to - std::string lFileName(filename); - if ( lFileName.empty() ) - { - itkExceptionMacro(<<"A FileName must be specified."); - return false; - } + std::string lFileName(filename); + if ( lFileName.empty() ) + { + itkExceptionMacro(<<"A FileName must be specified."); + return false; + } // Close file from any previous image - if ( m_Headerfile.is_open() ) - { - m_Headerfile.close(); - } - const std::string HeaderFileName = System::GetRootName(filename)+".ent"; + if ( m_Headerfile.is_open() ) + { + m_Headerfile.close(); + } + const std::string HeaderFileName = System::GetRootName(filename)+".ent"; // Open the new file for reading // Actually open the file - m_Headerfile.open( HeaderFileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); - if( m_Headerfile.fail() ) - { - otbMsgDebugMacro(<<"ONERAImageIO::OpenOneraHeaderFileForWriting() failed header open ! " ); - return false; - } - return true; + m_Headerfile.open( HeaderFileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); + if ( m_Headerfile.fail() ) + { + otbMsgDebugMacro(<<"ONERAImageIO::OpenOneraHeaderFileForWriting() failed header open ! " ); + return false; } + return true; +} - bool ONERAImageIO::CanWriteFile( const char* FileNameToWrite ) - { - std::string filename(FileNameToWrite); +bool ONERAImageIO::CanWriteFile( const char* FileNameToWrite ) +{ + std::string filename(FileNameToWrite); - const std::string HeaderFileName = System::GetRootName(filename)+".ent"; - const std::string DataFileName = System::GetRootName(filename)+".dat"; + const std::string HeaderFileName = System::GetRootName(filename)+".ent"; + const std::string DataFileName = System::GetRootName(filename)+".dat"; - if( filename == HeaderFileName ) - { - return true; - } - else - { - return false; - } + if ( filename == HeaderFileName ) + { + return true; } - - void ONERAImageIO::Write(const void* buffer) + else { + return false; + } +} - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } +void ONERAImageIO::Write(const void* buffer) +{ - unsigned long step = this->GetNumberOfComponents(); + if ( m_FlagWriteImageInformation == true ) + { + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } + + unsigned long step = this->GetNumberOfComponents(); // variable not used. // const unsigned long numberOfComponents = this->GetImageSizeInComponents(); - unsigned int lNbLines = this->GetIORegion().GetSize()[1]; - unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + unsigned int lNbLines = this->GetIORegion().GetSize()[1]; + unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] - otbMsgDevMacro( <<" ONERAImageIO::Write() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" ONERAImageIO::Write() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); // Cas particuliers : on controle que si la r�gion � �crire est de la m�me dimension que l'image enti�re, // on commence l'offset � 0 (lorsque que l'on est pas en "Streaming") - if( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) - { - otbMsgDevMacro(<<"Force l'offset de l'IORegion a 0"); - lFirstLine = 0; - lFirstColumn = 0; - } - - std::streamsize numberOfBytesPerLines = step * lNbColumns * m_NbOctetPixel; - std::streamoff headerLength = ONERA_HEADER_LENGTH + numberOfBytesPerLines; - std::streamoff offset; - unsigned long numberOfBytesRegion = step * m_NbOctetPixel *lNbColumns *lNbLines; + if ( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) + { + otbMsgDevMacro(<<"Force l'offset de l'IORegion a 0"); + lFirstLine = 0; + lFirstColumn = 0; + } - char *tempmemory = new char[numberOfBytesRegion]; - memcpy(tempmemory,buffer,numberOfBytesRegion); + std::streamsize numberOfBytesPerLines = step * lNbColumns * m_NbOctetPixel; + std::streamoff headerLength = ONERA_HEADER_LENGTH + numberOfBytesPerLines; + std::streamoff offset; + unsigned long numberOfBytesRegion = step * m_NbOctetPixel *lNbColumns *lNbLines; - for(unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - char* value = tempmemory + numberOfBytesPerLines * (LineNo - lFirstLine); + char *tempmemory = new char[numberOfBytesRegion]; + memcpy(tempmemory,buffer,numberOfBytesRegion); - offset = headerLength + static_cast<std::streamoff>(numberOfBytesPerLines) * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); - m_Datafile.seekp(offset, std::ios::beg); - m_Datafile.write( static_cast<char *>( value ), numberOfBytesPerLines ); - } + for (unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + { + char* value = tempmemory + numberOfBytesPerLines * (LineNo - lFirstLine); - delete [] tempmemory; - tempmemory = NULL; + offset = headerLength + static_cast<std::streamoff>(numberOfBytesPerLines) * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); + m_Datafile.seekp(offset, std::ios::beg); + m_Datafile.write( static_cast<char *>( value ), numberOfBytesPerLines ); } - void ONERAImageIO::WriteImageInformation() - { + delete [] tempmemory; + tempmemory = NULL; +} - if ( ! this->OpenOneraHeaderFileForWriting(m_FileName.c_str()) ) - { - itkExceptionMacro(<< "Cannot read requested file"); - } +void ONERAImageIO::WriteImageInformation() +{ - if ( ! this->OpenOneraDataFileForWriting(m_FileName.c_str()) ) - { - itkExceptionMacro(<< "Cannot read requested file"); - } + if ( ! this->OpenOneraHeaderFileForWriting(m_FileName.c_str()) ) + { + itkExceptionMacro(<< "Cannot read requested file"); + } + + if ( ! this->OpenOneraDataFileForWriting(m_FileName.c_str()) ) + { + itkExceptionMacro(<< "Cannot read requested file"); + } - /*-------- This part deals with writing header information ------ */ - const std::string DataFileName = System::GetRootName( m_FileName.c_str() )+".dat"; + /*-------- This part deals with writing header information ------ */ + const std::string DataFileName = System::GetRootName( m_FileName.c_str() )+".dat"; - m_Headerfile << "# [fichier en-tete produit par les routines de otb (Orfeo ToolBox) ]" << std::endl; - m_Headerfile << "# Nom du look :"<< std::endl; - m_Headerfile << "Look.dat= \t" << DataFileName.c_str() << std::endl; - m_Headerfile << std::endl; - m_Headerfile << "# Structure du fichier et codage des pixels :"<< std::endl; - m_Headerfile << "# 4 octets precedent la premiere ligne : ils correspondent a un nombre magique [I4= 33554433] "<< std::endl; - m_Headerfile << "# [dans ordre LSBfirst = big-endian]" << std::endl; + m_Headerfile << "# [fichier en-tete produit par les routines de otb (Orfeo ToolBox) ]" << std::endl; + m_Headerfile << "# Nom du look :"<< std::endl; + m_Headerfile << "Look.dat= \t" << DataFileName.c_str() << std::endl; + m_Headerfile << std::endl; + m_Headerfile << "# Structure du fichier et codage des pixels :"<< std::endl; + m_Headerfile << "# 4 octets precedent la premiere ligne : ils correspondent a un nombre magique [I4= 33554433] "<< std::endl; + m_Headerfile << "# [dans ordre LSBfirst = big-endian]" << std::endl; - std::string sPixelType("cmplx_real_4"); - if( (m_PixelType == COMPLEX) && (m_ComponentType == FLOAT) ) - { - sPixelType = "cmplx_real_4"; - } - else - { - itkExceptionMacro(<< "data format not supported by OTB (only 'complex_real_4' is available)"); - } + std::string sPixelType("cmplx_real_4"); + if ( (m_PixelType == COMPLEX) && (m_ComponentType == FLOAT) ) + { + sPixelType = "cmplx_real_4"; + } + else + { + itkExceptionMacro(<< "data format not supported by OTB (only 'complex_real_4' is available)"); + } - m_Headerfile << "Format_valeurs_look= \t"<< sPixelType << std::endl; - m_Headerfile << "Nb_case_par_ligne_look= \t"<< m_Dimensions[0] <<std::endl; - m_Headerfile << "Nb_ligne_look= \t"<< m_Dimensions[1] <<" + 1 ligne en-tete en binaire (entiers 16 bit) " << std::endl; + m_Headerfile << "Format_valeurs_look= \t"<< sPixelType << std::endl; + m_Headerfile << "Nb_case_par_ligne_look= \t"<< m_Dimensions[0] <<std::endl; + m_Headerfile << "Nb_ligne_look= \t"<< m_Dimensions[1] <<" + 1 ligne en-tete en binaire (entiers 16 bit) " << std::endl; // write magic_number - int magicNumber = ONERA_MAGIC_NUMBER; - short NbCol = static_cast<short>(m_Dimensions[0]); - short NbRow = static_cast<short>(m_Dimensions[1]); - int ByteSizeCol = NbCol*4*2; + int magicNumber = ONERA_MAGIC_NUMBER; + short NbCol = static_cast<short>(m_Dimensions[0]); + short NbRow = static_cast<short>(m_Dimensions[1]); + int ByteSizeCol = NbCol*4*2; // itk::ByteSwapper< int>::SwapFromSystemToLittleEndian(&magicNumber); - m_Datafile.seekp(0, std::ios::beg ); - m_Datafile.write((char*)(&magicNumber),4); + m_Datafile.seekp(0, std::ios::beg ); + m_Datafile.write((char*)(&magicNumber),4); - char * tab = new char[ByteSizeCol]; - for( int i = 0; i < (NbRow + 1); i++) - { - m_Datafile.write((char*)(tab),ByteSizeCol); - } - delete [] tab; + char * tab = new char[ByteSizeCol]; + for ( int i = 0; i < (NbRow + 1); i++) + { + m_Datafile.write((char*)(tab),ByteSizeCol); + } + delete [] tab; // write number of columns // itk::ByteSwapper<short>::SwapFromSystemToLittleEndian(&NbCol); - m_Datafile.seekp(ONERA_HEADER_LENGTH+2, std::ios::beg ); - m_Datafile.write((char*)(&NbCol),2); + m_Datafile.seekp(ONERA_HEADER_LENGTH+2, std::ios::beg ); + m_Datafile.write((char*)(&NbCol),2); - otbMsgDebugMacro( <<"Driver to write: ONERA"); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" NbOctetPixel : "<<m_NbOctetPixel); - otbMsgDebugMacro( <<" Host byte order : "<<this->GetByteOrderAsString(m_ByteOrder)); + otbMsgDebugMacro( <<"Driver to write: ONERA"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" NbOctetPixel : "<<m_NbOctetPixel); + otbMsgDebugMacro( <<" Host byte order : "<<this->GetByteOrderAsString(m_ByteOrder)); - } +} } // end namespace otb diff --git a/Code/IO/otbONERAImageIO.h b/Code/IO/otbONERAImageIO.h index 6af18fdf648bfae80c668382d12954171cfe375f..36f503bf217d1c3b82ad048a617e7499679cb3d4 100644 --- a/Code/IO/otbONERAImageIO.h +++ b/Code/IO/otbONERAImageIO.h @@ -60,7 +60,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -78,7 +81,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ diff --git a/Code/IO/otbPointSetFileReader.h b/Code/IO/otbPointSetFileReader.h index 6b40ba8f7e42ad0edc7597204bfe428089834d4b..b3cb6344fdb6b1d6a4caf79baae17a35da208e38 100644 --- a/Code/IO/otbPointSetFileReader.h +++ b/Code/IO/otbPointSetFileReader.h @@ -24,74 +24,74 @@ namespace otb { - /** \class PointSetFileReader - * \brief Read a point set from a lidar file. - * - * \sa PointSetSource - * - * \ingroup IOFilters - * - */ +/** \class PointSetFileReader + * \brief Read a point set from a lidar file. + * + * \sa PointSetSource + * + * \ingroup IOFilters + * + */ template<class TOutputPointSet> - class ITK_EXPORT PointSetFileReader: public otb::PointSetSource< TOutputPointSet > +class ITK_EXPORT PointSetFileReader: public otb::PointSetSource< TOutputPointSet > { - public: - /** Standard class typedefs. */ - typedef PointSetFileReader Self; - typedef otb::PointSetSource<TOutputPointSet> Superclass; - typedef itk::SmartPointer<Self> Pointer; +public: + /** Standard class typedefs. */ + typedef PointSetFileReader Self; + typedef otb::PointSetSource<TOutputPointSet> Superclass; + typedef itk::SmartPointer<Self> Pointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(PointSetFileReader, PointSetSource); + /** Run-time type information (and related methods). */ + itkTypeMacro(PointSetFileReader, PointSetSource); - /** Typedef */ - typedef TOutputPointSet PointSetType; - typedef typename PointSetType::PointType PointType; - typedef typename PointSetType::PixelType PixelType; + /** Typedef */ + typedef TOutputPointSet PointSetType; + typedef typename PointSetType::PointType PointType; + typedef typename PointSetType::PixelType PixelType; - /** Specify the file to read. This is forwarded to the IO instance. */ - itkSetStringMacro(FileName); - itkGetStringMacro(FileName); + /** Specify the file to read. This is forwarded to the IO instance. */ + itkSetStringMacro(FileName); + itkGetStringMacro(FileName); - /** Get Macro*/ - itkGetMacro( NumberOfPoints, long int ); - itkGetMacro( MinX, double ); - itkGetMacro( MaxX, double ); - itkGetMacro( MinY, double ); - itkGetMacro( MaxY, double ); + /** Get Macro*/ + itkGetMacro( NumberOfPoints, long int ); + itkGetMacro( MinX, double ); + itkGetMacro( MaxX, double ); + itkGetMacro( MinY, double ); + itkGetMacro( MaxY, double ); - virtual void GenerateOutputInformation(void); + virtual void GenerateOutputInformation(void); - /** Does the real work. */ - virtual void GenerateData(); + /** Does the real work. */ + virtual void GenerateData(); - protected: - PointSetFileReader(); - ~PointSetFileReader(); - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + PointSetFileReader(); + ~PointSetFileReader(); + void PrintSelf(std::ostream& os, itk::Indent indent) const; - void TestFileExistanceAndReadability(); + void TestFileExistanceAndReadability(); - std::string m_FileName; // The file to be read - long int m_NumberOfPoints; - double m_MinX; - double m_MaxX; - double m_MinY; - double m_MaxY; + std::string m_FileName; // The file to be read + long int m_NumberOfPoints; + double m_MinX; + double m_MaxX; + double m_MinY; + double m_MaxY; - private: - PointSetFileReader(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + PointSetFileReader(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - std::string m_ExceptionMessage; + std::string m_ExceptionMessage; }; diff --git a/Code/IO/otbPointSetFileReader.txx b/Code/IO/otbPointSetFileReader.txx index 563ac82694503978edb108bfb3aa40b68c87620d..badea44c1aedab72e966a77827c56e8fba931a47 100644 --- a/Code/IO/otbPointSetFileReader.txx +++ b/Code/IO/otbPointSetFileReader.txx @@ -29,167 +29,167 @@ namespace otb { - template <class TOutputPointSet> - PointSetFileReader<TOutputPointSet> - ::PointSetFileReader() : otb::PointSetSource<TOutputPointSet>() - { - m_NumberOfPoints=-1; - m_MinX=0; - m_MaxX=0; - m_MinY=0; - m_MaxY=0; - } +template <class TOutputPointSet> +PointSetFileReader<TOutputPointSet> +::PointSetFileReader() : otb::PointSetSource<TOutputPointSet>() +{ + m_NumberOfPoints=-1; + m_MinX=0; + m_MaxX=0; + m_MinY=0; + m_MaxY=0; +} + +template <class TOutputPointSet> +PointSetFileReader<TOutputPointSet> +::~PointSetFileReader() +{ +} + + + +template <class TOutputPointSet> +void +PointSetFileReader<TOutputPointSet> +::GenerateOutputInformation(void) +{ + typename TOutputPointSet::Pointer output = this->GetOutput(); - template <class TOutputPointSet> - PointSetFileReader<TOutputPointSet> - ::~PointSetFileReader() + otbDebugMacro(<<"Reading file for GenerateOutputInformation()" << m_FileName); + + // Check to see if we can read the file given the name or prefix + // + if ( m_FileName == "" ) { + throw itk::ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } - template <class TOutputPointSet> - void - PointSetFileReader<TOutputPointSet> - ::GenerateOutputInformation(void) + // Test if the file exists and if it can be open. + // An exception will be thrown otherwise. + // + try + { + m_ExceptionMessage = ""; + this->TestFileExistanceAndReadability(); + } + catch (itk::ExceptionObject &err) { - typename TOutputPointSet::Pointer output = this->GetOutput(); + m_ExceptionMessage = err.GetDescription(); + } - otbDebugMacro(<<"Reading file for GenerateOutputInformation()" << m_FileName); + std::ifstream ifs; + ifs.open(m_FileName.c_str(), std::ios::in | std::ios::binary); + liblas::LASReader reader(ifs); - // Check to see if we can read the file given the name or prefix - // - if ( m_FileName == "" ) - { - throw itk::ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); - } - - - - // Test if the file exists and if it can be open. - // An exception will be thrown otherwise. - // - try - { - m_ExceptionMessage = ""; - this->TestFileExistanceAndReadability(); - } - catch(itk::ExceptionObject &err) - { - m_ExceptionMessage = err.GetDescription(); - } - - std::ifstream ifs; - ifs.open(m_FileName.c_str(), std::ios::in | std::ios::binary); - liblas::LASReader reader(ifs); - - liblas::LASHeader const& header = reader.GetHeader(); - - otbDebugMacro(<< "Signature: " << header.GetFileSignature()); - otbDebugMacro(<< "Points count: " << header.GetPointRecordsCount()); - - m_NumberOfPoints = header.GetPointRecordsCount(); - m_MinX = header.GetMinX(); - m_MaxX = header.GetMaxX(); - m_MinY = header.GetMinY(); - m_MaxY = header.GetMaxY(); - ifs.close(); + liblas::LASHeader const& header = reader.GetHeader(); - } + otbDebugMacro(<< "Signature: " << header.GetFileSignature()); + otbDebugMacro(<< "Points count: " << header.GetPointRecordsCount()); + m_NumberOfPoints = header.GetPointRecordsCount(); + m_MinX = header.GetMinX(); + m_MaxX = header.GetMaxX(); + m_MinY = header.GetMinY(); + m_MaxY = header.GetMaxY(); + ifs.close(); - template <class TOutputPointSet> - void - PointSetFileReader<TOutputPointSet> - ::TestFileExistanceAndReadability() - { +} + + +template <class TOutputPointSet> +void +PointSetFileReader<TOutputPointSet> +::TestFileExistanceAndReadability() +{ // Test if the file exists. - if( ! itksys::SystemTools::FileExists( m_FileName.c_str() ) ) - { - itk::ImageFileReaderException e(__FILE__, __LINE__); - itk::OStringStream msg; - msg <<"The file doesn't exist. " - << std::endl << "Filename = " << m_FileName - << std::endl; - e.SetDescription(msg.str().c_str()); - throw e; - return; - } + if ( ! itksys::SystemTools::FileExists( m_FileName.c_str() ) ) + { + itk::ImageFileReaderException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg <<"The file doesn't exist. " + << std::endl << "Filename = " << m_FileName + << std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; + } // Test if the file can be open for reading access. - std::ifstream readTester; - readTester.open( m_FileName.c_str() ); - if( readTester.fail() ) - { - readTester.close(); - itk::OStringStream msg; - msg <<"The file couldn't be opened for reading. " - << std::endl << "Filename: " << m_FileName - << std::endl; - itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); - throw e; - return; - - } + std::ifstream readTester; + readTester.open( m_FileName.c_str() ); + if ( readTester.fail() ) + { readTester.close(); + itk::OStringStream msg; + msg <<"The file couldn't be opened for reading. " + << std::endl << "Filename: " << m_FileName + << std::endl; + itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); + throw e; + return; + } + readTester.close(); +} - template <class TOutputPointSet> - void PointSetFileReader<TOutputPointSet> - ::GenerateData() - { +template <class TOutputPointSet> +void PointSetFileReader<TOutputPointSet> +::GenerateData() +{ - typename TOutputPointSet::Pointer output = this->GetOutput(); + typename TOutputPointSet::Pointer output = this->GetOutput(); - std::ifstream ifs; - ifs.open(m_FileName.c_str(), std::ios::in | std::ios::binary); - liblas::LASReader reader(ifs); + std::ifstream ifs; + ifs.open(m_FileName.c_str(), std::ios::in | std::ios::binary); + liblas::LASReader reader(ifs); - liblas::LASHeader const& header = reader.GetHeader(); + liblas::LASHeader const& header = reader.GetHeader(); - otbDebugMacro(<< "Signature: " << header.GetFileSignature()); - otbDebugMacro(<< "Points count: " << header.GetPointRecordsCount()); + otbDebugMacro(<< "Signature: " << header.GetFileSignature()); + otbDebugMacro(<< "Points count: " << header.GetPointRecordsCount()); - m_NumberOfPoints = header.GetPointRecordsCount(); + m_NumberOfPoints = header.GetPointRecordsCount(); - while (reader.ReadNextPoint()) - { - liblas::LASPoint const& p = reader.GetPoint(); + while (reader.ReadNextPoint()) + { + liblas::LASPoint const& p = reader.GetPoint(); - PointType point; - point[0] = p.GetX(); - point[1] = p.GetY(); + PointType point; + point[0] = p.GetX(); + point[1] = p.GetY(); - unsigned long i = output->GetNumberOfPoints(); - output->SetPoint( i, point ); + unsigned long i = output->GetNumberOfPoints(); + output->SetPoint( i, point ); - PixelType V; - V = static_cast<PixelType>( p.GetZ() ); - output->SetPointData( i, V ); + PixelType V; + V = static_cast<PixelType>( p.GetZ() ); + output->SetPointData( i, V ); - } + } - ifs.close(); - } + ifs.close(); +} - template <class TOutputPointSet> - void PointSetFileReader<TOutputPointSet> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "Number of points: " << this->m_NumberOfPoints << std::endl; - os << indent << std::setprecision(15); - os << indent << "Min X: " << this->m_MinX << std::endl; - os << indent << "Max X: " << this->m_MaxX << std::endl; - os << indent << "Min Y: " << this->m_MinY << std::endl; - os << indent << "Max Y: " << this->m_MaxY << std::endl; - os << indent << "m_FileName: " << this->m_FileName << "\n"; - } +template <class TOutputPointSet> +void PointSetFileReader<TOutputPointSet> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Number of points: " << this->m_NumberOfPoints << std::endl; + os << indent << std::setprecision(15); + os << indent << "Min X: " << this->m_MinX << std::endl; + os << indent << "Max X: " << this->m_MaxX << std::endl; + os << indent << "Min Y: " << this->m_MinY << std::endl; + os << indent << "Max Y: " << this->m_MaxY << std::endl; + os << indent << "m_FileName: " << this->m_FileName << "\n"; +} } //namespace otb diff --git a/Code/IO/otbPrepareSRTMDirectory.h b/Code/IO/otbPrepareSRTMDirectory.h index 54b9119b49b4a2a38e733ff5128cef758e7043d3..3888d1a95f70d3c2071d0ed2209f79f63691c1c2 100644 --- a/Code/IO/otbPrepareSRTMDirectory.h +++ b/Code/IO/otbPrepareSRTMDirectory.h @@ -39,54 +39,54 @@ namespace otb */ - class ITK_EXPORT PrepareSRTMDirectory : public itk::Object - { - public: - /** Standard class typedefs. */ - typedef PrepareSRTMDirectory Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - - typedef itk::Object Superclass; - - itkTypeMacro(PrepareSRTMDirectory, Object); - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - itkGetMacro( ULLon, double ); - itkGetMacro( ULLat, double ); - itkGetMacro( LRLon, double ); - itkGetMacro( LRLat, double ); - itkGetMacro( FullDEMDirectoryPath, string ); - itkGetMacro( DEMDirectoryPath, string ); - - itkSetMacro( ULLon, double ); - itkSetMacro( ULLat, double ); - itkSetMacro( LRLon, double ); - itkSetMacro( LRLat, double ); - itkSetMacro( FullDEMDirectoryPath, string ); - itkSetMacro( DEMDirectoryPath, string ); - - - virtual bool Evaluate(); - - protected: - PrepareSRTMDirectory(); - ~PrepareSRTMDirectory(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - PrepareSRTMDirectory( const Self& ); //purposely not implemented - void operator=( const Self& ); //purposely not implemented - - double m_ULLon; - double m_ULLat; - double m_LRLon; - double m_LRLat; - string m_FullDEMDirectoryPath; - string m_DEMDirectoryPath; - }; +class ITK_EXPORT PrepareSRTMDirectory : public itk::Object +{ +public: + /** Standard class typedefs. */ + typedef PrepareSRTMDirectory Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + + typedef itk::Object Superclass; + + itkTypeMacro(PrepareSRTMDirectory, Object); + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + itkGetMacro( ULLon, double ); + itkGetMacro( ULLat, double ); + itkGetMacro( LRLon, double ); + itkGetMacro( LRLat, double ); + itkGetMacro( FullDEMDirectoryPath, string ); + itkGetMacro( DEMDirectoryPath, string ); + + itkSetMacro( ULLon, double ); + itkSetMacro( ULLat, double ); + itkSetMacro( LRLon, double ); + itkSetMacro( LRLat, double ); + itkSetMacro( FullDEMDirectoryPath, string ); + itkSetMacro( DEMDirectoryPath, string ); + + + virtual bool Evaluate(); + +protected: + PrepareSRTMDirectory(); + ~PrepareSRTMDirectory() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + PrepareSRTMDirectory( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + double m_ULLon; + double m_ULLat; + double m_LRLon; + double m_LRLat; + string m_FullDEMDirectoryPath; + string m_DEMDirectoryPath; +}; } // namespace otb diff --git a/Code/IO/otbPrepareSRTMDirectory.txx b/Code/IO/otbPrepareSRTMDirectory.txx index a9ec39a422ac178317a8d5f13c8ea04bf0500a5d..fa04b7d1ae0828804e6956d42e387acaa92433d5 100644 --- a/Code/IO/otbPrepareSRTMDirectory.txx +++ b/Code/IO/otbPrepareSRTMDirectory.txx @@ -28,105 +28,105 @@ namespace otb * Constructor */ - PrepareSRTMDirectory::PrepareSRTMDirectory() - { - m_ULLon = 0.0; - m_ULLat = 0.0; - m_LRLon = 0.0; - m_LRLat = 0.0; - m_FullDEMDirectoryPath = ""; - m_DEMDirectoryPath = ""; - } +PrepareSRTMDirectory::PrepareSRTMDirectory() +{ + m_ULLon = 0.0; + m_ULLat = 0.0; + m_LRLon = 0.0; + m_LRLat = 0.0; + m_FullDEMDirectoryPath = ""; + m_DEMDirectoryPath = ""; +} /** * */ - void - PrepareSRTMDirectory - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - this->Superclass::PrintSelf(os,indent); - os << indent << " m_ULLon " << m_ULLon << std::endl; - os << indent << " m_ULLat " << m_ULLat << std::endl; - os << indent << " m_LRLon " << m_LRLon << std::endl; - os << indent << " m_LRLat " << m_LRLat << std::endl; - os << indent << " m_FullDEMDirectoryPath" << m_FullDEMDirectoryPath << std::endl; - os << indent << " m_DEMDirectoryPath" << m_DEMDirectoryPath << std::endl; - } +void +PrepareSRTMDirectory +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + this->Superclass::PrintSelf(os,indent); + os << indent << " m_ULLon " << m_ULLon << std::endl; + os << indent << " m_ULLat " << m_ULLat << std::endl; + os << indent << " m_LRLon " << m_LRLon << std::endl; + os << indent << " m_LRLat " << m_LRLat << std::endl; + os << indent << " m_FullDEMDirectoryPath" << m_FullDEMDirectoryPath << std::endl; + os << indent << " m_DEMDirectoryPath" << m_DEMDirectoryPath << std::endl; +} - bool PrepareSRTMDirectory::Evaluate() - { +bool PrepareSRTMDirectory::Evaluate() +{ - int startX = floor(m_ULLon); - int endX = ceil(m_LRLon); - int startY = floor(m_LRLat); - int endY = ceil(m_ULLat); + int startX = floor(m_ULLon); + int endX = ceil(m_LRLon); + int startY = floor(m_LRLat); + int endY = ceil(m_ULLat); - std::cout << startX << std::endl; - std::cout << endX << std::endl; - std::cout << startY << std::endl; - std::cout << endY << std::endl; + std::cout << startX << std::endl; + std::cout << endX << std::endl; + std::cout << startY << std::endl; + std::cout << endY << std::endl; - for (int j=startY; j<endY; j++) + for (int j=startY; j<endY; j++) + { + for (int i=startX; i< endX; i++) { - for (int i=startX; i< endX; i++) - { - std::ostringstream inputfilename; - inputfilename << m_FullDEMDirectoryPath; - inputfilename << "/"; - - std::ostringstream outputfilename; - outputfilename << m_DEMDirectoryPath; - outputfilename << "/"; - - if (j >= 0) - { - inputfilename << "N"; - inputfilename << setfill('0') << setw(2) << j; - outputfilename << "N"; - outputfilename << setfill('0') << setw(2) << j; - } - else - { - inputfilename << "S"; - inputfilename << setfill('0') << setw(2) << -j; - outputfilename << "S"; - outputfilename << setfill('0') << setw(2) << -j; - } - if (i >= 0) - { - inputfilename << "E"; - inputfilename << setfill('0') << setw(3) << i; - outputfilename << "E"; - outputfilename << setfill('0') << setw(3) << i; - } - else - { - inputfilename << "W"; - inputfilename << setfill('0') << setw(3) << -i; - outputfilename << "W"; - outputfilename << setfill('0') << setw(3) << -i; - } - - inputfilename << ".hgt"; - outputfilename << ".hgt"; - - std::cout << "Copying " << inputfilename.str() << " to " << outputfilename.str() << std::endl; - - //copy input file to output file - ossimFilename inputFile(inputfilename.str().c_str()); - ossimFilename outputFile(outputfilename.str().c_str()); - inputFile.copyFileTo(outputFile); + std::ostringstream inputfilename; + inputfilename << m_FullDEMDirectoryPath; + inputfilename << "/"; + std::ostringstream outputfilename; + outputfilename << m_DEMDirectoryPath; + outputfilename << "/"; + if (j >= 0) + { + inputfilename << "N"; + inputfilename << setfill('0') << setw(2) << j; + outputfilename << "N"; + outputfilename << setfill('0') << setw(2) << j; + } + else + { + inputfilename << "S"; + inputfilename << setfill('0') << setw(2) << -j; + outputfilename << "S"; + outputfilename << setfill('0') << setw(2) << -j; + } + if (i >= 0) + { + inputfilename << "E"; + inputfilename << setfill('0') << setw(3) << i; + outputfilename << "E"; + outputfilename << setfill('0') << setw(3) << i; + } + else + { + inputfilename << "W"; + inputfilename << setfill('0') << setw(3) << -i; + outputfilename << "W"; + outputfilename << setfill('0') << setw(3) << -i; } - } - return true; + inputfilename << ".hgt"; + outputfilename << ".hgt"; + + std::cout << "Copying " << inputfilename.str() << " to " << outputfilename.str() << std::endl; + + //copy input file to output file + ossimFilename inputFile(inputfilename.str().c_str()); + ossimFilename outputFile(outputfilename.str().c_str()); + inputFile.copyFileTo(outputFile); + + + } } + return true; +} + } // namespace otb #endif diff --git a/Code/IO/otbRADImageIO.cxx b/Code/IO/otbRADImageIO.cxx index 18ec905162bb564d8a6db2083903e4c651601e71..647f1a898671982531d7e0beb63565e5f074ee4d 100644 --- a/Code/IO/otbRADImageIO.cxx +++ b/Code/IO/otbRADImageIO.cxx @@ -33,752 +33,753 @@ namespace otb { - RADImageIO::RADImageIO() - { +RADImageIO::RADImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); // By default the type to CI2 - m_TypeRAD= "CR4"; - m_NbOctetPixel=8; - m_NbOfChannels=1; - this->SetNumberOfComponents(2); - m_PixelType = COMPLEX; - m_ComponentType = FLOAT; + m_TypeRAD= "CR4"; + m_NbOctetPixel=8; + m_NbOfChannels=1; + this->SetNumberOfComponents(2); + m_PixelType = COMPLEX; + m_ComponentType = FLOAT; - if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) - { - m_ByteOrder = LittleEndian; - } - else - { - m_ByteOrder = BigEndian; - } + if ( itk::ByteSwapper<char>::SystemIsLittleEndian() == true) + { + m_ByteOrder = LittleEndian; + } + else + { + m_ByteOrder = BigEndian; + } - m_FileByteOrder = m_ByteOrder; + m_FileByteOrder = m_ByteOrder; // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; - m_ChannelsFile = NULL; - m_FlagWriteImageInformation = true; - } + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; + m_ChannelsFile = NULL; + m_FlagWriteImageInformation = true; +} - RADImageIO::~RADImageIO() - { +RADImageIO::~RADImageIO() +{ - if( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } - if( m_ChannelsFile != NULL) + if ( m_HeaderFile.is_open() ) + { + m_HeaderFile.close(); + } + if ( m_ChannelsFile != NULL) + { + for (unsigned int numChannel = 0; numChannel< m_NbOfChannels; numChannel++) { - for(unsigned int numChannel = 0; numChannel< m_NbOfChannels; numChannel++) + if ( m_ChannelsFile[numChannel].is_open() ) { - if( m_ChannelsFile[numChannel].is_open() ) - { - m_ChannelsFile[numChannel].close(); - } + m_ChannelsFile[numChannel].close(); } - delete [] m_ChannelsFile; } + delete [] m_ChannelsFile; } +} - bool RADImageIO::CanReadFile( const char* filename ) +bool RADImageIO::CanReadFile( const char* filename ) +{ + std::fstream header_file; + std::string lFileName(filename); + if ( System::IsADirName(lFileName) == true ) { - std::fstream header_file; - std::string lFileName(filename); - if( System::IsADirName(lFileName) == true ) - { - return false; - } - if( System::SetToLower(System::GetExtension(lFileName)) != "rad" ) - { - return false; - } - - header_file.open( lFileName.c_str(), std::ios::in ); - if( header_file.fail() ) - { - otbMsgDevMacro(<<"RADImageIO::CanReadFile() failed header open ! " ); - return false; - } + return false; + } + if ( System::SetToLower(System::GetExtension(lFileName)) != "rad" ) + { + return false; + } - //Read header informations - bool lResult = InternalReadHeaderInformation(lFileName, header_file,false); - header_file.close(); - return (lResult); + header_file.open( lFileName.c_str(), std::ios::in ); + if ( header_file.fail() ) + { + otbMsgDevMacro(<<"RADImageIO::CanReadFile() failed header open ! " ); + return false; } + //Read header informations + bool lResult = InternalReadHeaderInformation(lFileName, header_file,false); + header_file.close(); + return (lResult); +} + // Used to print information about this object - void RADImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } +void RADImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} // Read a 3D image (or event more bands)... not implemented yet - void RADImageIO::ReadVolume(void*) - { - } +void RADImageIO::ReadVolume(void*) +{ +} // Read image - void RADImageIO::Read(void* buffer) - { - unsigned long step = this->GetNumberOfComponents(); - char * p = static_cast<char *>(buffer); - - int lNbLines = this->GetIORegion().GetSize()[1]; - int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] - - otbMsgDevMacro( <<" RADImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - otbMsgDevMacro( <<" Size Of Components : "<<this->GetComponentSize()); - otbMsgDevMacro( <<" Nb Of Channels : "<<m_NbOfChannels); - - std::streamoff headerLength(0); - std::streamoff offset; - std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>( m_NbOctetPixel * m_Dimensions[0]); - std::streamsize numberOfBytesToBeRead = m_NbOctetPixel * lNbColumns; - std::streamsize numberOfBytesRead; - unsigned long cpt = 0; - - // Update the step variable - step = step * (unsigned long)(this->GetComponentSize()); - - char * value = new char[numberOfBytesToBeRead]; - if(value==NULL) - { - itkExceptionMacro(<<"RADImageIO::Read(): Bad alloc"); - return; - } +void RADImageIO::Read(void* buffer) +{ + unsigned long step = this->GetNumberOfComponents(); + char * p = static_cast<char *>(buffer); + + int lNbLines = this->GetIORegion().GetSize()[1]; + int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + + otbMsgDevMacro( <<" RADImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" Size Of Components : "<<this->GetComponentSize()); + otbMsgDevMacro( <<" Nb Of Channels : "<<m_NbOfChannels); + + std::streamoff headerLength(0); + std::streamoff offset; + std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>( m_NbOctetPixel * m_Dimensions[0]); + std::streamsize numberOfBytesToBeRead = m_NbOctetPixel * lNbColumns; + std::streamsize numberOfBytesRead; + unsigned long cpt = 0; + + // Update the step variable + step = step * (unsigned long)(this->GetComponentSize()); + + char * value = new char[numberOfBytesToBeRead]; + if (value==NULL) + { + itkExceptionMacro(<<"RADImageIO::Read(): Bad alloc"); + return; + } - otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); - otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); - otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); - otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); - otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); - otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); + otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); + otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); + otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); + otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); + otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); + otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); - for (unsigned int numChannel = 0; numChannel < m_NbOfChannels; numChannel++) + for (unsigned int numChannel = 0; numChannel < m_NbOfChannels; numChannel++) + { + cpt = (unsigned long )(numChannel)* (unsigned long)(m_NbOctetPixel); + //Read region of the channel + for (int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) { - cpt = (unsigned long )(numChannel)* (unsigned long)(m_NbOctetPixel); - //Read region of the channel - for(int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) - { - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>( m_NbOctetPixel * lFirstColumn); - m_ChannelsFile[numChannel].seekg(offset, std::ios::beg); - //Read a line - m_ChannelsFile[numChannel].read( static_cast<char *>( value ), numberOfBytesToBeRead ); + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>( m_NbOctetPixel * lFirstColumn); + m_ChannelsFile[numChannel].seekg(offset, std::ios::beg); + //Read a line + m_ChannelsFile[numChannel].read( static_cast<char *>( value ), numberOfBytesToBeRead ); - numberOfBytesRead = m_ChannelsFile[numChannel].gcount(); + numberOfBytesRead = m_ChannelsFile[numChannel].gcount(); #ifdef __APPLE_CC__ - // fail() is broken in the Mac. It returns true when reaches eof(). - if ( numberOfBytesRead != numberOfBytesToBeRead ) + // fail() is broken in the Mac. It returns true when reaches eof(). + if ( numberOfBytesRead != numberOfBytesToBeRead ) #else - if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_ChannelsFile[numChannel].fail() ) + if ( ( numberOfBytesRead != numberOfBytesToBeRead ) || m_ChannelsFile[numChannel].fail() ) #endif - { - itkExceptionMacro(<<"RADImageIO::Read() Can Read the specified Region"); // read failed - } - for ( std::streamsize i=0; i < numberOfBytesToBeRead; i = i+static_cast<std::streamsize>(m_NbOctetPixel) ) - { - memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(m_NbOctetPixel)); - cpt += step; - } + { + itkExceptionMacro(<<"RADImageIO::Read() Can Read the specified Region"); // read failed + } + for ( std::streamsize i=0; i < numberOfBytesToBeRead; i = i+static_cast<std::streamsize>(m_NbOctetPixel) ) + { + memcpy((void*)(&(p[cpt])),(const void*)(&(value[i])),(size_t)(m_NbOctetPixel)); + cpt += step; } } - unsigned long numberOfPixelsOfRegion = lNbLines * lNbColumns * this->GetNumberOfComponents(); - - - // Swap bytes if necessary - if ( 0 ) {} - otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsOfRegion ) - otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsOfRegion ) - else - { - itkExceptionMacro(<<"RADImageIO::Read() undefined component type! " ); - } + } + unsigned long numberOfPixelsOfRegion = lNbLines * lNbColumns * this->GetNumberOfComponents(); + + + // Swap bytes if necessary + if ( 0 ) {} + otbSwappFileToSystemMacro( unsigned short, USHORT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( short, SHORT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( char, CHAR, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned char, UCHAR, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned int, UINT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( int, INT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( long, LONG, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( unsigned long, ULONG, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( float, FLOAT, buffer, numberOfPixelsOfRegion ) + otbSwappFileToSystemMacro( double, DOUBLE, buffer, numberOfPixelsOfRegion ) + else + { + itkExceptionMacro(<<"RADImageIO::Read() undefined component type! " ); + } - delete [] value; - value = NULL; + delete [] value; + value = NULL; - } +} - void RADImageIO::ReadImageInformation() +void RADImageIO::ReadImageInformation() +{ + if ( m_HeaderFile.is_open() ) { - if( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } - m_HeaderFile.open( m_FileName.c_str(), std::ios::in ); - if( m_HeaderFile.fail() ) - { - itkExceptionMacro(<<"RADImageIO::ReadImageInformation() failed header open ! " ); - } + m_HeaderFile.close(); + } + m_HeaderFile.open( m_FileName.c_str(), std::ios::in ); + if ( m_HeaderFile.fail() ) + { + itkExceptionMacro(<<"RADImageIO::ReadImageInformation() failed header open ! " ); + } - //Read header informations - InternalReadHeaderInformation(m_FileName, m_HeaderFile,true); + //Read header informations + InternalReadHeaderInformation(m_FileName, m_HeaderFile,true); - otbMsgDebugMacro( <<"Driver to read: RAD"); - otbMsgDebugMacro( <<" Read file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to read: RAD"); + otbMsgDebugMacro( <<" Read file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} - bool RADImageIO::InternalReadHeaderInformation(const std::string & file_name, std::fstream & file, const bool reportError) - { +bool RADImageIO::InternalReadHeaderInformation(const std::string & file_name, std::fstream & file, const bool reportError) +{ - std::string lString; - std::string lStrCodePix; + std::string lString; + std::string lStrCodePix; - // Read NBCOLONNES information - file >> lString; - lString = System::SetToUpper(lString); - if( (lString != "NBCOLONNES") && (lString != "NBCOLUMNS")) + // Read NBCOLONNES information + file >> lString; + lString = System::SetToUpper(lString); + if ( (lString != "NBCOLONNES") && (lString != "NBCOLUMNS")) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : 'NBCOLONNES' keyword is not find in the header file."); - } - else - { - return false; - } + itkExceptionMacro(<< "RAD : 'NBCOLONNES' keyword is not find in the header file."); } - file >> m_Dimensions[0]; - - // Read NBLIGNES information - file >> lString; - lString = System::SetToUpper(lString); - if( (lString != "NBLIGNES") && (lString != "NBLINES") ) + else { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : 'NBLIGNES' keyword is not find in the header file."); - } - else - { - return false; - } + return false; } - file >> m_Dimensions[1]; + } + file >> m_Dimensions[0]; - // Read NBPLANS information - file >> lString; - lString = System::SetToUpper(lString); - if( (lString != "NBPLANS") && (lString != "NBBANDS") ) + // Read NBLIGNES information + file >> lString; + lString = System::SetToUpper(lString); + if ( (lString != "NBLIGNES") && (lString != "NBLINES") ) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : 'NBPLANS' keyword is not find in the header file."); - } - else - { - return false; - } + itkExceptionMacro(<< "RAD : 'NBLIGNES' keyword is not find in the header file."); } - file >> m_NbOfChannels; - // Because we read complex : *2 - this->SetNumberOfComponents(2*m_NbOfChannels); - - // Read TYPECODAGE information - file >> lString; - lString = System::SetToUpper(lString); - if( (lString != "TYPECODAGE") && (lString != "TYPE") ) + else { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : the first line of the header file must be contains 'TYPECODAGE' caracters."); - } - else - { - return false; - } + return false; } - file >> lStrCodePix; - + } + file >> m_Dimensions[1]; - lStrCodePix = System::SetToUpper(lStrCodePix); - if(lStrCodePix == "OCT") - { - m_PixelType = SCALAR; - SetComponentType(UCHAR); - m_NbOctetPixel=1; - } - if(lStrCodePix == "PHA") + // Read NBPLANS information + file >> lString; + lString = System::SetToUpper(lString); + if ( (lString != "NBPLANS") && (lString != "NBBANDS") ) + { + if ( reportError == true ) { - m_PixelType = SCALAR; - SetComponentType(CHAR); - m_NbOctetPixel=1; + itkExceptionMacro(<< "RAD : 'NBPLANS' keyword is not find in the header file."); } - if(lStrCodePix == "I2") + else { - m_PixelType = SCALAR; - SetComponentType(SHORT); - m_NbOctetPixel=2; + return false; } - if(lStrCodePix == "I4") + } + file >> m_NbOfChannels; + // Because we read complex : *2 + this->SetNumberOfComponents(2*m_NbOfChannels); + + // Read TYPECODAGE information + file >> lString; + lString = System::SetToUpper(lString); + if ( (lString != "TYPECODAGE") && (lString != "TYPE") ) + { + if ( reportError == true ) { - m_PixelType = SCALAR; - SetComponentType(INT); - m_NbOctetPixel=4; + itkExceptionMacro(<< "RAD : the first line of the header file must be contains 'TYPECODAGE' caracters."); } - if(lStrCodePix == "R4") + else { - m_PixelType = SCALAR; - SetComponentType(FLOAT); - m_NbOctetPixel=4; + return false; } - else if(lStrCodePix == "CI2") - { + } + file >> lStrCodePix; + + + lStrCodePix = System::SetToUpper(lStrCodePix); + if (lStrCodePix == "OCT") + { + m_PixelType = SCALAR; + SetComponentType(UCHAR); + m_NbOctetPixel=1; + } + if (lStrCodePix == "PHA") + { + m_PixelType = SCALAR; + SetComponentType(CHAR); + m_NbOctetPixel=1; + } + if (lStrCodePix == "I2") + { + m_PixelType = SCALAR; + SetComponentType(SHORT); + m_NbOctetPixel=2; + } + if (lStrCodePix == "I4") + { + m_PixelType = SCALAR; + SetComponentType(INT); + m_NbOctetPixel=4; + } + if (lStrCodePix == "R4") + { + m_PixelType = SCALAR; + SetComponentType(FLOAT); + m_NbOctetPixel=4; + } + else if (lStrCodePix == "CI2") + { + m_PixelType = COMPLEX; + SetComponentType(SHORT); + m_NbOctetPixel=4; + } + else if (lStrCodePix == "CR4") + { + m_PixelType = COMPLEX; + SetComponentType(FLOAT); + m_NbOctetPixel=8; + } + else if (lStrCodePix == "COCT") + { + m_PixelType = COMPLEX; + SetComponentType(UCHAR); + m_NbOctetPixel=2; + } + /* else if(lStrCodePix == "C3B") + { m_PixelType = COMPLEX; - SetComponentType(SHORT); - m_NbOctetPixel=4; + SetComponentType(FLOAT); + m_NbOctetPixel=2; } - else if(lStrCodePix == "CR4") - { + else if(lStrCodePix == "C5B") + { m_PixelType = COMPLEX; SetComponentType(FLOAT); - m_NbOctetPixel=8; + m_NbOctetPixel=2; } - else if(lStrCodePix == "COCT") - { + else if(lStrCodePix == "C7B") + { m_PixelType = COMPLEX; - SetComponentType(UCHAR); + SetComponentType(FLOAT); m_NbOctetPixel=2; } -/* else if(lStrCodePix == "C3B") - { - m_PixelType = COMPLEX; - SetComponentType(FLOAT); - m_NbOctetPixel=2; - } - else if(lStrCodePix == "C5B") - { + */ + + else if (lStrCodePix == "CI4") + { m_PixelType = COMPLEX; - SetComponentType(FLOAT); - m_NbOctetPixel=2; + SetComponentType(INT); + m_NbOctetPixel=8; } - else if(lStrCodePix == "C7B") - { + else if (lStrCodePix == "CR8") + { m_PixelType = COMPLEX; - SetComponentType(FLOAT); - m_NbOctetPixel=2; + SetComponentType(DOUBLE); + m_NbOctetPixel=16; } - */ - - else if(lStrCodePix == "CI4") + else + { + if ( reportError == true ) { - m_PixelType = COMPLEX; - SetComponentType(INT); - m_NbOctetPixel=8; + itkExceptionMacro(<< "RAD : the value type '"<<lStrCodePix<<"' (second line) set in the header file is not reconized as correct value."); } - else if(lStrCodePix == "CR8") + else { - m_PixelType = COMPLEX; - SetComponentType(DOUBLE); - m_NbOctetPixel=16; + return false; } - else + } + + // Read "SENSCODAGE" informations (optionnal) + file >> lString; + if ( lString.empty() == false) + { + lString = System::SetToUpper(lString); + if ( (lString == "SENSCODAGE") || (lString == "ORDER") ) { - if( reportError == true ) + file >> lString; + lString = System::SetToUpper(lString); + if ( lString == "INTEL" ) { - itkExceptionMacro(<< "RAD : the value type '"<<lStrCodePix<<"' (second line) set in the header file is not reconized as correct value."); + m_FileByteOrder = LittleEndian; } - else + else if ( lString == "IEEE" ) { - return false; + m_FileByteOrder = BigEndian; } - } - - // Read "SENSCODAGE" informations (optionnal) - file >> lString; - if( lString.empty() == false) - { - lString = System::SetToUpper(lString); - if( (lString == "SENSCODAGE") || (lString == "ORDER") ) + else { - file >> lString; - lString = System::SetToUpper(lString); - if( lString == "INTEL" ) - { - m_FileByteOrder = LittleEndian; - } - else if( lString == "IEEE" ) + if ( reportError == true ) { - m_FileByteOrder = BigEndian; + itkExceptionMacro(<< "RAD : the value SENSCODAGE '"<<lString<<"' set in the header file is not reconized as correct value. Possible values are INTEL or IEEE"); } else { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : the value SENSCODAGE '"<<lString<<"' set in the header file is not reconized as correct value. Possible values are INTEL or IEEE"); - } - else - { - return false; - } + return false; } } } + } - // Read FileName information - std::string lPathName = System::GetPathName( file_name ); - m_ChannelsFileName.clear(); - for(unsigned int i=0; i<m_NbOfChannels; i++) - { - file >> lString; - ::itk::OStringStream lStream; - lStream << lPathName <<"/"<< lString; - m_ChannelsFileName.push_back(lStream.str()); + // Read FileName information + std::string lPathName = System::GetPathName( file_name ); + m_ChannelsFileName.clear(); + for (unsigned int i=0; i<m_NbOfChannels; i++) + { + file >> lString; + ::itk::OStringStream lStream; + lStream << lPathName <<"/"<< lString; + m_ChannelsFileName.push_back(lStream.str()); - } - file.close(); + } + file.close(); - m_ChannelsFile = new std::fstream[m_NbOfChannels]; + m_ChannelsFile = new std::fstream[m_NbOfChannels]; - // Try to open channels file - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) - { + // Try to open channels file + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { - m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::in | std::ios::binary ); - if( m_ChannelsFile[channels].fail() ) + m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::in | std::ios::binary ); + if ( m_ChannelsFile[channels].fail() ) + { + if ( reportError == true ) { - if( reportError == true ) - { - itkExceptionMacro(<< "RAD : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); - } - else - { - return false; - } + itkExceptionMacro(<< "RAD : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); + } + else + { + return false; } } - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); - - return(true); } + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); + + return(true); +} - bool RADImageIO::CanWriteFile( const char* filename ) +bool RADImageIO::CanWriteFile( const char* filename ) +{ + std::string lFileName(filename); + if ( System::SetToLower(System::GetExtension(lFileName)) != "rad" ) { - std::string lFileName(filename); - if( System::SetToLower(System::GetExtension(lFileName)) != "rad" ) - { - return false; - } - if( System::IsADirName(lFileName) == true ) - { - return false; - } - return true; + return false; } - - void RADImageIO::Write(const void* buffer) + if ( System::IsADirName(lFileName) == true ) { + return false; + } + return true; +} +void RADImageIO::Write(const void* buffer) +{ - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } - unsigned long step = this->GetNumberOfComponents(); - unsigned int lNbLines = this->GetIORegion().GetSize()[1]; - unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; - int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] - int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + if ( m_FlagWriteImageInformation == true ) + { + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } - // Special case : we control that if the region to write has the same dimension that the entire picture, + unsigned long step = this->GetNumberOfComponents(); + unsigned int lNbLines = this->GetIORegion().GetSize()[1]; + unsigned int lNbColumns = this->GetIORegion().GetSize()[0]; + int lFirstLine = this->GetIORegion().GetIndex()[1]; // [1... ] + int lFirstColumn = this->GetIORegion().GetIndex()[0]; // [1... ] + + // Special case : we control that if the region to write has the same dimension that the entire picture, // we start to the offset to 0 ( when ze4re not in "Streaming") - if( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) - { - otbMsgDevMacro(<<"Force the IORegion offset to 0"); - lFirstLine = 0; - lFirstColumn = 0; - } + if ( (lNbLines == m_Dimensions[1]) && (lNbColumns == m_Dimensions[0])) + { + otbMsgDevMacro(<<"Force the IORegion offset to 0"); + lFirstLine = 0; + lFirstColumn = 0; + } - otbMsgDevMacro( <<" RADImageIO::Write() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); - otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); + otbMsgDevMacro( <<" RADImageIO::Write() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" GetComponentSize : "<<this->GetComponentSize()); - std::streamoff headerLength(0); - std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(m_NbOctetPixel * m_Dimensions[0]); - std::streamsize numberOfBytesToBeWrite = static_cast<std::streamsize>(m_NbOctetPixel * lNbColumns); + std::streamoff headerLength(0); + std::streamoff numberOfBytesPerLines = static_cast<std::streamoff>(m_NbOctetPixel * m_Dimensions[0]); + std::streamsize numberOfBytesToBeWrite = static_cast<std::streamsize>(m_NbOctetPixel * lNbColumns); - std::streamoff offset = 0; - unsigned long cpt = 0; + std::streamoff offset = 0; + unsigned long cpt = 0; - // Update the step variable - step = m_NbOctetPixel; + // Update the step variable + step = m_NbOctetPixel; - const char * p = static_cast<const char *>(buffer); + const char * p = static_cast<const char *>(buffer); - char* value = new char[numberOfBytesToBeWrite]; - if(value==NULL) - { - itkExceptionMacro(<<"RADImageIO::Write : Bad Alloc"); - return; - } + char* value = new char[numberOfBytesToBeWrite]; + if (value==NULL) + { + itkExceptionMacro(<<"RADImageIO::Write : Bad Alloc"); + return; + } - for (unsigned int numChannel = 0; numChannel < m_NbOfChannels; numChannel++) + for (unsigned int numChannel = 0; numChannel < m_NbOfChannels; numChannel++) + { + cpt = (unsigned long )(numChannel)* (unsigned long)(m_NbOctetPixel); + //Read region of the channel + for (unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) { - cpt = (unsigned long )(numChannel)* (unsigned long)(m_NbOctetPixel); - //Read region of the channel - for(unsigned int LineNo = lFirstLine;LineNo <lFirstLine + lNbLines; LineNo++ ) + for ( std::streamsize i=0; i < numberOfBytesToBeWrite; i = i+static_cast<std::streamsize>(m_NbOctetPixel) ) { - for ( std::streamsize i=0; i < numberOfBytesToBeWrite; i = i+static_cast<std::streamsize>(m_NbOctetPixel) ) - { - memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(m_NbOctetPixel)); - cpt += step; - } - - offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); - offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); - m_ChannelsFile[numChannel].seekp(offset, std::ios::beg); - //Write a line - m_ChannelsFile[numChannel].write( static_cast<char *>( value ), numberOfBytesToBeWrite ); + memcpy((void*)(&(value[i])),(const void*)(&(p[cpt])),(size_t)(m_NbOctetPixel)); + cpt += step; } - } - delete [] value; + offset = headerLength + numberOfBytesPerLines * static_cast<std::streamoff>(LineNo); + offset += static_cast<std::streamoff>(m_NbOctetPixel * lFirstColumn); + m_ChannelsFile[numChannel].seekp(offset, std::ios::beg); + //Write a line + m_ChannelsFile[numChannel].write( static_cast<char *>( value ), numberOfBytesToBeWrite ); + } } + delete [] value; +} + - void RADImageIO::WriteImageInformation() +void RADImageIO::WriteImageInformation() +{ + if ( m_FileName == "" ) { - if ( m_FileName == "" ) - { - itkExceptionMacro(<<"A FileName must be specified."); - } - if( CanWriteFile(m_FileName.c_str()) == false) - { - itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a RAD file"); - } + itkExceptionMacro(<<"A FileName must be specified."); + } + if ( CanWriteFile(m_FileName.c_str()) == false) + { + itkExceptionMacro(<< "The file "<<m_FileName.c_str()<<" is not defined as a RAD file"); + } - // Close file from any previous image - if ( m_HeaderFile.is_open() ) - { - m_HeaderFile.close(); - } + // Close file from any previous image + if ( m_HeaderFile.is_open() ) + { + m_HeaderFile.close(); + } - // Open the new file for writing - // Actually open the file - m_HeaderFile.open( m_FileName.c_str(), std::ios::out | std::ios::trunc ); - if( m_HeaderFile.fail() ) - { - itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); - } + // Open the new file for writing + // Actually open the file + m_HeaderFile.open( m_FileName.c_str(), std::ios::out | std::ios::trunc ); + if ( m_HeaderFile.fail() ) + { + itkExceptionMacro(<< "Cannot write requested file "<<m_FileName.c_str()<<"."); + } - //Write COLUMNS information - m_HeaderFile << "NBCOLUMNS "; - m_HeaderFile << m_Dimensions[0] << std::endl; + //Write COLUMNS information + m_HeaderFile << "NBCOLUMNS "; + m_HeaderFile << m_Dimensions[0] << std::endl; - //Write LINES information - m_HeaderFile << "NBLINES "; - m_HeaderFile << m_Dimensions[1] << std::endl; + //Write LINES information + m_HeaderFile << "NBLINES "; + m_HeaderFile << m_Dimensions[1] << std::endl; - //Write CHANNELS information - m_HeaderFile << "NBBANDS "; - m_HeaderFile << m_NbOfChannels << std::endl; + //Write CHANNELS information + m_HeaderFile << "NBBANDS "; + m_HeaderFile << m_NbOfChannels << std::endl; - std::string lString; - //Write TYPE information - m_HeaderFile << "TYPECODAGE "; + std::string lString; + //Write TYPE information + m_HeaderFile << "TYPECODAGE "; - std::string lExtension; - std::string lStringPixelType = System::SetToUpper(this->GetPixelTypeAsString(m_PixelType)); - std::string lStringComponentType = System::SetToUpper(this->GetComponentTypeAsString(this->GetComponentType())); + std::string lExtension; + std::string lStringPixelType = System::SetToUpper(this->GetPixelTypeAsString(m_PixelType)); + std::string lStringComponentType = System::SetToUpper(this->GetComponentTypeAsString(this->GetComponentType())); - if(lStringPixelType == "SCALAR") + if (lStringPixelType == "SCALAR") + { + if ( lStringComponentType =="UCHAR") { - if( lStringComponentType =="UCHAR") - { - m_NbOctetPixel=1; - m_TypeRAD = "OCT"; - lExtension=".oct"; - } - else if( lStringComponentType =="CHAR") - { - m_NbOctetPixel=1; - m_TypeRAD = "PHA"; - lExtension=".pha"; - } - else if( lStringComponentType =="SHORT") - { - m_NbOctetPixel=2; - m_TypeRAD = "I2"; - lExtension=".i2"; - } - else if( lStringComponentType =="INT") - { - m_NbOctetPixel=4; - m_TypeRAD = "I4"; - lExtension=".i4"; - } - else if( lStringComponentType =="FLOAT") - { - m_NbOctetPixel=4; - m_TypeRAD = "R4"; - lExtension=".r4"; - - } + m_NbOctetPixel=1; + m_TypeRAD = "OCT"; + lExtension=".oct"; } - else if( lStringPixelType == "COMPLEX") + else if ( lStringComponentType =="CHAR") { - if( lStringComponentType == "SHORT" ) - { - - m_NbOctetPixel=4; - m_TypeRAD = "CI2"; - lExtension=".ci2"; - } - else if( lStringComponentType == "FLOAT") - { - m_NbOctetPixel=8; - m_TypeRAD = "CR4"; - lExtension=".cr4"; - } - if( lStringComponentType == "CHAR") - { - m_NbOctetPixel=2; - m_TypeRAD = "COCT"; - lExtension=".coct"; - } -/* if( this->GetComponentType()=="FLOAT") - { - m_NbOctetPixel=2; - m_TypeRAD = "C3B" + m_NbOctetPixel=1; + m_TypeRAD = "PHA"; + lExtension=".pha"; } - if( this->GetComponentType()==FLOAT) - { + else if ( lStringComponentType =="SHORT") + { m_NbOctetPixel=2; - m_TypeRAD = "C5B" + m_TypeRAD = "I2"; + lExtension=".i2"; } - if( this->GetComponentType()==FLOAT) - { - m_NbOctetPixel=2; - m_TypeRAD = "C7B" + else if ( lStringComponentType =="INT") + { + m_NbOctetPixel=4; + m_TypeRAD = "I4"; + lExtension=".i4"; } - */ else if( lStringComponentType == "INT") - { - m_NbOctetPixel=8; - m_TypeRAD = "CI4"; - lExtension=".ci4"; - } - else if( lStringComponentType == "DOUBLE") - { - m_NbOctetPixel=16; - m_TypeRAD = "CR8"; - lExtension=".cr8"; - } + else if ( lStringComponentType =="FLOAT") + { + m_NbOctetPixel=4; + m_TypeRAD = "R4"; + lExtension=".r4"; + } - m_HeaderFile << m_TypeRAD << std::endl; + } + else if ( lStringPixelType == "COMPLEX") + { + if ( lStringComponentType == "SHORT" ) + { - //Write "SENSCODAGE" informations - m_HeaderFile << "SENSCODAGE "; // << std::endl; - if( m_ByteOrder == LittleEndian ) + m_NbOctetPixel=4; + m_TypeRAD = "CI2"; + lExtension=".ci2"; + } + else if ( lStringComponentType == "FLOAT") { - m_HeaderFile << "INTEL" << std::endl; + m_NbOctetPixel=8; + m_TypeRAD = "CR4"; + lExtension=".cr4"; } - else + if ( lStringComponentType == "CHAR") { - m_HeaderFile << "IEEE" << std::endl; + m_NbOctetPixel=2; + m_TypeRAD = "COCT"; + lExtension=".coct"; } - - //Define channels file name - std::string lRootName = System::GetRootName( m_FileName ); - m_ChannelsFileName.clear(); - for(unsigned int i=0; i<m_NbOfChannels; i++) + /* if( this->GetComponentType()=="FLOAT") + { + m_NbOctetPixel=2; + m_TypeRAD = "C3B" + } + if( this->GetComponentType()==FLOAT) + { + m_NbOctetPixel=2; + m_TypeRAD = "C5B" + } + if( this->GetComponentType()==FLOAT) + { + m_NbOctetPixel=2; + m_TypeRAD = "C7B" + } + */ + else if ( lStringComponentType == "INT") { - ::itk::OStringStream lStream; - lStream << lRootName <<"_"<< i+1 << lExtension; - m_ChannelsFileName.push_back(lStream.str()); + m_NbOctetPixel=8; + m_TypeRAD = "CI4"; + lExtension=".ci4"; } - - for(unsigned int i=0;i<m_NbOfChannels;i++) + else if ( lStringComponentType == "DOUBLE") { - m_HeaderFile << System::GetShortFileName(this->m_ChannelsFileName[i].c_str()) << std::endl; + m_NbOctetPixel=16; + m_TypeRAD = "CR8"; + lExtension=".cr8"; } - m_HeaderFile.close(); + } + m_HeaderFile << m_TypeRAD << std::endl; + + //Write "SENSCODAGE" informations + m_HeaderFile << "SENSCODAGE "; // << std::endl; + if ( m_ByteOrder == LittleEndian ) + { + m_HeaderFile << "INTEL" << std::endl; + } + else + { + m_HeaderFile << "IEEE" << std::endl; + } + + //Define channels file name + std::string lRootName = System::GetRootName( m_FileName ); + m_ChannelsFileName.clear(); + for (unsigned int i=0; i<m_NbOfChannels; i++) + { + ::itk::OStringStream lStream; + lStream << lRootName <<"_"<< i+1 << lExtension; + m_ChannelsFileName.push_back(lStream.str()); + } + + for (unsigned int i=0;i<m_NbOfChannels;i++) + { + m_HeaderFile << System::GetShortFileName(this->m_ChannelsFileName[i].c_str()) << std::endl; + } + m_HeaderFile.close(); - //Allocate buffer of stream file - m_ChannelsFile = new std::fstream[m_NbOfChannels]; + //Allocate buffer of stream file + m_ChannelsFile = new std::fstream[m_NbOfChannels]; - //Try to open channels file - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + //Try to open channels file + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { + m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); + if ( m_ChannelsFile[channels].fail() ) { - m_ChannelsFile[channels].open( m_ChannelsFileName[channels].c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); - if( m_ChannelsFile[channels].fail() ) - { - itkExceptionMacro(<< "RAD : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); - } + itkExceptionMacro(<< "RAD : impossible to find the file <"<<m_ChannelsFileName[channels]<<">."); } - this->SetFileTypeToBinary(); - this->SetNumberOfDimensions(2); - this->SetNumberOfComponents(2*m_NbOfChannels); + } + this->SetFileTypeToBinary(); + this->SetNumberOfDimensions(2); + this->SetNumberOfComponents(2*m_NbOfChannels); - unsigned long numberOfBytesPerLines = m_NbOctetPixel * m_Dimensions[0]; - char* value = new char[numberOfBytesPerLines]; + unsigned long numberOfBytesPerLines = m_NbOctetPixel * m_Dimensions[0]; + char* value = new char[numberOfBytesPerLines]; - for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + for (unsigned int channels = 0; channels<m_ChannelsFileName.size(); channels++) + { + m_ChannelsFile[channels].seekp(0, std::ios::beg ); + //Write Header line and all file (whitout information) + for (unsigned int numLigne=0; numLigne<(m_Dimensions[1]); numLigne++) { - m_ChannelsFile[channels].seekp(0, std::ios::beg ); - //Write Header line and all file (whitout information) - for(unsigned int numLigne=0; numLigne<(m_Dimensions[1]); numLigne++) - { - m_ChannelsFile[channels].write(value,numberOfBytesPerLines); - } + m_ChannelsFile[channels].write(value,numberOfBytesPerLines); } + } - delete [] value; + delete [] value; - otbMsgDebugMacro( <<"Driver to write: RAD"); - otbMsgDebugMacro( <<" Write file : "<< m_FileName); - otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDebugMacro( <<" Type Rad : "<<m_TypeRAD); - otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); - otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); - otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); - otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); + otbMsgDebugMacro( <<"Driver to write: RAD"); + otbMsgDebugMacro( <<" Write file : "<< m_FileName); + otbMsgDebugMacro( <<" Size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDebugMacro( <<" Type Rad : "<<m_TypeRAD); + otbMsgDebugMacro( <<" ComponentType : "<<this->GetComponentType() ); + otbMsgDebugMacro( <<" NumberOfComponents : "<<this->GetNumberOfComponents()); + otbMsgDebugMacro( <<" ComponentSize : "<<this->GetComponentSize()); + otbMsgDebugMacro( <<" GetPixelSize : "<<this->GetPixelSize()); - } +} } // end namespace otb diff --git a/Code/IO/otbRADImageIO.h b/Code/IO/otbRADImageIO.h index 643e3e84b6370c5612dac65fc36a4c429668125b..ab8516f831b2145fe822d52d207e74cd4a2fcef8 100644 --- a/Code/IO/otbRADImageIO.h +++ b/Code/IO/otbRADImageIO.h @@ -61,7 +61,10 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + virtual bool CanStreamRead() + { + return true; + }; /** Set the spacing and dimention information for the set filename. */ virtual void ReadImageInformation(); @@ -79,7 +82,10 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ diff --git a/Code/IO/otbSHPVectorDataIO.h b/Code/IO/otbSHPVectorDataIO.h index 501499036f9a9ed3d0d9c90415dc7dc64c57818f..5388a960fe7e7dc767ee3887fabc9e55389e4cdf 100644 --- a/Code/IO/otbSHPVectorDataIO.h +++ b/Code/IO/otbSHPVectorDataIO.h @@ -34,8 +34,8 @@ namespace otb * */ template <class TData> class ITK_EXPORT SHPVectorDataIO - : public VectorDataIOBase<TData> - { + : public VectorDataIOBase<TData> +{ public: /** Standard class typedefs. */ @@ -84,10 +84,13 @@ public: virtual bool CanReadFile(const char*); /** Determine the file type. Returns true if the VectorDataIO can stream read the specified file */ - virtual bool CanStreamRead(){ return false; }; + virtual bool CanStreamRead() + { + return false; + }; -/* /\** Set the spacing and dimention information for the set filename. *\/ */ -/* virtual void ReadVectorDataInformation(); */ + /* /\** Set the spacing and dimention information for the set filename. *\/ */ + /* virtual void ReadVectorDataInformation(); */ /** Reads the data from disk into the memory buffer provided. */ virtual void Read(VectorDataPointerType data); @@ -99,11 +102,14 @@ public: virtual bool CanWriteFile(const char*); /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ - virtual bool CanStreamWrite() { return false; }; + virtual bool CanStreamWrite() + { + return false; + }; -/* /\** Writes the spacing and dimentions of the image. */ -/* * Assumes SetFileName has been called with a valid file name. *\/ */ -/* virtual void WriteVectorDataInformation(); */ + /* /\** Writes the spacing and dimentions of the image. */ + /* * Assumes SetFileName has been called with a valid file name. *\/ */ + /* virtual void WriteVectorDataInformation(); */ /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegion has been set properly. */ diff --git a/Code/IO/otbSHPVectorDataIO.txx b/Code/IO/otbSHPVectorDataIO.txx index 17b8596e5f95766c6c859345d85256e91cca8409..49171d6bf44becfa5a0fe8dd6b66e6b2dda2b1cf 100644 --- a/Code/IO/otbSHPVectorDataIO.txx +++ b/Code/IO/otbSHPVectorDataIO.txx @@ -32,100 +32,100 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template<class TData> - SHPVectorDataIO<TData> - ::SHPVectorDataIO() - { - // OGR factory registration - OGRRegisterAll(); - m_DataSource = NULL; +template<class TData> +SHPVectorDataIO<TData> +::SHPVectorDataIO() +{ + // OGR factory registration + OGRRegisterAll(); + m_DataSource = NULL; - } +} - template<class TData> - SHPVectorDataIO<TData>::~SHPVectorDataIO() +template<class TData> +SHPVectorDataIO<TData>::~SHPVectorDataIO() +{ + if (m_DataSource != NULL) { - if(m_DataSource != NULL) - { - OGRDataSource::DestroyDataSource(m_DataSource); - } + OGRDataSource::DestroyDataSource(m_DataSource); } +} - template<class TData> - bool - SHPVectorDataIO<TData>::CanReadFile( const char* filename ) - { - +template<class TData> +bool +SHPVectorDataIO<TData>::CanReadFile( const char* filename ) +{ - OGRDataSource * poDS = OGRSFDriverRegistrar::Open(filename, FALSE); - if(poDS == NULL) - { - return false; - } - OGRDataSource::DestroyDataSource(poDS); - return true; + OGRDataSource * poDS = OGRSFDriverRegistrar::Open(filename, FALSE); + if (poDS == NULL) + { + return false; } + OGRDataSource::DestroyDataSource(poDS); + return true; +} - // Used to print information about this object - template<class TData> - void - SHPVectorDataIO<TData>::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - } - // Read vector data - template<class TData> - void - SHPVectorDataIO<TData> - ::Read(VectorDataPointerType data) +// Used to print information about this object +template<class TData> +void +SHPVectorDataIO<TData>::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +// Read vector data +template<class TData> +void +SHPVectorDataIO<TData> +::Read(VectorDataPointerType data) +{ + // Destroy previous opened data source + if (m_DataSource != NULL) { - // Destroy previous opened data source - if(m_DataSource != NULL) - { - OGRDataSource::DestroyDataSource(m_DataSource); - } + OGRDataSource::DestroyDataSource(m_DataSource); + } - m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), FALSE); + m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), FALSE); - if(m_DataSource == NULL) - { - itkExceptionMacro(<<"Failed to open data file "<<this->m_FileName); - } + if (m_DataSource == NULL) + { + itkExceptionMacro(<<"Failed to open data file "<<this->m_FileName); + } - otbMsgDebugMacro( <<"Driver to read: OGR"); - otbMsgDebugMacro( <<"Reading file: "<< this->m_FileName); + otbMsgDebugMacro( <<"Driver to read: OGR"); + otbMsgDebugMacro( <<"Reading file: "<< this->m_FileName); - // Reading layers - otbMsgDebugMacro(<<"Number of layers: "<<m_DataSource->GetLayerCount()); + // Reading layers + otbMsgDebugMacro(<<"Number of layers: "<<m_DataSource->GetLayerCount()); - // Retrieving root node - DataTreePointerType tree = data->GetDataTree(); - DataNodePointerType root = tree->GetRoot()->Get(); + // Retrieving root node + DataTreePointerType tree = data->GetDataTree(); + DataNodePointerType root = tree->GetRoot()->Get(); - OGRSpatialReference * oSRS =NULL; - //We take the assumption that the spatial reference is common to all layers - oSRS = m_DataSource->GetLayer(0)->GetSpatialRef(); + OGRSpatialReference * oSRS =NULL; + //We take the assumption that the spatial reference is common to all layers + oSRS = m_DataSource->GetLayer(0)->GetSpatialRef(); - if (oSRS != NULL) - { - char * projectionRefChar; - oSRS->exportToWkt(&projectionRefChar); - std::string projectionRef = projectionRefChar; - OGRFree(projectionRefChar); - itk::MetaDataDictionary & dict = data->GetMetaDataDictionary(); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); - } - else - { - otbMsgDevMacro(<< "Can't retrieve the OGRSpatialReference from the shapefile"); - } + if (oSRS != NULL) + { + char * projectionRefChar; + oSRS->exportToWkt(&projectionRefChar); + std::string projectionRef = projectionRefChar; + OGRFree(projectionRefChar); + itk::MetaDataDictionary & dict = data->GetMetaDataDictionary(); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); + } + else + { + otbMsgDevMacro(<< "Can't retrieve the OGRSpatialReference from the shapefile"); + } - std::string projectionRefWkt = data->GetProjectionRef(); + std::string projectionRefWkt = data->GetProjectionRef(); // if (projectionRefWkt.compare(this->m_TargetProjection) != 0) // { @@ -134,769 +134,769 @@ namespace otb // } - bool projectionInformationAvailable = !projectionRefWkt.empty(); + bool projectionInformationAvailable = !projectionRefWkt.empty(); - if (projectionInformationAvailable) - { - otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); - } - else + if (projectionInformationAvailable) + { + otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); + } + else + { + otbMsgDevMacro(<< "Projection information unavailable"); + } + + // For each layer + for (int layerIndex = 0;layerIndex<m_DataSource->GetLayerCount();++layerIndex) + { + /** retrieving layer and property */ + OGRLayer * layer = m_DataSource->GetLayer(layerIndex); + OGRFeatureDefn * dfn = layer->GetLayerDefn(); + + /** Create the document node */ + DataNodePointerType document = DataNodeType::New(); + document->SetNodeType(DOCUMENT); + document->SetNodeId(dfn->GetName()); + + /** Retrieving the fields types */ + for (int fieldIndex = 0; fieldIndex<dfn->GetFieldCount();++fieldIndex) { - otbMsgDevMacro(<< "Projection information unavailable"); + OGRFieldDefn * field = dfn->GetFieldDefn(fieldIndex); + document->SetField(field->GetNameRef(),OGRFieldDefn::GetFieldTypeName(field->GetType())); + // std::cout<<"Document "<<document->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<OGRFieldDefn::GetFieldTypeName(field->GetType())<<std::endl; } - // For each layer - for(int layerIndex = 0;layerIndex<m_DataSource->GetLayerCount();++layerIndex) - { - /** retrieving layer and property */ - OGRLayer * layer = m_DataSource->GetLayer(layerIndex); - OGRFeatureDefn * dfn = layer->GetLayerDefn(); + /** Adding the layer to the data tree */ + tree->Add(document,root); + + /** Temporary pointer to store the feature */ + OGRFeature * feature; + + layer->ResetReading(); - /** Create the document node */ - DataNodePointerType document = DataNodeType::New(); - document->SetNodeType(DOCUMENT); - document->SetNodeId(dfn->GetName()); + while ((feature = layer->GetNextFeature())!=NULL) + { + DataNodePointerType folder = DataNodeType::New(); + folder->SetNodeType(FOLDER); + folder->SetNodeId(feature->GetDefnRef()->GetName()); - /** Retrieving the fields types */ - for(int fieldIndex = 0; fieldIndex<dfn->GetFieldCount();++fieldIndex) + // Reading fields + for (int fieldIndex = 0; fieldIndex<dfn->GetFieldCount();++fieldIndex) { OGRFieldDefn * field = dfn->GetFieldDefn(fieldIndex); - document->SetField(field->GetNameRef(),OGRFieldDefn::GetFieldTypeName(field->GetType())); - // std::cout<<"Document "<<document->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<OGRFieldDefn::GetFieldTypeName(field->GetType())<<std::endl; + folder->SetField(field->GetNameRef(),feature->GetFieldAsString(fieldIndex)); + // std::cout<<"Folder "<<folder->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<feature->GetFieldAsString(fieldIndex)<<std::endl; } - /** Adding the layer to the data tree */ - tree->Add(document,root); - /** Temporary pointer to store the feature */ - OGRFeature * feature; + tree->Add(folder,document); - layer->ResetReading(); + /** Temporary geometry container */ + OGRGeometry * geometry = feature->GetGeometryRef(); - while((feature = layer->GetNextFeature())!=NULL) + + if (geometry != NULL) { - DataNodePointerType folder = DataNodeType::New(); - folder->SetNodeType(FOLDER); - folder->SetNodeId(feature->GetDefnRef()->GetName()); + switch (geometry->getGeometryType()) + { + case wkbPoint: + { + tree->Add(ConvertGeometryToPointNode(geometry),folder); + break; + } + case wkbPoint25D: + { + tree->Add(ConvertGeometryToPointNode(geometry),folder); + break; + } + case wkbLineString: + { + tree->Add(ConvertGeometryToLineNode(geometry),folder); + break; + } + case wkbLineString25D: + { + tree->Add(ConvertGeometryToLineNode(geometry),folder); + break; + } + case wkbPolygon: + { + tree->Add(ConvertGeometryToPolygonNode(geometry),folder); + break; + } + case wkbPolygon25D: + { + tree->Add(ConvertGeometryToPolygonNode(geometry),folder); + break; + } + case wkbMultiPoint: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTIPOINT); + tree->Add(multi,folder); - // Reading fields - for(int fieldIndex = 0; fieldIndex<dfn->GetFieldCount();++fieldIndex) + OGRMultiPoint * ogrMulti = (OGRMultiPoint *) geometry; + + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; + } + case wkbMultiPoint25D: { - OGRFieldDefn * field = dfn->GetFieldDefn(fieldIndex); - folder->SetField(field->GetNameRef(),feature->GetFieldAsString(fieldIndex)); - // std::cout<<"Folder "<<folder->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<feature->GetFieldAsString(fieldIndex)<<std::endl; + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTIPOINT); + tree->Add(multi,folder); + + OGRMultiPoint * ogrMulti = (OGRMultiPoint *) geometry; + + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; } + case wkbMultiLineString: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTILINE); + tree->Add(multi,folder); + + OGRMultiLineString * ogrMulti = (OGRMultiLineString *) geometry; + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; + } + case wkbMultiLineString25D: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTILINE); + tree->Add(multi,folder); + + OGRMultiLineString * ogrMulti = (OGRMultiLineString *) geometry; + + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; + } + case wkbMultiPolygon: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTIPOLYGON); + tree->Add(multi,folder); - tree->Add(folder,document); + OGRMultiPolygon * ogrMulti = (OGRMultiPolygon *) geometry; - /** Temporary geometry container */ - OGRGeometry * geometry = feature->GetGeometryRef(); + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; + } + case wkbMultiPolygon25D: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_MULTIPOLYGON); + tree->Add(multi,folder); + OGRMultiPolygon * ogrMulti = (OGRMultiPolygon *) geometry; - if(geometry != NULL) + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); + } + break; + } + case wkbGeometryCollection: { - switch(geometry->getGeometryType()) + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_COLLECTION); + tree->Add(multi,folder); + + OGRGeometryCollection * ogrMulti = (OGRGeometryCollection *) geometry; + + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) { + switch (ogrMulti->getGeometryRef(geoIndex)->getGeometryType()) + { case wkbPoint: { - tree->Add(ConvertGeometryToPointNode(geometry),folder); + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } case wkbPoint25D: { - tree->Add(ConvertGeometryToPointNode(geometry),folder); + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } case wkbLineString: { - tree->Add(ConvertGeometryToLineNode(geometry),folder); + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } case wkbLineString25D: { - tree->Add(ConvertGeometryToLineNode(geometry),folder); + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } case wkbPolygon: { - tree->Add(ConvertGeometryToPolygonNode(geometry),folder); + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } case wkbPolygon25D: { - tree->Add(ConvertGeometryToPolygonNode(geometry),folder); + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbMultiPoint: + default: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTIPOINT); - tree->Add(multi,folder); - - OGRMultiPoint * ogrMulti = (OGRMultiPoint *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } + std::cout<<"Geometry type not found: "<<ogrMulti->getGeometryRef(geoIndex)->getGeometryType()<<std::endl; break; } - case wkbMultiPoint25D: - { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTIPOINT); - tree->Add(multi,folder); - - OGRMultiPoint * ogrMulti = (OGRMultiPoint *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } - break; } - case wkbMultiLineString: - { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTILINE); - tree->Add(multi,folder); + } + break; + } + case wkbGeometryCollection25D: + { + DataNodePointerType multi = DataNodeType::New(); + multi->SetNodeType(FEATURE_COLLECTION); + tree->Add(multi,folder); - OGRMultiLineString * ogrMulti = (OGRMultiLineString *) geometry; + OGRGeometryCollection * ogrMulti = (OGRGeometryCollection *) geometry; - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } + for (int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) + { + switch (ogrMulti->getGeometryRef(geoIndex)->getGeometryType()) + { + case wkbPoint: + { + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbMultiLineString25D: + case wkbPoint25D: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTILINE); - tree->Add(multi,folder); - - OGRMultiLineString * ogrMulti = (OGRMultiLineString *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } + tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbMultiPolygon: + case wkbLineString: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTIPOLYGON); - tree->Add(multi,folder); - - OGRMultiPolygon * ogrMulti = (OGRMultiPolygon *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbMultiPolygon25D: + case wkbLineString25D: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_MULTIPOLYGON); - tree->Add(multi,folder); - - OGRMultiPolygon * ogrMulti = (OGRMultiPolygon *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - } + tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbGeometryCollection: + case wkbPolygon: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_COLLECTION); - tree->Add(multi,folder); - - OGRGeometryCollection * ogrMulti = (OGRGeometryCollection *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - switch(ogrMulti->getGeometryRef(geoIndex)->getGeometryType()) - { - case wkbPoint: - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPoint25D: - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbLineString: - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbLineString25D: - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPolygon: - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPolygon25D: - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - default: - { - std::cout<<"Geometry type not found: "<<ogrMulti->getGeometryRef(geoIndex)->getGeometryType()<<std::endl; - break; - } - } - } + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } - case wkbGeometryCollection25D: + case wkbPolygon25D: { - DataNodePointerType multi = DataNodeType::New(); - multi->SetNodeType(FEATURE_COLLECTION); - tree->Add(multi,folder); - - OGRGeometryCollection * ogrMulti = (OGRGeometryCollection *) geometry; - - for(int geoIndex = 0;geoIndex<ogrMulti->getNumGeometries();++geoIndex) - { - switch(ogrMulti->getGeometryRef(geoIndex)->getGeometryType()) - { - case wkbPoint: - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPoint25D: - { - tree->Add(ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbLineString: - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbLineString25D: - { - tree->Add(ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPolygon: - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - case wkbPolygon25D: - { - tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); - break; - } - default: - { - std::cout<<"Geometry type not found: "<<ogrMulti->getGeometryRef(geoIndex)->getGeometryType()<<std::endl; - break; - } - } - } + tree->Add(ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex)),multi); break; } default: { - std::cout<<"Geometry not handled: "<<geometry->getGeometryName()<<std::endl; + std::cout<<"Geometry type not found: "<<ogrMulti->getGeometryRef(geoIndex)->getGeometryType()<<std::endl; break; } + } } - + break; + } + default: + { + std::cout<<"Geometry not handled: "<<geometry->getGeometryName()<<std::endl; + break; + } } + } } } +} + +template<class TData> +typename SHPVectorDataIO<TData> +::DataNodePointerType +SHPVectorDataIO<TData> +::ConvertGeometryToPointNode(const OGRGeometry * ogrGeometry) const +{ + OGRPoint * ogrPoint = (OGRPoint *) ogrGeometry; - template<class TData> - typename SHPVectorDataIO<TData> - ::DataNodePointerType - SHPVectorDataIO<TData> - ::ConvertGeometryToPointNode(const OGRGeometry * ogrGeometry) const + if (ogrPoint == NULL) { - OGRPoint * ogrPoint = (OGRPoint *) ogrGeometry; + itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRPoint"); + } - if(ogrPoint == NULL) - { - itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRPoint"); - } + PointType otbPoint; + otbPoint.Fill(0); + otbPoint[0] = static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getX()); + otbPoint[1] = static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getY()); - PointType otbPoint; - otbPoint.Fill(0); - otbPoint[0] = static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getX()); - otbPoint[1] = static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getY()); + if (DataNodeType::Dimension > 2) + { + otbPoint[2]=static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getZ()); + } - if(DataNodeType::Dimension > 2) - { - otbPoint[2]=static_cast<typename DataNodeType::PrecisionType>(ogrPoint->getZ()); - } + DataNodePointerType node = DataNodeType::New(); + node->SetPoint(otbPoint); + return node; +} + +template<class TData> +typename SHPVectorDataIO<TData> +::DataNodePointerType +SHPVectorDataIO<TData> +::ConvertGeometryToLineNode(const OGRGeometry * ogrGeometry) const +{ + OGRLineString * ogrLine = (OGRLineString *)ogrGeometry; - DataNodePointerType node = DataNodeType::New(); - node->SetPoint(otbPoint); - return node; + if (ogrLine == NULL) + { + itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRLine"); } - template<class TData> - typename SHPVectorDataIO<TData> - ::DataNodePointerType - SHPVectorDataIO<TData> - ::ConvertGeometryToLineNode(const OGRGeometry * ogrGeometry) const + LinePointerType line = LineType::New(); + + OGRPoint * ogrTmpPoint = new OGRPoint(); + + for (int pIndex = 0;pIndex<ogrLine->getNumPoints();++pIndex) { - OGRLineString * ogrLine = (OGRLineString *)ogrGeometry; - if(ogrLine == NULL) - { - itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRLine"); - } + ogrLine->getPoint(pIndex,ogrTmpPoint); - LinePointerType line = LineType::New(); + typename LineType::VertexType vertex; - OGRPoint * ogrTmpPoint = new OGRPoint(); + vertex[0] = ogrTmpPoint->getX(); + vertex[1] = ogrTmpPoint->getY(); - for(int pIndex = 0;pIndex<ogrLine->getNumPoints();++pIndex) + if (DataNodeType::Dimension > 2) { + vertex[2]= ogrTmpPoint->getZ(); + } - ogrLine->getPoint(pIndex,ogrTmpPoint); + line->AddVertex(vertex); + } + delete ogrTmpPoint; - typename LineType::VertexType vertex; + DataNodePointerType node = DataNodeType::New(); + node->SetLine(line); - vertex[0] = ogrTmpPoint->getX(); - vertex[1] = ogrTmpPoint->getY(); + return node; +} - if(DataNodeType::Dimension > 2) - { - vertex[2]= ogrTmpPoint->getZ(); - } +template<class TData> +typename SHPVectorDataIO<TData> +::DataNodePointerType +SHPVectorDataIO<TData> +::ConvertGeometryToPolygonNode(const OGRGeometry * ogrGeometry) const +{ + OGRPolygon * ogrPolygon = (OGRPolygon *)ogrGeometry; - line->AddVertex(vertex); - } - delete ogrTmpPoint; + if (ogrPolygon == NULL) + { + itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRPolygon"); + } - DataNodePointerType node = DataNodeType::New(); - node->SetLine(line); + OGRPoint * ogrTmpPoint = new OGRPoint(); - return node; - } + OGRLinearRing * ogrRing = ogrPolygon->getExteriorRing(); - template<class TData> - typename SHPVectorDataIO<TData> - ::DataNodePointerType - SHPVectorDataIO<TData> - ::ConvertGeometryToPolygonNode(const OGRGeometry * ogrGeometry) const + PolygonPointerType extRing = PolygonType::New(); + + for (int pIndex = 0;pIndex<ogrRing->getNumPoints();++pIndex) { - OGRPolygon * ogrPolygon = (OGRPolygon *)ogrGeometry; + ogrRing->getPoint(pIndex,ogrTmpPoint); + typename PolygonType::VertexType vertex; + vertex[0] = ogrTmpPoint->getX(); + vertex[1] = ogrTmpPoint->getY(); - if(ogrPolygon == NULL) + if (DataNodeType::Dimension > 2) { - itkGenericExceptionMacro(<<"Failed to convert OGRGeometry to OGRPolygon"); + vertex[2]= ogrTmpPoint->getZ(); } - OGRPoint * ogrTmpPoint = new OGRPoint(); - - OGRLinearRing * ogrRing = ogrPolygon->getExteriorRing(); + extRing->AddVertex(vertex); + } - PolygonPointerType extRing = PolygonType::New(); + PolygonListPointerType intRings = PolygonListType::New(); - for(int pIndex = 0;pIndex<ogrRing->getNumPoints();++pIndex) + for (int intRingIndex = 0;intRingIndex<ogrPolygon->getNumInteriorRings();++intRingIndex) + { + PolygonPointerType ring = PolygonType::New(); + ogrRing = ogrPolygon->getInteriorRing(intRingIndex); + for (int pIndex = 0;pIndex<ogrRing->getNumPoints();++pIndex) { ogrRing->getPoint(pIndex,ogrTmpPoint); typename PolygonType::VertexType vertex; + vertex[0] = ogrTmpPoint->getX(); vertex[1] = ogrTmpPoint->getY(); - - if(DataNodeType::Dimension > 2) + if (DataNodeType::Dimension > 2) { vertex[2]= ogrTmpPoint->getZ(); } - - extRing->AddVertex(vertex); + ring->AddVertex(vertex); } + intRings->PushBack(ring); + } - PolygonListPointerType intRings = PolygonListType::New(); + delete ogrTmpPoint; - for(int intRingIndex = 0;intRingIndex<ogrPolygon->getNumInteriorRings();++intRingIndex) - { - PolygonPointerType ring = PolygonType::New(); - ogrRing = ogrPolygon->getInteriorRing(intRingIndex); - for(int pIndex = 0;pIndex<ogrRing->getNumPoints();++pIndex) - { - ogrRing->getPoint(pIndex,ogrTmpPoint); - typename PolygonType::VertexType vertex; + DataNodePointerType node = DataNodeType::New(); + node->SetPolygonExteriorRing(extRing); + node->SetPolygonInteriorRings(intRings); - vertex[0] = ogrTmpPoint->getX(); - vertex[1] = ogrTmpPoint->getY(); - if(DataNodeType::Dimension > 2) - { - vertex[2]= ogrTmpPoint->getZ(); - } - ring->AddVertex(vertex); - } - intRings->PushBack(ring); - } + return node; +} - delete ogrTmpPoint; +template<class TData> +bool SHPVectorDataIO<TData>::CanWriteFile( const char* filename ) +{ + std::string lFileName(filename); + if ( System::IsADirName(lFileName) == true ) + { + return false; + } + const std::string Extension = System::GetExtension(filename); + if ( (Extension == "shp") || (Extension == "SHP") ) + { + return true; + } + else + { + return false; + } +} - DataNodePointerType node = DataNodeType::New(); - node->SetPolygonExteriorRing(extRing); - node->SetPolygonInteriorRings(intRings); +template<class TData> +void SHPVectorDataIO<TData>::Write(const VectorDataConstPointerType data) +{ + // // try to create an ogr driver + OGRSFDriver * ogrDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("ESRI Shapefile"); - return node; + if (ogrDriver == NULL) + { + itkExceptionMacro(<<"No OGR driver found to write file "<<this->m_FileName); } - template<class TData> - bool SHPVectorDataIO<TData>::CanWriteFile( const char* filename ) + // free an existing previous data source, if any + if (m_DataSource != NULL) { - std::string lFileName(filename); - if( System::IsADirName(lFileName) == true ) - { - return false; - } - const std::string Extension = System::GetExtension(filename); - if( (Extension == "shp") || (Extension == "SHP") ) - { - return true; - } - else - { - return false; - } + OGRDataSource::DestroyDataSource(m_DataSource); } - template<class TData> - void SHPVectorDataIO<TData>::Write(const VectorDataConstPointerType data) + //if file exist, OGR can't overwrite: remove it first + otb::FileName filename(this->m_FileName.c_str()); + if (filename.exists()) { - // // try to create an ogr driver - OGRSFDriver * ogrDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("ESRI Shapefile"); + filename.remove(); + } - if(ogrDriver == NULL) - { - itkExceptionMacro(<<"No OGR driver found to write file "<<this->m_FileName); - } + // m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); + m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(),NULL); - // free an existing previous data source, if any - if(m_DataSource != NULL) - { - OGRDataSource::DestroyDataSource(m_DataSource); - } - //if file exist, OGR can't overwrite: remove it first - otb::FileName filename(this->m_FileName.c_str()); - if (filename.exists()) - { - filename.remove(); - } + // check the created data source + if (m_DataSource == NULL) + { + itkExceptionMacro(<<"Failed to create OGR data source for file "<<this->m_FileName<<". Since OGR can not overwrite existing file, be sure that this file does not already exist"); + } - // m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); - m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(),NULL); + // Retrieve data required for georeferencing + std::string projectionRefWkt = data->GetProjectionRef(); + bool projectionInformationAvailable = !projectionRefWkt.empty(); - // check the created data source - if(m_DataSource == NULL) - { - itkExceptionMacro(<<"Failed to create OGR data source for file "<<this->m_FileName<<". Since OGR can not overwrite existing file, be sure that this file does not already exist"); - } + if (projectionInformationAvailable) + { + otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); + } + else + { + otbMsgDevMacro(<< "Projection information unavailable"); + } - // Retrieve data required for georeferencing + // Retrieving root node + DataTreeConstPointerType tree = data->GetDataTree(); + if (tree->GetRoot() == NULL) + { + itkExceptionMacro(<<"Data tree is empty: Root == NULL"); + } + DataNodePointerType root = tree->GetRoot()->Get(); - std::string projectionRefWkt = data->GetProjectionRef(); - bool projectionInformationAvailable = !projectionRefWkt.empty(); + typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; - if (projectionInformationAvailable) - { - otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); - } - else - { - otbMsgDevMacro(<< "Projection information unavailable"); - } + OGRSpatialReference * oSRS =NULL; + OGRLayer * ogrCurrentLayer = NULL; + std::vector<OGRFeature *> ogrFeatures; + OGRGeometryCollection * ogrCollection = NULL; + // OGRGeometry * ogrCurrentGeometry = NULL; + + TreeIteratorType it(tree); + it.GoToBegin(); - // Retrieving root node - DataTreeConstPointerType tree = data->GetDataTree(); - if (tree->GetRoot() == NULL) + while (!it.IsAtEnd()) + { + switch (it.Get()->GetNodeType()) + { + case ROOT: { - itkExceptionMacro(<<"Data tree is empty: Root == NULL"); + break; } - DataNodePointerType root = tree->GetRoot()->Get(); - - typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; - - OGRSpatialReference * oSRS =NULL; - OGRLayer * ogrCurrentLayer = NULL; - std::vector<OGRFeature *> ogrFeatures; - OGRGeometryCollection * ogrCollection = NULL; - // OGRGeometry * ogrCurrentGeometry = NULL; - - TreeIteratorType it(tree); - it.GoToBegin(); - - while(!it.IsAtEnd()) + case DOCUMENT: { - switch(it.Get()->GetNodeType()) + if (ogrCurrentLayer!=NULL && ogrFeatures.size()>0) { - case ROOT: - { - break; - } - case DOCUMENT: - { - if(ogrCurrentLayer!=NULL && ogrFeatures.size()>0) - { - std::vector<OGRFeature*>::iterator fIt = ogrFeatures.begin(); - - while(fIt!=ogrFeatures.end()) - { - if(ogrCurrentLayer->CreateFeature(*fIt) != OGRERR_NONE) - { - itkExceptionMacro(<<"Failed to create ogr feature in file "<<this->m_FileName); - } - OGRFeature::DestroyFeature(*fIt); - ++fIt; - } - } - ogrFeatures.clear(); - //TODO georeference here from OGRSpatialReference http://www.gdal.org/ogr/classOGRDataSource.html - if (projectionInformationAvailable) - { - oSRS = new OGRSpatialReference(projectionRefWkt.c_str()); - } + std::vector<OGRFeature*>::iterator fIt = ogrFeatures.begin(); - ogrCurrentLayer = m_DataSource->CreateLayer(it.Get()->GetNodeId(),oSRS,wkbUnknown,NULL); - if(ogrCurrentLayer == NULL) - { - itkExceptionMacro(<<"Failed to create layer "<<it.Get()->GetNodeId()); - } - break; - } - case FOLDER: + while (fIt!=ogrFeatures.end()) { - if(ogrCurrentLayer!=NULL && ogrCollection != NULL && !ogrFeatures.empty()) + if (ogrCurrentLayer->CreateFeature(*fIt) != OGRERR_NONE) { - ogrFeatures.back()->SetGeometry(ogrCollection); - delete ogrCollection; - ogrCollection = NULL; + itkExceptionMacro(<<"Failed to create ogr feature in file "<<this->m_FileName); } + OGRFeature::DestroyFeature(*fIt); + ++fIt; + } + } + ogrFeatures.clear(); + //TODO georeference here from OGRSpatialReference http://www.gdal.org/ogr/classOGRDataSource.html + if (projectionInformationAvailable) + { + oSRS = new OGRSpatialReference(projectionRefWkt.c_str()); + } - ogrFeatures.push_back(OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn())); - ogrFeatures.back()->SetField("Name",it.Get()->GetNodeId()); + ogrCurrentLayer = m_DataSource->CreateLayer(it.Get()->GetNodeId(),oSRS,wkbUnknown,NULL); + if (ogrCurrentLayer == NULL) + { + itkExceptionMacro(<<"Failed to create layer "<<it.Get()->GetNodeId()); + } + break; + } + case FOLDER: + { + if (ogrCurrentLayer!=NULL && ogrCollection != NULL && !ogrFeatures.empty()) + { + ogrFeatures.back()->SetGeometry(ogrCollection); + delete ogrCollection; + ogrCollection = NULL; + } - break; - } - case FEATURE_POINT: - { - OGRPoint ogrPoint; - ogrPoint.setX(it.Get()->GetPoint()[0]); - ogrPoint.setY(it.Get()->GetPoint()[1]); + ogrFeatures.push_back(OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn())); + ogrFeatures.back()->SetField("Name",it.Get()->GetNodeId()); + break; + } + case FEATURE_POINT: + { + OGRPoint ogrPoint; + ogrPoint.setX(it.Get()->GetPoint()[0]); + ogrPoint.setY(it.Get()->GetPoint()[1]); - if(DataNodeType::Dimension>2) - { - ogrPoint.setZ(it.Get()->GetPoint()[2]); - } - if(ogrCollection == NULL) - { - if(ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating FEATURE_POINT: ogrFeatures is not initialized."); - } - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbPoint); - ogrFeatures.back()->SetGeometry(&ogrPoint); - } - else - { - ogrCollection->addGeometry(&ogrPoint); - } + if (DataNodeType::Dimension>2) + { + ogrPoint.setZ(it.Get()->GetPoint()[2]); + } - break; - } - case FEATURE_LINE: + if (ogrCollection == NULL) + { + if (ogrFeatures.empty()) { - OGRLineString ogrLine; - VertexListConstPointerType vertexList = it.Get()->GetLine()->GetVertexList(); - - typename VertexListType::ConstIterator vIt = vertexList->Begin(); + itkExceptionMacro(<<"Problem while creating FEATURE_POINT: ogrFeatures is not initialized."); + } + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbPoint); + ogrFeatures.back()->SetGeometry(&ogrPoint); + } + else + { + ogrCollection->addGeometry(&ogrPoint); + } - while(vIt != vertexList->End()) - { - OGRPoint ogrPoint; - ogrPoint.setX(vIt.Value()[0]); - ogrPoint.setY(vIt.Value()[1]); - if(DataNodeType::Dimension>2) - { - ogrPoint.setZ(vIt.Value()[2]); - } - ogrLine.addPoint(&ogrPoint); - ++vIt; - } + break; + } + case FEATURE_LINE: + { + OGRLineString ogrLine; + VertexListConstPointerType vertexList = it.Get()->GetLine()->GetVertexList(); - if(ogrCollection == NULL) - { - if(ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating FEATURE_LINE: ogrFeatures is not initialized."); - } - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbLineString); - ogrFeatures.back()->SetGeometry(&ogrLine); - } - else - { - ogrCollection->addGeometry(&ogrLine); - } + typename VertexListType::ConstIterator vIt = vertexList->Begin(); - break; + while (vIt != vertexList->End()) + { + OGRPoint ogrPoint; + ogrPoint.setX(vIt.Value()[0]); + ogrPoint.setY(vIt.Value()[1]); + if (DataNodeType::Dimension>2) + { + ogrPoint.setZ(vIt.Value()[2]); } - case FEATURE_POLYGON: + ogrLine.addPoint(&ogrPoint); + ++vIt; + } + + if (ogrCollection == NULL) + { + if (ogrFeatures.empty()) { - OGRPolygon * ogrPolygon = new OGRPolygon(); - OGRLinearRing * ogrExternalRing = new OGRLinearRing(); - VertexListConstPointerType vertexList = it.Get()->GetPolygonExteriorRing()->GetVertexList(); + itkExceptionMacro(<<"Problem while creating FEATURE_LINE: ogrFeatures is not initialized."); + } + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbLineString); + ogrFeatures.back()->SetGeometry(&ogrLine); + } + else + { + ogrCollection->addGeometry(&ogrLine); + } - typename VertexListType::ConstIterator vIt = vertexList->Begin(); + break; + } + case FEATURE_POLYGON: + { + OGRPolygon * ogrPolygon = new OGRPolygon(); + OGRLinearRing * ogrExternalRing = new OGRLinearRing(); + VertexListConstPointerType vertexList = it.Get()->GetPolygonExteriorRing()->GetVertexList(); - while(vIt != vertexList->End()) - { - OGRPoint ogrPoint; - ogrPoint.setX(vIt.Value()[0]); - ogrPoint.setY(vIt.Value()[1]); - if(DataNodeType::Dimension>2) - { - ogrPoint.setZ(vIt.Value()[2]); - } + typename VertexListType::ConstIterator vIt = vertexList->Begin(); - ogrExternalRing->addPoint(&ogrPoint); - ++vIt; - } - ogrPolygon->addRing(ogrExternalRing); - delete ogrExternalRing; + while (vIt != vertexList->End()) + { + OGRPoint ogrPoint; + ogrPoint.setX(vIt.Value()[0]); + ogrPoint.setY(vIt.Value()[1]); + if (DataNodeType::Dimension>2) + { + ogrPoint.setZ(vIt.Value()[2]); + } - // Retrieving internal rings as well - for(typename PolygonListType::Iterator pIt = it.Get()->GetPolygonInteriorRings()->Begin(); - pIt!=it.Get()->GetPolygonInteriorRings()->End();++pIt) - { - OGRLinearRing * ogrInternalRing = new OGRLinearRing(); - vertexList = pIt.Get()->GetVertexList(); - vIt = vertexList->Begin(); + ogrExternalRing->addPoint(&ogrPoint); + ++vIt; + } + ogrPolygon->addRing(ogrExternalRing); + delete ogrExternalRing; - while(vIt != vertexList->End()) - { - OGRPoint ogrPoint; - ogrPoint.setX(vIt.Value()[0]); - ogrPoint.setY(vIt.Value()[1]); - if(DataNodeType::Dimension>2) - { - ogrPoint.setZ(vIt.Value()[2]); - } - ogrInternalRing->addPoint(&ogrPoint); - ++vIt; - } - ogrPolygon->addRing(ogrInternalRing); - delete ogrInternalRing; - } - if(ogrCollection == NULL) - { - if(ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating FEATURE_POLYGON: ogrFeatures is not initialized."); - } - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbPolygon); - ogrFeatures.back()->SetGeometry(ogrPolygon); - } - else - { - ogrCollection->addGeometry(ogrPolygon); - } + // Retrieving internal rings as well + for (typename PolygonListType::Iterator pIt = it.Get()->GetPolygonInteriorRings()->Begin(); + pIt!=it.Get()->GetPolygonInteriorRings()->End();++pIt) + { + OGRLinearRing * ogrInternalRing = new OGRLinearRing(); + vertexList = pIt.Get()->GetVertexList(); + vIt = vertexList->Begin(); - delete ogrPolygon; - break; - } - case FEATURE_MULTIPOINT: + while (vIt != vertexList->End()) { - if(ogrCollection != NULL || ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating multipoint."); - } - ogrCollection = new OGRMultiPoint(); - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiPoint); - break; - } - case FEATURE_MULTILINE: - { - if(ogrCollection != NULL || ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating multiline."); - } - ogrCollection = new OGRMultiLineString(); - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiLineString); - break; - } - case FEATURE_MULTIPOLYGON: - { - if(ogrCollection != NULL || ogrFeatures.empty()) + OGRPoint ogrPoint; + ogrPoint.setX(vIt.Value()[0]); + ogrPoint.setY(vIt.Value()[1]); + if (DataNodeType::Dimension>2) { - itkExceptionMacro(<<"Problem while creating multipolygon."); + ogrPoint.setZ(vIt.Value()[2]); } - ogrCollection = new OGRMultiPolygon(); - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiPolygon); - break; + ogrInternalRing->addPoint(&ogrPoint); + ++vIt; } - case FEATURE_COLLECTION: + ogrPolygon->addRing(ogrInternalRing); + delete ogrInternalRing; + } + if (ogrCollection == NULL) + { + if (ogrFeatures.empty()) { - if(ogrCollection != NULL || ogrFeatures.empty()) - { - itkExceptionMacro(<<"Problem while creating collection."); - } - ogrCollection = new OGRMultiPoint(); - ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbGeometryCollection); - break; + itkExceptionMacro(<<"Problem while creating FEATURE_POLYGON: ogrFeatures is not initialized."); } + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbPolygon); + ogrFeatures.back()->SetGeometry(ogrPolygon); } - ++it; + else + { + ogrCollection->addGeometry(ogrPolygon); + } + + delete ogrPolygon; + break; } - if(ogrCurrentLayer!=NULL && ogrCollection != NULL && !ogrFeatures.empty()) + case FEATURE_MULTIPOINT: { - ogrFeatures.back()->SetGeometry(ogrCollection); - delete ogrCollection; - ogrCollection = NULL; + if (ogrCollection != NULL || ogrFeatures.empty()) + { + itkExceptionMacro(<<"Problem while creating multipoint."); + } + ogrCollection = new OGRMultiPoint(); + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiPoint); + break; } - - if(ogrCurrentLayer!=NULL && ogrFeatures.size()>0) + case FEATURE_MULTILINE: { - std::vector<OGRFeature*>::iterator fIt = ogrFeatures.begin(); - - while(fIt!=ogrFeatures.end()) + if (ogrCollection != NULL || ogrFeatures.empty()) { - if(ogrCurrentLayer->CreateFeature(*fIt) != OGRERR_NONE) - { - itkExceptionMacro(<<"Failed to create ogr feature in file "<<this->m_FileName); - } - OGRFeature::DestroyFeature(*fIt); - ++fIt; + itkExceptionMacro(<<"Problem while creating multiline."); + } + ogrCollection = new OGRMultiLineString(); + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiLineString); + break; + } + case FEATURE_MULTIPOLYGON: + { + if (ogrCollection != NULL || ogrFeatures.empty()) + { + itkExceptionMacro(<<"Problem while creating multipolygon."); + } + ogrCollection = new OGRMultiPolygon(); + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbMultiPolygon); + break; + } + case FEATURE_COLLECTION: + { + if (ogrCollection != NULL || ogrFeatures.empty()) + { + itkExceptionMacro(<<"Problem while creating collection."); } + ogrCollection = new OGRMultiPoint(); + ogrFeatures.back()->GetDefnRef()->SetGeomType(wkbGeometryCollection); + break; } - ogrFeatures.clear(); + } + ++it; + } + if (ogrCurrentLayer!=NULL && ogrCollection != NULL && !ogrFeatures.empty()) + { + ogrFeatures.back()->SetGeometry(ogrCollection); + delete ogrCollection; + ogrCollection = NULL; + } + + if (ogrCurrentLayer!=NULL && ogrFeatures.size()>0) + { + std::vector<OGRFeature*>::iterator fIt = ogrFeatures.begin(); - otbMsgDevMacro( <<" SHPVectorDataIO::Write() "); + while (fIt!=ogrFeatures.end()) + { + if (ogrCurrentLayer->CreateFeature(*fIt) != OGRERR_NONE) + { + itkExceptionMacro(<<"Failed to create ogr feature in file "<<this->m_FileName); + } + OGRFeature::DestroyFeature(*fIt); + ++fIt; + } } + ogrFeatures.clear(); + + otbMsgDevMacro( <<" SHPVectorDataIO::Write() "); +} - } // end namespace otb +} // end namespace otb #endif diff --git a/Code/IO/otbSpatialObjectDXFReader.h b/Code/IO/otbSpatialObjectDXFReader.h index eb47926c387acfc78f3bde9f52a011e0884a8680..8cf6b6effbb49bd2eeb33cb447d81e38e7bc4924 100644 --- a/Code/IO/otbSpatialObjectDXFReader.h +++ b/Code/IO/otbSpatialObjectDXFReader.h @@ -23,19 +23,19 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SpatialObjectDXFReader - * \brief This class reads the DXF file format to SpatialObjects. - * - * \ingroup ObjectSource - * - * \example IO/DXFReaderExample.cxx - * - */ +/** \class SpatialObjectDXFReader + * \brief This class reads the DXF file format to SpatialObjects. + * + * \ingroup ObjectSource + * + * \example IO/DXFReaderExample.cxx + * + */ template <class TSpatialObject> class ITK_EXPORT SpatialObjectDXFReader - : public SpatialObjectSource< TSpatialObject > + : public SpatialObjectSource< TSpatialObject > { - public: +public: typedef SpatialObjectDXFReader Self; typedef SpatialObjectSource<TSpatialObject> Superclass; typedef itk::SmartPointer<Self> Pointer; @@ -47,9 +47,9 @@ class ITK_EXPORT SpatialObjectDXFReader /** Run-time type information (and related methods). */ itkTypeMacro(SpatialObjectDXFReader, SpatialObjectSource); - /** Superclass Typedefs */ - typedef TSpatialObject GroupSpatialObjectType; - typedef typename GroupSpatialObjectType::Pointer GroupSpatialObjectPointerType; + /** Superclass Typedefs */ + typedef TSpatialObject GroupSpatialObjectType; + typedef typename GroupSpatialObjectType::Pointer GroupSpatialObjectPointerType; /** Set the filename */ void SetFileName(char * filename); @@ -57,24 +57,24 @@ class ITK_EXPORT SpatialObjectDXFReader /** Get the filename */ itkGetStringMacro(FileName); - /** Set The layer name */ - itkSetStringMacro(LayerName); + /** Set The layer name */ + itkSetStringMacro(LayerName); - /** Get The layer name */ - itkGetStringMacro(LayerName); + /** Get The layer name */ + itkGetStringMacro(LayerName); - /** Workaround while waiting for the SpatialObject bug to be fixed */ - virtual void Update(void); + /** Workaround while waiting for the SpatialObject bug to be fixed */ + virtual void Update(void); - protected: - /** Constructor */ +protected: + /** Constructor */ SpatialObjectDXFReader(); - /** Destructor */ + /** Destructor */ ~SpatialObjectDXFReader(); /** Main computation method */ virtual void GenerateData(); - private: +private: SpatialObjectDXFReader(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/IO/otbSpatialObjectDXFReader.txx b/Code/IO/otbSpatialObjectDXFReader.txx index 550e709e327b2e952406e025d3c3bbcf5c748a25..f8fd3f4e39656b42364ebd86128a609621f6279b 100644 --- a/Code/IO/otbSpatialObjectDXFReader.txx +++ b/Code/IO/otbSpatialObjectDXFReader.txx @@ -58,49 +58,49 @@ SpatialObjectDXFReader<TSpatialObject> m_FileName = filename; this->Modified(); } - /** Test whether the given filename exist and it is readable, - this is intended to be called before attempting to use - ImageIO classes for actually reading the file. If the file - doesn't exist or it is not readable, and exception with an - approriate message will be thrown. */ +/** Test whether the given filename exist and it is readable, + this is intended to be called before attempting to use + ImageIO classes for actually reading the file. If the file + doesn't exist or it is not readable, and exception with an + approriate message will be thrown. */ template <class TSpatialObject> void SpatialObjectDXFReader<TSpatialObject> ::TestFileExistanceAndReadability() { - // Test if the file exists. - if( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) - { - itk::ImageFileReaderException e(__FILE__, __LINE__); + // Test if the file exists. + if ( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) + { + itk::ImageFileReaderException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg <<"The file doesn't exists. " + << std::endl << "Filename = " << this->m_FileName + << std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; + } + + // Test if the file can be open for reading access. + //Only if m_FileName speciy a filname (not a dirname) + if ( System::IsAFileName( this->m_FileName ) == true ) + { + std::ifstream readTester; + readTester.open( this->m_FileName.c_str() ); + if ( readTester.fail() ) + { + readTester.close(); itk::OStringStream msg; - msg <<"The file doesn't exists. " - << std::endl << "Filename = " << this->m_FileName - << std::endl; - e.SetDescription(msg.str().c_str()); + msg <<"The file couldn't be opened for reading. " + << std::endl << "Filename: " << this->m_FileName + << std::endl; + itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); throw e; return; - } - - // Test if the file can be open for reading access. - //Only if m_FileName speciy a filname (not a dirname) - if( System::IsAFileName( this->m_FileName ) == true ) - { - std::ifstream readTester; - readTester.open( this->m_FileName.c_str() ); - if( readTester.fail() ) - { - readTester.close(); - itk::OStringStream msg; - msg <<"The file couldn't be opened for reading. " - << std::endl << "Filename: " << this->m_FileName - << std::endl; - itk::ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); - throw e; - return; - } - readTester.close(); } + readTester.close(); + } } /** @@ -115,9 +115,9 @@ SpatialObjectDXFReader<TSpatialObject> typedef otb::DXFToSpatialObjectGroupFilter<TSpatialObject> CreationFilter; typename CreationFilter::Pointer creationClass = CreationFilter::New(); if (m_LayerName.size()>0) - { - creationClass->SetLayer(m_LayerName.c_str()); - } + { + creationClass->SetLayer(m_LayerName.c_str()); + } DL_Dxf dxf; dxf.in(m_FileName, creationClass); GroupSpatialObjectType * group = creationClass->GetOutput(); diff --git a/Code/IO/otbStreamingImageFileWriter.h b/Code/IO/otbStreamingImageFileWriter.h index 74f7f16dc712cd191daa56bcafa42b204b30bdac..148d9324f88d8419373a98292862918f4fc8ea66 100644 --- a/Code/IO/otbStreamingImageFileWriter.h +++ b/Code/IO/otbStreamingImageFileWriter.h @@ -138,11 +138,11 @@ public: * \param filename the name of the file. */ virtual void SetFileName(std::string filename) - { - m_FileName = filename; - m_ImageIO = NULL; - this->Modified(); - } + { + m_FileName = filename; + m_ImageIO = NULL; + this->Modified(); + } /** Specify the region to write. If left NULL, then the whole image @@ -206,7 +206,7 @@ private: itk::ImageIORegion m_IORegion; bool m_UserSpecifiedIORegion; // - //track whether the region is user specified + //track whether the region is user specified bool m_FactorySpecifiedImageIO; //track whether the factory mechanism set the ImageIO bool m_UseCompression; bool m_UseInputMetaDataDictionary; // whether to use the MetaDataDictionary from the input or not. diff --git a/Code/IO/otbStreamingImageFileWriter.txx b/Code/IO/otbStreamingImageFileWriter.txx index f4324a67dad2d48c67b9b8d60002c3a4e4b36845..e7e6562ca873e7e59e66546f00796c8f313eef07 100644 --- a/Code/IO/otbStreamingImageFileWriter.txx +++ b/Code/IO/otbStreamingImageFileWriter.txx @@ -72,8 +72,8 @@ void StreamingImageFileWriter<TInputImage> ::SetBufferMemorySize(unsigned long memory_size_divisions) { - m_BufferMemorySize = memory_size_divisions; - m_CalculationDivision = SET_BUFFER_MEMORY_SIZE; + m_BufferMemorySize = memory_size_divisions; + m_CalculationDivision = SET_BUFFER_MEMORY_SIZE; this->Modified(); } @@ -85,8 +85,8 @@ void StreamingImageFileWriter<TInputImage> ::SetBufferNumberOfLinesDivisions(unsigned long nb_lines_divisions) { - m_BufferNumberOfLinesDivisions = nb_lines_divisions; - m_CalculationDivision = SET_BUFFER_NUMBER_OF_LINES; + m_BufferNumberOfLinesDivisions = nb_lines_divisions; + m_CalculationDivision = SET_BUFFER_NUMBER_OF_LINES; this->Modified(); } @@ -98,8 +98,8 @@ void StreamingImageFileWriter<TInputImage> ::SetNumberOfStreamDivisions(unsigned long nb_divisions) { - m_NumberOfStreamDivisions = nb_divisions; - m_CalculationDivision = SET_NUMBER_OF_STREAM_DIVISIONS; + m_NumberOfStreamDivisions = nb_divisions; + m_CalculationDivision = SET_NUMBER_OF_STREAM_DIVISIONS; this->Modified(); } @@ -111,8 +111,8 @@ void StreamingImageFileWriter<TInputImage> ::SetAutomaticNumberOfStreamDivisions(void) { - m_CalculationDivision = SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS; - this->Modified(); + m_CalculationDivision = SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS; + this->Modified(); } /** @@ -123,8 +123,8 @@ void StreamingImageFileWriter<TInputImage> ::SetTilingStreamDivisions(void) { - m_CalculationDivision = SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS; - m_RegionSplitter = itk::ImageRegionMultidimensionalSplitter<InputImageDimension>::New(); + m_CalculationDivision = SET_TILING_WITH_SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS; + m_RegionSplitter = itk::ImageRegionMultidimensionalSplitter<InputImageDimension>::New(); this->Modified(); } @@ -133,9 +133,9 @@ void StreamingImageFileWriter<TInputImage> ::SetTilingStreamDivisions(unsigned long nb_divisions) { - m_CalculationDivision = SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS; - m_NumberOfStreamDivisions = nb_divisions; - m_RegionSplitter = itk::ImageRegionMultidimensionalSplitter<InputImageDimension>::New(); + m_CalculationDivision = SET_TILING_WITH_SET_NUMBER_OF_STREAM_DIVISIONS; + m_NumberOfStreamDivisions = nb_divisions; + m_RegionSplitter = itk::ImageRegionMultidimensionalSplitter<InputImageDimension>::New(); this->Modified(); } @@ -147,7 +147,7 @@ unsigned long StreamingImageFileWriter<TInputImage> ::GetNumberOfStreamDivisions(void) { - return(CalculateNumberOfStreamDivisions()); + return(CalculateNumberOfStreamDivisions()); } /** @@ -172,59 +172,59 @@ StreamingImageFileWriter<TInputImage> Superclass::PrintSelf(os,indent); os << indent << "File Name: " - << (m_FileName.data() ? m_FileName.data() : "(none)") << std::endl; + << (m_FileName.data() ? m_FileName.data() : "(none)") << std::endl; os << indent << "Image IO: "; if ( m_ImageIO.IsNull() ) - { + { os << "(none)\n"; - } + } else - { + { os << m_ImageIO << "\n"; - } + } os << indent << "IO Region: " << m_IORegion << "\n"; if (m_UseCompression) - { + { os << indent << "Compression: On\n"; - } + } else - { + { os << indent << "Compression: Off\n"; - } + } if (m_UseInputMetaDataDictionary) - { + { os << indent << "UseInputMetaDataDictionary: On\n"; - } + } else - { + { os << indent << "UseInputMetaDataDictionary: Off\n"; - } + } if (m_FactorySpecifiedImageIO) - { + { os << indent << "FactorySpecifiedmageIO: On\n"; - } + } else - { + { os << indent << "FactorySpecifiedmageIO: Off\n"; - } + } os << indent << "Number of stream divisions: " << m_NumberOfStreamDivisions - << std::endl; + << std::endl; if (m_RegionSplitter) - { + { os << indent << "Region splitter:" << m_RegionSplitter << std::endl; - } + } else - { + { os << indent << "Region splitter: (none)" << std::endl; - } + } } //--------------------------------------------------------- @@ -235,11 +235,11 @@ StreamingImageFileWriter<TInputImage> { itkDebugMacro("setting IORegion to " << region ); if ( m_IORegion != region) - { + { m_IORegion = region; this->Modified(); m_UserSpecifiedIORegion = true; - } + } } /** @@ -251,14 +251,14 @@ StreamingImageFileWriter<TInputImage> ::CalculateNumberOfStreamDivisions(void) { - return StreamingTraitsType - ::CalculateNumberOfStreamDivisions(this->GetInput(), - this->GetInput()->GetLargestPossibleRegion(), - m_RegionSplitter, - m_CalculationDivision, - m_NumberOfStreamDivisions, - m_BufferMemorySize, - m_BufferNumberOfLinesDivisions); + return StreamingTraitsType + ::CalculateNumberOfStreamDivisions(this->GetInput(), + this->GetInput()->GetLargestPossibleRegion(), + m_RegionSplitter, + m_CalculationDivision, + m_NumberOfStreamDivisions, + m_BufferMemorySize, + m_BufferNumberOfLinesDivisions); } @@ -277,9 +277,9 @@ StreamingImageFileWriter<TInputImage> * prevent chasing our tail */ if (this->m_Updating) - { + { return; - } + } /** @@ -292,10 +292,10 @@ StreamingImageFileWriter<TInputImage> */ unsigned int ninputs = this->GetNumberOfValidRequiredInputs(); if (ninputs < this->GetNumberOfRequiredInputs()) - { + { itkExceptionMacro(<< "At least " << static_cast<unsigned int>( this->GetNumberOfRequiredInputs() ) << " inputs are required but only " << ninputs << " are specified."); return; - } + } this->SetAbortGenerateData(0); this->SetProgress(0.0); this->m_Updating = true; @@ -317,56 +317,56 @@ StreamingImageFileWriter<TInputImage> // Make sure that we can write the file given the name // if ( m_FileName == "" ) - { + { itkExceptionMacro(<<"No filename was specified"); - } + } if ( m_ImageIO.IsNull() ) //try creating via factory - { + { itkDebugMacro(<<"Attempting factory creation of ImageIO for file: " << m_FileName); this->SetImageIO( ImageIOFactory::CreateImageIO( m_FileName.c_str(), - itk::ImageIOFactory::WriteMode ) ); + itk::ImageIOFactory::WriteMode ) ); -/* m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), - itk::ImageIOFactory::WriteMode );*/ + /* m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), + itk::ImageIOFactory::WriteMode );*/ m_FactorySpecifiedImageIO = true; - } + } else + { + if ( m_FactorySpecifiedImageIO && !m_ImageIO->CanWriteFile( m_FileName.c_str() ) ) { - if( m_FactorySpecifiedImageIO && !m_ImageIO->CanWriteFile( m_FileName.c_str() ) ) - { itkDebugMacro(<<"ImageIO exists but doesn't know how to write file:" << m_FileName ); itkDebugMacro(<<"Attempting creation of ImageIO with a factory for file:" << m_FileName); m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), - itk::ImageIOFactory::WriteMode ); + itk::ImageIOFactory::WriteMode ); m_FactorySpecifiedImageIO = true; - } } + } if ( m_ImageIO.IsNull() ) - { + { itk::ImageFileWriterException e(__FILE__, __LINE__); itk::OStringStream msg; msg << " Could not create IO object for file " - << m_FileName.c_str() << std::endl; + << m_FileName.c_str() << std::endl; msg << " Tried to create one of the following:" << std::endl; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); - for(std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { itk::ImageIOBase* io = dynamic_cast<itk::ImageIOBase*>(i->GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; - } + } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; e.SetDescription(msg.str().c_str()); e.SetLocation(ITK_LOCATION); throw e; - } + } /** End of Prepare ImageIO : create ImageFactory */ @@ -385,32 +385,32 @@ StreamingImageFileWriter<TInputImage> unsigned int numDivisions; /** Control if the ImageIO is CanStreamWrite */ - if( m_ImageIO->CanStreamWrite() == false ) - { - otbMsgDebugMacro(<<"WARNING : The ImageFactory selected for the image file <"<<m_FileName.c_str()<<"> is not StreamWrite. So, the streaming method is not use."); - numDivisions = 1; - } - else if( inputPtr->GetBufferedRegion() == inputPtr->GetLargestPossibleRegion()) - { - otbMsgDebugMacro(<<"WARNING : Buffered region is the largest possible region, there is no need for streaming."); - numDivisions = 1; - - } - else - { - numDivisions = static_cast<unsigned int>(CalculateNumberOfStreamDivisions()); -/* - otbDebugMacro(<< "NumberOfStreamDivisions : " << numDivisions); - numDivisionsFromSplitter = m_RegionSplitter->GetNumberOfSplits(outputRegion, numDivisions); - otbDebugMacro(<< "NumberOfStreamSplitterDivisions : " << numDivisionsFromSplitter); - - // In tiling streaming mode, we keep the number of divisions calculed by splitter - if ((numDivisionsFromSplitter < numDivisions)||(m_CalculationDivision==SET_TILING_STREAM_DIVISIONS)) - { - numDivisions = numDivisionsFromSplitter; - } -*/ - } + if ( m_ImageIO->CanStreamWrite() == false ) + { + otbMsgDebugMacro(<<"WARNING : The ImageFactory selected for the image file <"<<m_FileName.c_str()<<"> is not StreamWrite. So, the streaming method is not use."); + numDivisions = 1; + } + else if ( inputPtr->GetBufferedRegion() == inputPtr->GetLargestPossibleRegion()) + { + otbMsgDebugMacro(<<"WARNING : Buffered region is the largest possible region, there is no need for streaming."); + numDivisions = 1; + + } + else + { + numDivisions = static_cast<unsigned int>(CalculateNumberOfStreamDivisions()); + /* + otbDebugMacro(<< "NumberOfStreamDivisions : " << numDivisions); + numDivisionsFromSplitter = m_RegionSplitter->GetNumberOfSplits(outputRegion, numDivisions); + otbDebugMacro(<< "NumberOfStreamSplitterDivisions : " << numDivisionsFromSplitter); + + // In tiling streaming mode, we keep the number of divisions calculed by splitter + if ((numDivisionsFromSplitter < numDivisions)||(m_CalculationDivision==SET_TILING_STREAM_DIVISIONS)) + { + numDivisions = numDivisionsFromSplitter; + } + */ + } /** * Loop over the number of pieces, execute the upstream pipeline on each @@ -426,8 +426,8 @@ StreamingImageFileWriter<TInputImage> const typename TInputImage::PointType& origin = outputPtr->GetOrigin(); const typename TInputImage::DirectionType& direction = outputPtr->GetDirection(); - for(unsigned int i=0; i<TInputImage::ImageDimension; i++) - { + for (unsigned int i=0; i<TInputImage::ImageDimension; i++) + { // Final image size m_ImageIO->SetDimensions(i,outputRegion.GetSize(i)); m_ImageIO->SetSpacing(i,spacing[i]); @@ -435,22 +435,22 @@ StreamingImageFileWriter<TInputImage> vnl_vector< double > axisDirection(TInputImage::ImageDimension); // Please note: direction cosines are stored as columns of the // direction matrix - for(unsigned int j=0; j<TInputImage::ImageDimension; j++) - { + for (unsigned int j=0; j<TInputImage::ImageDimension; j++) + { axisDirection[j] = direction[j][i]; - } - m_ImageIO->SetDirection( i, axisDirection ); } + m_ImageIO->SetDirection( i, axisDirection ); + } m_ImageIO->SetUseCompression(m_UseCompression); m_ImageIO->SetMetaDataDictionary(inputPtr->GetMetaDataDictionary()); - /** Create Image file */ - // Setup the image IO for writing. - // - m_ImageIO->SetFileName(m_FileName.c_str()); - m_ImageIO->WriteImageInformation(); + /** Create Image file */ + // Setup the image IO for writing. + // + m_ImageIO->SetFileName(m_FileName.c_str()); + m_ImageIO->WriteImageInformation(); /** @@ -468,46 +468,46 @@ StreamingImageFileWriter<TInputImage> for (piece = 0; piece < numDivisions && !this->GetAbortGenerateData(); piece++) - { - streamRegion = m_RegionSplitter->GetSplit(piece, numDivisions, - outputRegion); + { + streamRegion = m_RegionSplitter->GetSplit(piece, numDivisions, + outputRegion); otbMsgDebugMacro(<<"Piece : " << piece ); otbMsgDebugMacro(<<"RegionSplit : Index(" << streamRegion.GetIndex()[0] - << "," << streamRegion.GetIndex()[1] - << ") Size(" << streamRegion.GetSize()[0] - << "," << streamRegion.GetSize()[1] << ")"); + << "," << streamRegion.GetIndex()[1] + << ") Size(" << streamRegion.GetSize()[0] + << "," << streamRegion.GetSize()[1] << ")"); - inputPtr->SetRequestedRegion(streamRegion); - inputPtr->PropagateRequestedRegion(); - inputPtr->UpdateOutputData(); + inputPtr->SetRequestedRegion(streamRegion); + inputPtr->PropagateRequestedRegion(); + inputPtr->UpdateOutputData(); - // Write the whole image - itk::ImageIORegion ioRegion(TInputImage::ImageDimension); - for(unsigned int i=0; i<TInputImage::ImageDimension; i++) - { - ioRegion.SetSize(i,streamRegion.GetSize(i)); - ioRegion.SetIndex(i,streamRegion.GetIndex(i)); - } - this->SetIORegion( ioRegion ); - m_ImageIO->SetIORegion(m_IORegion); + // Write the whole image + itk::ImageIORegion ioRegion(TInputImage::ImageDimension); + for (unsigned int i=0; i<TInputImage::ImageDimension; i++) + { + ioRegion.SetSize(i,streamRegion.GetSize(i)); + ioRegion.SetIndex(i,streamRegion.GetIndex(i)); + } + this->SetIORegion( ioRegion ); + m_ImageIO->SetIORegion(m_IORegion); - // Start writing streamregion in the image file - this->GenerateData(); + // Start writing streamregion in the image file + this->GenerateData(); - this->UpdateProgress((float) piece / numDivisions ); - } + this->UpdateProgress((float) piece / numDivisions ); + } /** * If we ended due to aborting, push the progress up to 1.0 (since * it probably didn't end there) */ if ( !this->GetAbortGenerateData() ) - { + { this->UpdateProgress(1.0); - } + } // Notify end event observers this->InvokeEvent( itk::EndEvent() ); @@ -516,12 +516,12 @@ StreamingImageFileWriter<TInputImage> * Now we have to mark the data as up to data. */ for (idx = 0; idx < this->GetNumberOfOutputs(); ++idx) - { + { if (this->GetOutput(idx)) - { + { this->GetOutput(idx)->DataHasBeenGenerated(); - } } + } /** * Release any inputs if marked for release @@ -543,27 +543,27 @@ void StreamingImageFileWriter<TInputImage> ::GenerateData(void) { - // otbGenericMsgDebugMacro(<< "TEST GenerateData"); +// otbGenericMsgDebugMacro(<< "TEST GenerateData"); - const InputImageType * input = this->GetInput(); + const InputImageType * input = this->GetInput(); // Make sure that the image is the right type and no more than // four components. typedef typename InputImageType::PixelType ScalarType; - if( strcmp( input->GetNameOfClass(), "VectorImage" ) == 0 ) - { + if ( strcmp( input->GetNameOfClass(), "VectorImage" ) == 0 ) + { typedef typename InputImageType::InternalPixelType VectorImageScalarType; m_ImageIO->SetPixelTypeInfo( typeid(VectorImageScalarType) ); typedef typename InputImageType::AccessorFunctorType AccessorFunctorType; m_ImageIO->SetNumberOfComponents( AccessorFunctorType::GetVectorLength(input) ); - } + } else - { + { // Set the pixel and component type; the number of components. m_ImageIO->SetPixelTypeInfo(typeid(ScalarType)); - } + } // Setup the image IO for writing. // diff --git a/Code/IO/otbStreamingImageVirtualWriter.h b/Code/IO/otbStreamingImageVirtualWriter.h index 42c22572901f6c62479b49ac72df1d0241e70c27..0c5e3c5dbc2204b2bfa67bcdad4435b4781c1b6f 100644 --- a/Code/IO/otbStreamingImageVirtualWriter.h +++ b/Code/IO/otbStreamingImageVirtualWriter.h @@ -46,7 +46,7 @@ namespace otb * \sa PersistentImageStreamingDecorator. */ template <class TInputImage> - class ITK_EXPORT StreamingImageVirtualWriter : public itk::ImageToImageFilter<TInputImage,TInputImage> +class ITK_EXPORT StreamingImageVirtualWriter : public itk::ImageToImageFilter<TInputImage,TInputImage> { public: /** Standard class typedefs. */ diff --git a/Code/IO/otbStreamingImageVirtualWriter.txx b/Code/IO/otbStreamingImageVirtualWriter.txx index f1cf861341badbcb0dae4535687212ef3e700da1..aa83620596c053560155f573ee64172eacb76ef1 100644 --- a/Code/IO/otbStreamingImageVirtualWriter.txx +++ b/Code/IO/otbStreamingImageVirtualWriter.txx @@ -105,7 +105,7 @@ StreamingImageVirtualWriter<TInputImage> ::SetAutomaticNumberOfStreamDivisions(void) { m_CalculationDivision = SET_AUTOMATIC_NUMBER_OF_STREAM_DIVISIONS; - this->Modified(); + this->Modified(); } /** @@ -139,7 +139,7 @@ StreamingImageVirtualWriter<TInputImage> { // ProcessObject is not const_correct so this cast is required here. this->itk::ProcessObject::SetNthInput(0, - const_cast<TInputImage *>(input ) ); + const_cast<TInputImage *>(input ) ); } @@ -150,12 +150,12 @@ StreamingImageVirtualWriter<TInputImage> ::GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<TInputImage*> - (this->itk::ProcessObject::GetInput(0)); + (this->itk::ProcessObject::GetInput(0)); } @@ -197,13 +197,13 @@ StreamingImageVirtualWriter<TInputImage> ::CalculateNumberOfStreamDivisions(void) { return StreamingTraitsType - ::CalculateNumberOfStreamDivisions(this->GetInput(), - this->GetInput()->GetLargestPossibleRegion(), - m_RegionSplitter, - m_CalculationDivision, - m_NumberOfStreamDivisions, - m_BufferMemorySize, - m_BufferNumberOfLinesDivisions); + ::CalculateNumberOfStreamDivisions(this->GetInput(), + this->GetInput()->GetLargestPossibleRegion(), + m_RegionSplitter, + m_CalculationDivision, + m_NumberOfStreamDivisions, + m_BufferMemorySize, + m_BufferNumberOfLinesDivisions); } /** * @@ -225,15 +225,15 @@ StreamingImageVirtualWriter<TInputImage> { Superclass::PrintSelf(os,indent); os << indent << "Number of stream divisions: " << m_NumberOfStreamDivisions - << std::endl; + << std::endl; if (m_RegionSplitter) - { + { os << indent << "Region splitter:" << m_RegionSplitter << std::endl; - } + } else - { + { os << indent << "Region splitter: (none)" << std::endl; - } + } } template<class TInputImage> void @@ -273,21 +273,21 @@ StreamingImageVirtualWriter<TInputImage> for (piece = 0; piece < numDivisions && !this->GetAbortGenerateData(); piece++) - { - streamRegion = m_RegionSplitter->GetSplit(piece, numDivisions,outputRegion); - inputPtr->ReleaseData(); - inputPtr->SetRequestedRegion(streamRegion); - inputPtr->Update(); - this->UpdateProgress((float) piece / numDivisions ); - } + { + streamRegion = m_RegionSplitter->GetSplit(piece, numDivisions,outputRegion); + inputPtr->ReleaseData(); + inputPtr->SetRequestedRegion(streamRegion); + inputPtr->Update(); + this->UpdateProgress((float) piece / numDivisions ); + } /** * If we ended due to aborting, push the progress up to 1.0 (since * it probably didn't end there) */ if ( !this->GetAbortGenerateData() ) - { + { this->UpdateProgress(1.0); - } + } // Notify end event observers this->InvokeEvent( itk::EndEvent() ); @@ -296,12 +296,12 @@ StreamingImageVirtualWriter<TInputImage> * Now we have to mark the data as up to data. */ for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) - { + { if (this->GetOutput(idx)) - { + { this->GetOutput(idx)->DataHasBeenGenerated(); - } } + } /** * Release any inputs if marked for release */ diff --git a/Code/IO/otbTileMapImageIO.cxx b/Code/IO/otbTileMapImageIO.cxx index 052877dcbef24f0fc10b2f8a5378b0dfd15d1a47..37bf0a69c7477d7e30444fab587a3c1d7afcc105 100644 --- a/Code/IO/otbTileMapImageIO.cxx +++ b/Code/IO/otbTileMapImageIO.cxx @@ -51,1330 +51,1338 @@ namespace otb { - TileMapImageIO::TileMapImageIO() - { +TileMapImageIO::TileMapImageIO() +{ // By default set number of dimensions to two. - this->SetNumberOfDimensions(2); + this->SetNumberOfDimensions(2); // By default set pixel type to scalar. - m_PixelType = SCALAR; + m_PixelType = SCALAR; // By default set component type to unsigned char - m_ComponentType = UCHAR; - m_UseCompression = false; - m_CompressionLevel = 4; // Range 0-9; 0 = no file compression, 9 = maximum file compression + m_ComponentType = UCHAR; + m_UseCompression = false; + m_CompressionLevel = 4; // Range 0-9; 0 = no file compression, 9 = maximum file compression // Set default spacing to one - m_Spacing[0] = 1.0; - m_Spacing[1] = 1.0; + m_Spacing[0] = 1.0; + m_Spacing[1] = 1.0; // Set default origin to zero - m_Origin[0] = 0.0; - m_Origin[1] = 0.0; + m_Origin[0] = 0.0; + m_Origin[1] = 0.0; - m_currentfile = NULL; + m_currentfile = NULL; - m_NbBands = 3; - m_FlagWriteImageInformation = true; + m_NbBands = 3; + m_FlagWriteImageInformation = true; //Resolution depth - m_Depth = 8; + m_Depth = 8; - m_NbOctetPixel=1; + m_NbOctetPixel=1; - useCache=false; - m_ServerName=""; - m_CacheDirectory=""; - m_FileSuffix="jpg"; - m_AddressMode="0"; + useCache=false; + m_ServerName=""; + m_CacheDirectory=""; + m_FileSuffix="jpg"; + m_AddressMode="0"; - } +} - TileMapImageIO::~TileMapImageIO() - { - } +TileMapImageIO::~TileMapImageIO() +{ +} // Tell only if the file can be read with GDAL. - bool TileMapImageIO::CanReadFile(const char* file) - { +bool TileMapImageIO::CanReadFile(const char* file) +{ // First check the extension - if( file == NULL ) - { - itkDebugMacro(<<"No filename specified."); - return false; - } - - std::string filename = file; - std::string::size_type gmPos = filename.rfind(".otb"); - if ( (gmPos != std::string::npos) - && (gmPos == filename.length() - 3) ) - { - return true; - } + if ( file == NULL ) + { + itkDebugMacro(<<"No filename specified."); return false; } -// Used to print information about this object - void TileMapImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const + std::string filename = file; + std::string::size_type gmPos = filename.rfind(".otb"); + if ( (gmPos != std::string::npos) + && (gmPos == filename.length() - 3) ) { - Superclass::PrintSelf(os, indent); - os << indent << "Compression Level : " << m_CompressionLevel << "\n"; + return true; } + return false; +} + +// Used to print information about this object +void TileMapImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Compression Level : " << m_CompressionLevel << "\n"; +} // Read a 3D image (or event more bands)... not implemented yet - void TileMapImageIO::ReadVolume(void*) - { - } +void TileMapImageIO::ReadVolume(void*) +{ +} // Read image with GDAL - void TileMapImageIO::Read(void* buffer) +void TileMapImageIO::Read(void* buffer) +{ + unsigned char * p = static_cast<unsigned char *>(buffer); + if (p==NULL) { - unsigned char * p = static_cast<unsigned char *>(buffer); - if(p==NULL) - { - itkExceptionMacro(<<"Memory allocation error"); - return; - } + itkExceptionMacro(<<"Memory allocation error"); + return; + } - int totLines = this->GetIORegion().GetSize()[1]; - int totSamples = this->GetIORegion().GetSize()[0]; - int firstLine = this->GetIORegion().GetIndex()[1]; - int firstSample = this->GetIORegion().GetIndex()[0]; - int nComponents = this->GetNumberOfComponents(); + int totLines = this->GetIORegion().GetSize()[1]; + int totSamples = this->GetIORegion().GetSize()[0]; + int firstLine = this->GetIORegion().GetIndex()[1]; + int firstSample = this->GetIORegion().GetIndex()[0]; + int nComponents = this->GetNumberOfComponents(); - otbMsgDevMacro( <<" TileMapImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" TileMapImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); // std::streamoff lNbPixels = (static_cast<std::streamoff>(totSamples))*(static_cast<std::streamoff>(totLines)); - //otbMsgDevMacro( <<" Allocation buff tempon taille : "<<lNbPixels<<"*"<<m_NbOctetPixel<<" (NbOctetPixel) = "<<lTailleBuffer); - otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); - otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); - otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); - otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); - otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); - //otbMsgDevMacro( <<" sizeof(pos_type) : "<<sizeof(pos_type)); - //otbMsgDevMacro( <<" sizeof(off_type) : "<<sizeof(off_type)); - otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); - - int nTilesX = (int) ceil(totSamples/256.)+1; - int nTilesY = (int) ceil(totLines/256.)+1; - unsigned char * bufferTile = new unsigned char[256*256*nComponents]; - - //Read all the required tiles - //FIXME assume RGB image - for(int numTileY=0; numTileY<nTilesY; numTileY++) + //otbMsgDevMacro( <<" Allocation buff tempon taille : "<<lNbPixels<<"*"<<m_NbOctetPixel<<" (NbOctetPixel) = "<<lTailleBuffer); + otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); + otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); + otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); + otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); + otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); + //otbMsgDevMacro( <<" sizeof(pos_type) : "<<sizeof(pos_type)); + //otbMsgDevMacro( <<" sizeof(off_type) : "<<sizeof(off_type)); + otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); + + int nTilesX = (int) ceil(totSamples/256.)+1; + int nTilesY = (int) ceil(totLines/256.)+1; + unsigned char * bufferTile = new unsigned char[256*256*nComponents]; + + //Read all the required tiles + //FIXME assume RGB image + for (int numTileY=0; numTileY<nTilesY; numTileY++) + { + for (int numTileX=0; numTileX<nTilesX; numTileX++) { - for(int numTileX=0; numTileX<nTilesX; numTileX++) - { - double xTile = (firstSample+256*numTileX)/((1 << m_Depth)*256.); - double yTile = (firstLine+256*numTileY)/((1 << m_Depth)*256.); - //Retrieve the tile - InternalRead(xTile, yTile, bufferTile); + double xTile = (firstSample+256*numTileX)/((1 << m_Depth)*256.); + double yTile = (firstLine+256*numTileY)/((1 << m_Depth)*256.); + //Retrieve the tile + InternalRead(xTile, yTile, bufferTile); - //Copy the tile in the output buffer - for(int tileJ=0; tileJ<256; tileJ++) + //Copy the tile in the output buffer + for (int tileJ=0; tileJ<256; tileJ++) + { + long int yImageOffset=(long int) (256*floor(firstLine/256.)+256*numTileY-firstLine+tileJ); + if ((yImageOffset >= 0) && (yImageOffset < totLines)) { - long int yImageOffset=(long int) (256*floor(firstLine/256.)+256*numTileY-firstLine+tileJ); - if ((yImageOffset >= 0) && (yImageOffset < totLines)) + long int xImageOffset = (long int) + (256*floor(firstSample/256.)+256*numTileX-firstSample); + unsigned char * dst = p+nComponents*(xImageOffset+totSamples*yImageOffset); + unsigned char * src = bufferTile+nComponents*256*tileJ; + int size = nComponents*256; + if (xImageOffset < 0) + { + dst -= nComponents*xImageOffset; + src -= nComponents*xImageOffset; + size += nComponents*xImageOffset; + } + if (xImageOffset+256 > totSamples) { - long int xImageOffset = (long int) - (256*floor(firstSample/256.)+256*numTileX-firstSample); - unsigned char * dst = p+nComponents*(xImageOffset+totSamples*yImageOffset); - unsigned char * src = bufferTile+nComponents*256*tileJ; - int size = nComponents*256; - if (xImageOffset < 0){ - dst -= nComponents*xImageOffset; - src -= nComponents*xImageOffset; - size += nComponents*xImageOffset; - } - if (xImageOffset+256 > totSamples) - { - size += nComponents*(totSamples-xImageOffset-256); - } - if (size > 0) - { - memcpy(dst, src, size); - } + size += nComponents*(totSamples-xImageOffset-256); + } + if (size > 0) + { + memcpy(dst, src, size); + } - } - }//end of tile copy + } + }//end of tile copy - } - }//end of full image copy + } + }//end of full image copy - delete[] bufferTile; + delete[] bufferTile; - otbMsgDevMacro( << "TileMapImageIO::Read() completed"); - } + otbMsgDevMacro( << "TileMapImageIO::Read() completed"); +} - void TileMapImageIO::InternalRead(double x, double y, void* buffer) - { - std::ostringstream quad; - std::ostringstream quad2; +void TileMapImageIO::InternalRead(double x, double y, void* buffer) +{ + std::ostringstream quad; + std::ostringstream quad2; // int lDepth=m_Depth; - unsigned char * bufferCacheFault = NULL; - double xorig=x; - double yorig=y; + unsigned char * bufferCacheFault = NULL; + double xorig=x; + double yorig=y; - XYToQuadTree(x, y, quad); - XYToQuadTree2(x, y, quad2); + XYToQuadTree(x, y, quad); + XYToQuadTree2(x, y, quad2); - std::ostringstream filename; - BuildFileName(quad2, filename); + std::ostringstream filename; + BuildFileName(quad2, filename); - itk::ImageIOBase::Pointer imageIO; + itk::ImageIOBase::Pointer imageIO; //Open the file to fill the buffer + if (m_AddressMode[0] == '0') + { + imageIO = itk::JPEGImageIO::New(); + } + if (m_AddressMode[0] == '1') + { + imageIO = itk::PNGImageIO::New(); + } + bool lCanRead(false); + lCanRead = imageIO->CanReadFile(filename.str().c_str()); + otbMsgDevMacro( << filename.str()); + + //If we cannot read the file: retrieve and read + if ( lCanRead == false) + { if (m_AddressMode[0] == '0') { - imageIO = itk::JPEGImageIO::New(); + GetFromNetGM(filename, xorig, yorig); } if (m_AddressMode[0] == '1') { - imageIO = itk::PNGImageIO::New(); + GetFromNetOSM(filename, xorig, yorig); } - bool lCanRead(false); lCanRead = imageIO->CanReadFile(filename.str().c_str()); - otbMsgDevMacro( << filename.str()); - - //If we cannot read the file: retrieve and read - if ( lCanRead == false) - { - if (m_AddressMode[0] == '0') - { - GetFromNetGM(filename, xorig, yorig); - } - if (m_AddressMode[0] == '1') - { - GetFromNetOSM(filename, xorig, yorig); - } - lCanRead = imageIO->CanReadFile(filename.str().c_str()); - } + } - if ( lCanRead == true) + if ( lCanRead == true) + { + imageIO->SetFileName(filename.str().c_str()); + imageIO->Read(buffer); + } + else + { + if (bufferCacheFault == NULL) { - imageIO->SetFileName(filename.str().c_str()); - imageIO->Read(buffer); + bufferCacheFault = new unsigned char[256*256*3]; + FillCacheFaults(bufferCacheFault); } - else - { - if (bufferCacheFault == NULL) - { - bufferCacheFault = new unsigned char[256*256*3]; - FillCacheFaults(bufferCacheFault); - } - memcpy(buffer, bufferCacheFault,256*256*3 ); + memcpy(buffer, bufferCacheFault,256*256*3 ); - } + } - } +} - void TileMapImageIO::BuildFileName(std::ostringstream& quad, std::ostringstream& filename) { +void TileMapImageIO::BuildFileName(std::ostringstream& quad, std::ostringstream& filename) +{ - int quadsize=quad.str().size(); - std::ostringstream directory; - directory << m_CacheDirectory; + int quadsize=quad.str().size(); + std::ostringstream directory; + directory << m_CacheDirectory; //build directory name - int i=0; - while ((i<8) && (i<quadsize)) - { - directory << "/"; - directory << (quad.str().c_str())[i]; - i++; - } - ossimFilename directoryOssim(directory.str().c_str()); - directoryOssim.createDirectory(); + int i=0; + while ((i<8) && (i<quadsize)) + { + directory << "/"; + directory << (quad.str().c_str())[i]; + i++; + } + ossimFilename directoryOssim(directory.str().c_str()); + directoryOssim.createDirectory(); - filename << directory.str(); - filename << "/"; - filename << "otb-"; - filename << quad.str(); - filename << "." << m_FileSuffix; + filename << directory.str(); + filename << "/"; + filename << "otb-"; + filename << quad.str(); + filename << "." << m_FileSuffix; - } +} - /** Get the file from net in a qtrssrtstr.jpg fashion */ - void TileMapImageIO::GetFromNetGM(std::ostringstream& filename, double x, double y) - { +/** Get the file from net in a qtrssrtstr.jpg fashion */ +void TileMapImageIO::GetFromNetGM(std::ostringstream& filename, double x, double y) +{ - std::ostringstream quad; - XYToQuadTree(x, y, quad); + std::ostringstream quad; + XYToQuadTree(x, y, quad); - std::ostringstream urlStream; - urlStream << m_ServerName; - urlStream << quad.str(); + std::ostringstream urlStream; + urlStream << m_ServerName; + urlStream << quad.str(); // std::ostringstream filename; // BuildFileName(quad, filename); - FILE* output_file = fopen(filename.str().c_str(),"w"); - if(output_file == NULL) - { - itkExceptionMacro(<<"TileMap read : bad file name."); - } + FILE* output_file = fopen(filename.str().c_str(),"w"); + if (output_file == NULL) + { + itkExceptionMacro(<<"TileMap read : bad file name."); + } - std::ostringstream browserStream; - browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; + std::ostringstream browserStream; + browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; - CURL *curl; - CURLcode res; - curl = curl_easy_init(); + CURL *curl; + CURLcode res; + curl = curl_easy_init(); - otbMsgDevMacro( << urlStream.str().data() ); + otbMsgDevMacro( << urlStream.str().data() ); - char url[200]; - strcpy(url,urlStream.str().data()); + char url[200]; + strcpy(url,urlStream.str().data()); - char browser[200]; - strcpy(browser,browserStream.str().data()); + char browser[200]; + strcpy(browser,browserStream.str().data()); //Download the file - if(curl) { - curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); - curl_easy_setopt(curl, CURLOPT_URL, url); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); - res = curl_easy_perform(curl); - if (res != 0){ - itkExceptionMacro(<<"TileMap read : transfert error."); - } - - fclose(output_file); - /* always cleanup */ - curl_easy_cleanup(curl); + if (curl) + { + curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); + res = curl_easy_perform(curl); + if (res != 0) + { + itkExceptionMacro(<<"TileMap read : transfert error."); } + fclose(output_file); + /* always cleanup */ + curl_easy_cleanup(curl); } - /** Get the file from net in a 132/153.png fashion */ - void TileMapImageIO::GetFromNetOSM(std::ostringstream& filename, double x, double y) - { - otbMsgDevMacro( << "(x,y): (" << x << "," << y << ")"); - std::ostringstream urlStream; - urlStream << m_ServerName; +} + +/** Get the file from net in a 132/153.png fashion */ +void TileMapImageIO::GetFromNetOSM(std::ostringstream& filename, double x, double y) +{ + otbMsgDevMacro( << "(x,y): (" << x << "," << y << ")"); + std::ostringstream urlStream; + urlStream << m_ServerName; // urlStream << quad.str(); - urlStream << m_Depth; - urlStream << "/"; - urlStream << (long int) (((double) x*(1 << m_Depth))); - urlStream << "/"; - urlStream << (long int) (((double) y*(1 << m_Depth))); - urlStream << "." << m_FileSuffix; + urlStream << m_Depth; + urlStream << "/"; + urlStream << (long int) (((double) x*(1 << m_Depth))); + urlStream << "/"; + urlStream << (long int) (((double) y*(1 << m_Depth))); + urlStream << "." << m_FileSuffix; // std::ostringstream filename; // BuildFileName(quad, filename); - FILE* output_file = fopen(filename.str().c_str(),"w"); - if(output_file == NULL) - { - itkExceptionMacro(<<"TileMap read : bad file name."); - } + FILE* output_file = fopen(filename.str().c_str(),"w"); + if (output_file == NULL) + { + itkExceptionMacro(<<"TileMap read : bad file name."); + } - std::ostringstream browserStream; - browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; + std::ostringstream browserStream; + browserStream << "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; - CURL *curl; - CURLcode res; - curl = curl_easy_init(); + CURL *curl; + CURLcode res; + curl = curl_easy_init(); - otbMsgDevMacro(<< urlStream.str().data()); + otbMsgDevMacro(<< urlStream.str().data()); - char url[200]; - strcpy(url,urlStream.str().data()); + char url[200]; + strcpy(url,urlStream.str().data()); - char browser[200]; - strcpy(browser,browserStream.str().data()); + char browser[200]; + strcpy(browser,browserStream.str().data()); //Download the file - if(curl) { - curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); - curl_easy_setopt(curl, CURLOPT_URL, url); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); - res = curl_easy_perform(curl); - if (res != 0){ - itkExceptionMacro(<<"TileMap read : transfert error."); - } - - fclose(output_file); - /* always cleanup */ - curl_easy_cleanup(curl); + if (curl) + { + curl_easy_setopt(curl, CURLOPT_USERAGENT, browser); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); + res = curl_easy_perform(curl); + if (res != 0) + { + itkExceptionMacro(<<"TileMap read : transfert error."); } + fclose(output_file); + /* always cleanup */ + curl_easy_cleanup(curl); } - void TileMapImageIO::ReadImageInformation() - { +} - if( m_FileName.empty() == true ) - { - itkExceptionMacro(<<"TileMap read : empty image file name file."); - } +void TileMapImageIO::ReadImageInformation() +{ + + if ( m_FileName.empty() == true ) + { + itkExceptionMacro(<<"TileMap read : empty image file name file."); + } - m_Dimensions[0] = (1 << m_Depth)*256; - m_Dimensions[1] = (1 << m_Depth)*256; - otbMsgDevMacro(<<"Get Dimensions : x="<<m_Dimensions[0]<<" & y="<<m_Dimensions[1]); - this->SetNumberOfComponents(3); - this->SetNumberOfDimensions(2); - this->SetFileTypeToBinary(); - SetComponentType(UCHAR); + m_Dimensions[0] = (1 << m_Depth)*256; + m_Dimensions[1] = (1 << m_Depth)*256; + otbMsgDevMacro(<<"Get Dimensions : x="<<m_Dimensions[0]<<" & y="<<m_Dimensions[1]); + this->SetNumberOfComponents(3); + this->SetNumberOfDimensions(2); + this->SetFileTypeToBinary(); + SetComponentType(UCHAR); // Default Spacing - m_Spacing[0]=1; - m_Spacing[1]=1; - m_Origin[0] = 0; - m_Origin[1] = 0; - - - std::ifstream file(m_FileName.c_str(), std::ifstream::in ); - std::getline(file, m_ServerName); - if (m_ServerName[0]!='h' - || m_ServerName[1]!='t' - || m_ServerName[2]!='t' - || m_ServerName[3]!='p') - { - itkExceptionMacro(<<"Can't read server name from file"); - } - std::getline(file, m_FileSuffix); - std::getline(file, m_AddressMode); - otbMsgDevMacro( << "File parameters: " << m_ServerName << " " << m_FileSuffix << " " << m_AddressMode); + m_Spacing[0]=1; + m_Spacing[1]=1; + m_Origin[0] = 0; + m_Origin[1] = 0; + + + std::ifstream file(m_FileName.c_str(), std::ifstream::in ); + std::getline(file, m_ServerName); + if (m_ServerName[0]!='h' + || m_ServerName[1]!='t' + || m_ServerName[2]!='t' + || m_ServerName[3]!='p') + { + itkExceptionMacro(<<"Can't read server name from file"); } + std::getline(file, m_FileSuffix); + std::getline(file, m_AddressMode); + otbMsgDevMacro( << "File parameters: " << m_ServerName << " " << m_FileSuffix << " " << m_AddressMode); +} - bool TileMapImageIO::CanWriteFile( const char* name ) - { +bool TileMapImageIO::CanWriteFile( const char* name ) +{ // First if filename is provided - if( name == NULL ) - { - itkDebugMacro(<<"No filename specified."); - return false; - } - - // Check for file extension - std::string filename = name; - std::string::size_type gmPos = filename.rfind(".otb"); - if ( (gmPos != std::string::npos) - && (gmPos == filename.length() - 3) ) - { - return true; - } + if ( name == NULL ) + { + itkDebugMacro(<<"No filename specified."); return false; - } - void TileMapImageIO::WriteImageInformation(void) + // Check for file extension + std::string filename = name; + std::string::size_type gmPos = filename.rfind(".otb"); + if ( (gmPos != std::string::npos) + && (gmPos == filename.length() - 3) ) { + return true; } + return false; - void TileMapImageIO::Write(const void* buffer) - { +} - const unsigned char * p = static_cast<const unsigned char *>(buffer); - if(p==NULL) - { - itkExceptionMacro(<<"Memory allocation error"); - return; - } +void TileMapImageIO::WriteImageInformation(void) +{ +} - if( m_FlagWriteImageInformation == true ) - { - this->WriteImageInformation(); - m_FlagWriteImageInformation = false; - } +void TileMapImageIO::Write(const void* buffer) +{ + + const unsigned char * p = static_cast<const unsigned char *>(buffer); + if (p==NULL) + { + itkExceptionMacro(<<"Memory allocation error"); + return; + } - int totLines = this->GetIORegion().GetSize()[1]; - int totSamples = this->GetIORegion().GetSize()[0]; - int firstLine = this->GetIORegion().GetIndex()[1]; - int firstSample = this->GetIORegion().GetIndex()[0]; - int originLine = (int)this->GetOrigin(1); - int originSample = (int)this->GetOrigin(0); - int nComponents = this->GetNumberOfComponents(); + if ( m_FlagWriteImageInformation == true ) + { + this->WriteImageInformation(); + m_FlagWriteImageInformation = false; + } + + int totLines = this->GetIORegion().GetSize()[1]; + int totSamples = this->GetIORegion().GetSize()[0]; + int firstLine = this->GetIORegion().GetIndex()[1]; + int firstSample = this->GetIORegion().GetIndex()[0]; + int originLine = (int)this->GetOrigin(1); + int originSample = (int)this->GetOrigin(0); + int nComponents = this->GetNumberOfComponents(); - otbMsgDevMacro( << "TileMapImageIO::Write: Size " << totLines << ", "<< totSamples); - otbMsgDevMacro( << "TileMapImageIO::Write: Index" << firstLine << ", "<< firstSample); - otbMsgDevMacro( << "TileMapImageIO::Write: Origin" << originLine << ", "<< originSample); + otbMsgDevMacro( << "TileMapImageIO::Write: Size " << totLines << ", "<< totSamples); + otbMsgDevMacro( << "TileMapImageIO::Write: Index" << firstLine << ", "<< firstSample); + otbMsgDevMacro( << "TileMapImageIO::Write: Origin" << originLine << ", "<< originSample); - otbMsgDevMacro( <<" TileMapImageIO::Read() "); - otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); - otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); - otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); + otbMsgDevMacro( <<" TileMapImageIO::Read() "); + otbMsgDevMacro( <<" Image size : "<<m_Dimensions[0]<<","<<m_Dimensions[1]); + otbMsgDevMacro( <<" Region read (IORegion) : "<<this->GetIORegion()); + otbMsgDevMacro( <<" Nb Of Components : "<<this->GetNumberOfComponents()); // std::streamoff lNbPixels = (static_cast<std::streamoff>(totSamples))*(static_cast<std::streamoff>(totLines)); // std::streamoff lTailleBuffer = static_cast<std::streamoff>(m_NbOctetPixel)*lNbPixels; // otbMsgDevMacro( <<" Allocation buff tempon taille : "<<lNbPixels<<"*"<<m_NbOctetPixel<<" (NbOctetPixel) = "<<lTailleBuffer); - otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); - otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); - otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); - otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); - otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); - //otbMsgDevMacro( <<" sizeof(pos_type) : "<<sizeof(pos_type)); - //otbMsgDevMacro( <<" sizeof(off_type) : "<<sizeof(off_type)); - otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); - -/* double x = (originSample+firstSample)/((1 << m_Depth)*256.); - double y = (originLine+firstLine)/((1 << m_Depth)*256.); - otbMsgDevMacro(<< x ); - otbMsgDevMacro(<< y ); -*/ - - int nTilesX = (int) ceil(totSamples/256.)+1; - int nTilesY = (int) ceil(totLines/256.)+1; - unsigned char * bufferTile = new unsigned char[256*256*nComponents]; + otbMsgDevMacro( <<" sizeof(streamsize) : "<<sizeof(std::streamsize)); + otbMsgDevMacro( <<" sizeof(streampos) : "<<sizeof(std::streampos)); + otbMsgDevMacro( <<" sizeof(streamoff) : "<<sizeof(std::streamoff)); + otbMsgDevMacro( <<" sizeof(std::ios::beg) : "<<sizeof(std::ios::beg)); + otbMsgDevMacro( <<" sizeof(size_t) : "<<sizeof(size_t)); + //otbMsgDevMacro( <<" sizeof(pos_type) : "<<sizeof(pos_type)); + //otbMsgDevMacro( <<" sizeof(off_type) : "<<sizeof(off_type)); + otbMsgDevMacro( <<" sizeof(unsigned long) : "<<sizeof(unsigned long)); + + /* double x = (originSample+firstSample)/((1 << m_Depth)*256.); + double y = (originLine+firstLine)/((1 << m_Depth)*256.); + otbMsgDevMacro(<< x ); + otbMsgDevMacro(<< y ); + */ + + int nTilesX = (int) ceil(totSamples/256.)+1; + int nTilesY = (int) ceil(totLines/256.)+1; + unsigned char * bufferTile = new unsigned char[256*256*nComponents]; //Read all the required tiles - for(int numTileY=0; numTileY<nTilesY; numTileY++) + for (int numTileY=0; numTileY<nTilesY; numTileY++) + { + for (int numTileX=0; numTileX<nTilesX; numTileX++) { - for(int numTileX=0; numTileX<nTilesX; numTileX++) - { - //Set tile buffer to 0 - for(int iInit=0; iInit<256*256*nComponents; iInit++){ - bufferTile[iInit]=0; - } + //Set tile buffer to 0 + for (int iInit=0; iInit<256*256*nComponents; iInit++) + { + bufferTile[iInit]=0; + } - for(int tileJ=0; tileJ<256; tileJ++) + for (int tileJ=0; tileJ<256; tileJ++) + { + long int yImageOffset=(long int) (256*floor((originLine+firstLine)/256.)+256*numTileY-(originLine+firstLine)+tileJ); + if ((yImageOffset >= 0) && (yImageOffset < totLines)) { - long int yImageOffset=(long int) (256*floor((originLine+firstLine)/256.)+256*numTileY-(originLine+firstLine)+tileJ); - if ((yImageOffset >= 0) && (yImageOffset < totLines)) + long int xImageOffset = (long int) + (256*floor((originSample+firstSample)/256.)+256*numTileX-(originSample+firstSample)); + unsigned char * dst = bufferTile+nComponents*256*tileJ; + const unsigned char * src = p+nComponents*(xImageOffset+totSamples*yImageOffset); + int size = nComponents*256; + if (xImageOffset < 0) + { + src -= nComponents*xImageOffset; + dst -= nComponents*xImageOffset; + size += nComponents*xImageOffset; + } + if (xImageOffset+256 > totSamples) + { + size += nComponents*(totSamples-xImageOffset-256); + } + if (size > 0) { - long int xImageOffset = (long int) - (256*floor((originSample+firstSample)/256.)+256*numTileX-(originSample+firstSample)); - unsigned char * dst = bufferTile+nComponents*256*tileJ; - const unsigned char * src = p+nComponents*(xImageOffset+totSamples*yImageOffset); - int size = nComponents*256; - if (xImageOffset < 0){ - src -= nComponents*xImageOffset; - dst -= nComponents*xImageOffset; - size += nComponents*xImageOffset; - } - if (xImageOffset+256 > totSamples) - { - size += nComponents*(totSamples-xImageOffset-256); - } - if (size > 0) - { - memcpy(dst, src, size); - } + memcpy(dst, src, size); + } - } - }//end of tile copy + } + }//end of tile copy - double xTile = (originSample+firstSample+256*numTileX)/((1 << m_Depth)*256.); - double yTile = (originLine+firstLine+256*numTileY)/((1 << m_Depth)*256.); + double xTile = (originSample+firstSample+256*numTileX)/((1 << m_Depth)*256.); + double yTile = (originLine+firstLine+256*numTileY)/((1 << m_Depth)*256.); //Write the tile - InternalWrite(xTile, yTile, bufferTile); + InternalWrite(xTile, yTile, bufferTile); - } - }//end of full image copy + } + }//end of full image copy - delete[] bufferTile; + delete[] bufferTile; - otbMsgDevMacro( << "TileMapImageIO::Write() completed"); + otbMsgDevMacro( << "TileMapImageIO::Write() completed"); - } +} - void TileMapImageIO::InternalWrite(double x, double y, const void* buffer) - { - std::ostringstream quad; +void TileMapImageIO::InternalWrite(double x, double y, const void* buffer) +{ + std::ostringstream quad; - otbMsgDevMacro( << x << ", " << y ); + otbMsgDevMacro( << x << ", " << y ); - XYToQuadTree2(x, y, quad); + XYToQuadTree2(x, y, quad); - std::ostringstream filename; - BuildFileName(quad, filename); + std::ostringstream filename; + BuildFileName(quad, filename); - itk::ImageIOBase::Pointer imageIO; + itk::ImageIOBase::Pointer imageIO; //Open the file to write the buffer - if (m_AddressMode[0] == '0') - { - imageIO = itk::JPEGImageIO::New(); - } - if (m_AddressMode[0] == '1') - { - imageIO = itk::PNGImageIO::New(); - } + if (m_AddressMode[0] == '0') + { + imageIO = itk::JPEGImageIO::New(); + } + if (m_AddressMode[0] == '1') + { + imageIO = itk::PNGImageIO::New(); + } - bool lCanWrite(false); - lCanWrite = imageIO->CanWriteFile(filename.str().c_str()); - otbMsgDevMacro( << filename.str()); + bool lCanWrite(false); + lCanWrite = imageIO->CanWriteFile(filename.str().c_str()); + otbMsgDevMacro( << filename.str()); - if ( lCanWrite == true) - { - imageIO->SetNumberOfDimensions(2); - imageIO->SetDimensions(0,256); - imageIO->SetDimensions(1,256); - imageIO->SetSpacing(0,1); - imageIO->SetSpacing(1,1); - imageIO->SetOrigin(0,0); - imageIO->SetOrigin(1,0); - imageIO->SetNumberOfComponents(3); - - vnl_vector< double > axisDirection(2); - - axisDirection[0] = 1; - axisDirection[1] = 0; - imageIO->SetDirection( 0, axisDirection ); - axisDirection[0] = 0; - axisDirection[1] = 1; - imageIO->SetDirection( 1, axisDirection ); + if ( lCanWrite == true) + { + imageIO->SetNumberOfDimensions(2); + imageIO->SetDimensions(0,256); + imageIO->SetDimensions(1,256); + imageIO->SetSpacing(0,1); + imageIO->SetSpacing(1,1); + imageIO->SetOrigin(0,0); + imageIO->SetOrigin(1,0); + imageIO->SetNumberOfComponents(3); + + vnl_vector< double > axisDirection(2); + + axisDirection[0] = 1; + axisDirection[1] = 0; + imageIO->SetDirection( 0, axisDirection ); + axisDirection[0] = 0; + axisDirection[1] = 1; + imageIO->SetDirection( 1, axisDirection ); imageIO->SetUseCompression(1); - imageIO->SetFileName(filename.str().c_str()); - imageIO->WriteImageInformation(); - - itk::ImageIORegion ioRegion(2); - for(unsigned int i=0; i<2; i++) - { - ioRegion.SetSize(i,256); - ioRegion.SetIndex(i,0); - } - imageIO->SetIORegion(ioRegion); + imageIO->SetFileName(filename.str().c_str()); + imageIO->WriteImageInformation(); - imageIO->Write(buffer); - } - else + itk::ImageIORegion ioRegion(2); + for (unsigned int i=0; i<2; i++) { - itkExceptionMacro(<<"TileMap write : bad file name."); + ioRegion.SetSize(i,256); + ioRegion.SetIndex(i,0); } + imageIO->SetIORegion(ioRegion); + imageIO->Write(buffer); } - - /** Generate the quadtree address in qrts style */ - int TileMapImageIO::XYToQuadTree(double x, double y, std::ostringstream& quad) + else { - int lDepth=m_Depth; - while (lDepth--) // (post-decrement) - { - // make sure we only look at fractional part - x -= floor(x); - y -= floor(y); - int quad_index = ((x >= 0.5 ? 1 : 0) + (y >= 0.5 ? 2 : 0)); - - switch(quad_index) - { - case 0: - quad<<"q"; - break; - case 1: - quad<<"r"; - break; - case 2: - quad<<"t"; - break; - case 3: - quad<<"s"; - break; - } -// level down - x *= 2; - y *= 2; - } - - return 0; + itkExceptionMacro(<<"TileMap write : bad file name."); } - /** Generate the quadtree address in 0123 style */ - int TileMapImageIO::XYToQuadTree2(double x, double y, std::ostringstream& quad) +} + +/** Generate the quadtree address in qrts style */ +int TileMapImageIO::XYToQuadTree(double x, double y, std::ostringstream& quad) +{ + int lDepth=m_Depth; + while (lDepth--) // (post-decrement) { - int lDepth=m_Depth; - while (lDepth--) // (post-decrement) - { - // make sure we only look at fractional part - x -= floor(x); - y -= floor(y); - int quad_index = ((x >= 0.5 ? 1 : 0) + (y >= 0.5 ? 2 : 0)); + // make sure we only look at fractional part + x -= floor(x); + y -= floor(y); + int quad_index = ((x >= 0.5 ? 1 : 0) + (y >= 0.5 ? 2 : 0)); - switch(quad_index) - { - case 0: - quad<<"0"; - break; - case 1: - quad<<"1"; - break; - case 2: - quad<<"2"; - break; - case 3: - quad<<"3"; - break; - } -// level down - x *= 2; - y *= 2; + switch (quad_index) + { + case 0: + quad<<"q"; + break; + case 1: + quad<<"r"; + break; + case 2: + quad<<"t"; + break; + case 3: + quad<<"s"; + break; } - - return 0; +// level down + x *= 2; + y *= 2; } - /** RGB buffer filling when the tile is not found */ - void TileMapImageIO::FillCacheFaults(void* buffer) + return 0; +} + +/** Generate the quadtree address in 0123 style */ +int TileMapImageIO::XYToQuadTree2(double x, double y, std::ostringstream& quad) +{ + int lDepth=m_Depth; + while (lDepth--) // (post-decrement) { - const char * logo = - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337fedZZXZZXZZX\333\332\326" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\5\5\5T\4\6=" - "\3\4\4\4\4\340\337\333\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\330\327\323KKJ<" - "<:<<;\261\260\255\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\336\335\331\1\1\1\253\10\14n\6\10" - "\"\"!\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\266\265\262\36\36\36" - "\261\261\261UUUmmk\341\340\334\322\321\316\312\312\306\312\312\306\312\312" - "\306\312\312\306\324\323\317\343\342\336\326\325\321\0\0\0\253\11\14Z\5\6" - "FFE\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\264\263\260+++\377\377\377" - "zzz\7\7\6\5\5\5\4\4\4\21\21\21\23\23\23\23\23\23\20\20\20\3\3\3\7\7\7\33" - "\33\32\0\0\0\257\11\15""3\3\4jig\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\250\250\245PPN\13" - "\13\13;;;\377\377\377\311\311\311\300\300\300\343\343\343\372\372\372\377" - "\377\377\377\377\377\377\377\377\377\377\377\370\370\370\337\337\337a``\0" - "\0\0\266\12\16\15\1\1\216\216\213\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\250\247\244++*\20\20\20lll\310\310\310\375" - "\375\375\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377hhh\0" - "\0\0\244\11\14\0\0\0\262\261\256\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\334\333\330\\[Z\14\14\14\202\202\202\361\361\361\371\371\371\273" - "\273\274\246\246\247\377\377\377\277\277\277\206\206\206\257\257\257\351" - "\352\351\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377POO\1\0\0\200\7\12\0\0\0\326\325\321\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\324\323\320211777\333\333\333\324\324\324bbb\15\15\15\0\0\0...\377" - "\377\377\214\214\214\2\2\3\2\2\3\2\2\2>>>\254\254\254\375\375\375\377\377" - "\377\377\377\377\377\377\377766\5\0\0P\4\6\26\26\26\344\343\337\344\343\337" - "\343\342\336\330\327\323\334\333\330\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\327\326\323--,VVV\360\360\360mmm\2\2\2\24\37-2Lo1Jm...\377\377" - "\377\244\244\244\6\11\14Df\2241Kl\26!.\1\1\1""222\322\322\322\377\377\377" - "\377\377\377\35\35\35\0\0\0\0\0\0\12\12\11--,\20\20\17\1\1\1\2\1\1\1\1\1" - "\4\4\4\34\34\34""443llj\314\313\307\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\342\336EEDHHH\342\342\342111\12\17\26""6RxFj\233Fj\2334Nr.." - ".\377\377\377\310\310\310\0\0\0Ab\216Fj\233Fj\233:X\177\20\30\"\11\11\11" - "nnn211\0\0\0\0\0\0\0\0\0\16\2\3j\13\15\250\15\20\275\15\20\306\14\20\303" - "\14\20\266\15\20\237\14\17~\13\15""5\7\10\14\13\13\230\227\224\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\230\230\225\25\25\25\331\331\331&&&\25\40.Be\223" - "Fj\233Fj\233Fj\2334Nr...\377\377\377\364\364\364\4\4\4""0IiFj\233Fj\233B" - "c\220\"2F\2\2\1\0\0\0\0\0\0\0\0\0\12\20\11\36""2\33\16\26\15\0\0\0\24\3\4" - "d\11\13\272\15\21\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\206\14" - "\17\11\5\5\253\252\247\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\33700/\212\212\212IIJ\17\27!Dg\227" - "Fj\233Fj\233Fj\233Fj\2334Nr...\377\377\377\377\377\377BBB\25\37,Fj\2330E" - "c\7\11\14\7\12\16!1F+@]\4\5\10\0\0\0""2V0p\312op\312ob\255`:b7\13\17\11\21" - "\3\3\225\14\17\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20i\12\14$" - "$$\342\341\335\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\323\322\317\2\2\2\223\223\223\3\5\7>^\212Fj\233Fj\233Fj\233" - "Fj\233Fj\2334Nr...\377\377\377\377\377\377\270\271\271\1\1\1\26\37+\5\7\12" - "(<VDf\225Fj\233Fj\2330Hi\0\0\0""9e7p\312op\312op\312op\312ol\300j-H)\6\2" - "\2\222\14\17\313\14\20\313\14\20\313\14\20\313\14\20\302\15\21\16\3\3\251" - "\250\246\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\275\274\271\33\33\33""222!2IFj\233Fj\233Fj\233Fj\233Fj\233Fj\233" - "4Nr...\377\377\377\377\377\377\363\363\363\32\32\31\1\1\1""4NoFj\233Fj\233" - "Fj\233Fj\2333Lm\0\0\0:f8p\312op\312op\312op\312op\312op\312o3S/\12\2\2\255" - "\15\20\313\14\20\313\14\20\313\14\20\313\14\20E\7\10qpn\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\276\275\272\3\3\3\4" - "\6\11?_\213Fj\233Fj\233Fj\233Fj\233Fj\233Fj\2334Nr...\377\377\377\374\373" - "\373FEELKK???\3\5\7#5K;Y\2006Rw\37.B\3\4\5\0\0\0.P,p\312op\312op\312op\312" - "op\312op\312oo\307m\30%\26A\7\10\313\14\20\313\14\20\313\14\20\313\14\20" - "l\11\13TSR\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\226\225\222!0D=\\\207Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" - "4Nr+++\377\377\377\206\205\205GFF\374\374\374\372\373\372\204\205\204\25" - "\25\25\0\0\0\0\0\0\"#\"EDD\0\0\0\31(\26p\312op\312op\312op\312op\312op\312" - "op\312oK\203I\35\3\4\313\14\20\313\14\20\313\14\20\313\14\20p\11\13SRQ\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337yyv/" - "GhFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\2337Sz\14\14\14\346\345\345" - ",++\357\356\356\377\377\377\377\377\377\377\377\377\373\373\373\331\331\331" - "\332\332\332\375\376\376\206\205\205\6\3\3\2\2\1d\257ap\312op\312op\312o" - "p\312op\312op\312oP\216N!\3\4\313\14\20\313\14\20\313\14\20\313\14\20Q\10" - "\12fec\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337yxv0IkFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Df\225\2\3\5SR" - "S\267\266\266\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377qpp<\6\7\34\4\5,H)p\312op\312op\312o" - "p\312op\312op\312o-N,=\5\6\313\14\20\313\14\20\313\14\20\313\14\20\37\5\6" - "\233\232\230\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337~}{-EeFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" - "\23\35+/..\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377]\\\\P\6\10\221\14\17\2\1\1>" - "f:p\310np\312op\312oo\307nDr@\2\1\1\213\13\15\313\14\20\313\14\20\313\14" - "\20\254\14\17\4\4\4\323\322\316\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\232\231\227#4MFj\233Fj\233Fj\233Fj\233Fj\233" - "Fj\233Fj\233Fj\233Fj\2335Pv\6\5\6\312\312\312\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377IHH`" - "\7\11\313\14\20\177\14\16\4\1\1\26\"\24""5Y2.M,\17\26\15\3\1\1p\12\14\313" - "\14\20\313\14\20\313\14\20\313\14\20V\10\12DDC\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\315\314\310\23\33" - "'Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233\36.D\37\37" - "\37\345\345\346\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377433p\10\12\313\14\20\313\14\20\250\15\20Y\10\12C" - "\7\10F\7\10h\11\13\260\15\20\313\14\20\313\14\20\313\14\20\313\14\20\261" - "\15\20\7\1\1\256\255\252\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337:::=\\\207Fj\233Fj\233Fj" - "\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Eh\230\26!1\40\40\40\304\304\304" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\40\37\37\200\11\13\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" - "\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\312\14\20""8\7\10" - "NML\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\226\226\223\34+>Fj\233Fj\233Fj\233F" - "j\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Dh\230\37/D\2\2\3QQQ\256\256\256" - "\344\344\344\361\361\361\335\335\335\247\247\247\11\10\10r\7\11\313\14\20" - "\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" - "\14\20\313\14\20\313\14\20j\13\15\32\32\31\323\322\316\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\342\341\3359982LpFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj" - "\233Fj\233Fj\233Fj\233Fj\2339V}\33)<\7\13\20\0\0\1\0\0\0\1\1\2\11\15\23\16" - "\25\36*\4\5\312\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" - "\14\20\313\14\20\313\14\20\313\14\20s\14\16\17\16\16\265\264\261\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" - "\337\344\343\337\344\343\337\344\343\337\344\343\337\312\311\306\31\34\37" - ";Z\203Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" - "Fj\233Fj\233Dg\227Dg\227Eh\230Ei\232\"-;\4\4\3w\14\16\313\14\20\313\14\20" - "\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\271\15\21E\11\12\22\22" - "\21\263\262\257\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\263\262\257\24\30\36""8U}Fj\233Fj\233Fj\233Fj\233" - "Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Dg\226\30$4g" - "fd\250\247\244\13\12\12Y\11\13\266\16\21\313\14\20\313\14\20\313\14\20\262" - "\16\21d\12\14\15\3\3>=<\314\313\307\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\274" - "\273\270$%&(<XEi\231Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" - "Fj\233Fj\2339V~\22\31\"}}z\344\343\337\344\343\337\267\266\263876\4\2\2+" - "\5\5A\5\6&\5\6\3\2\2""887\236\236\233\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\331\330\324hhf\23\30\37*?]Ac\220Fj\233" - "Fj\233Fj\233Fj\233Fj\233Fj\233Ei\2324Os\27\"2998\266\265\262\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\305\304\300\224\223\220" - "\210\210\206\232\231\226\313\312\307\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" - "\344\343\337\316\315\312xwu000\21\30\"\33)<!2H!3J\35,@\24\36,\34\36!YXW\255" - "\254\251\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\331\330\324\270\267\264\250\247\244\247\246\243\263" - "\262\257\314\313\307\344\342\336\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" - "\343\337\344\343\337\344\343\337\344\343\337"; + // make sure we only look at fractional part + x -= floor(x); + y -= floor(y); + int quad_index = ((x >= 0.5 ? 1 : 0) + (y >= 0.5 ? 2 : 0)); - //replicate to make 256x256x3 pixels - for(int line=0; line<256; line++) + switch (quad_index) { - memcpy(((unsigned char *) buffer)+line*256*3, logo+(line % 64)*64*3, 64*3); - memcpy(((unsigned char *) buffer)+line*256*3+64*3, logo+(line % 64)*64*3, 64*3); - memcpy(((unsigned char *) buffer)+line*256*3+64*3*2, logo+(line % 64)*64*3, 64*3); - memcpy(((unsigned char *) buffer)+line*256*3+64*3*3, logo+(line % 64)*64*3, 64*3); + case 0: + quad<<"0"; + break; + case 1: + quad<<"1"; + break; + case 2: + quad<<"2"; + break; + case 3: + quad<<"3"; + break; } +// level down + x *= 2; + y *= 2; + } + + return 0; +} +/** RGB buffer filling when the tile is not found */ +void TileMapImageIO::FillCacheFaults(void* buffer) +{ + const char * logo = + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337fedZZXZZXZZX\333\332\326" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\5\5\5T\4\6=" + "\3\4\4\4\4\340\337\333\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\330\327\323KKJ<" + "<:<<;\261\260\255\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\336\335\331\1\1\1\253\10\14n\6\10" + "\"\"!\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\266\265\262\36\36\36" + "\261\261\261UUUmmk\341\340\334\322\321\316\312\312\306\312\312\306\312\312" + "\306\312\312\306\324\323\317\343\342\336\326\325\321\0\0\0\253\11\14Z\5\6" + "FFE\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\264\263\260+++\377\377\377" + "zzz\7\7\6\5\5\5\4\4\4\21\21\21\23\23\23\23\23\23\20\20\20\3\3\3\7\7\7\33" + "\33\32\0\0\0\257\11\15""3\3\4jig\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\250\250\245PPN\13" + "\13\13;;;\377\377\377\311\311\311\300\300\300\343\343\343\372\372\372\377" + "\377\377\377\377\377\377\377\377\377\377\377\370\370\370\337\337\337a``\0" + "\0\0\266\12\16\15\1\1\216\216\213\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\250\247\244++*\20\20\20lll\310\310\310\375" + "\375\375\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377hhh\0" + "\0\0\244\11\14\0\0\0\262\261\256\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\334\333\330\\[Z\14\14\14\202\202\202\361\361\361\371\371\371\273" + "\273\274\246\246\247\377\377\377\277\277\277\206\206\206\257\257\257\351" + "\352\351\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\377\377POO\1\0\0\200\7\12\0\0\0\326\325\321\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\324\323\320211777\333\333\333\324\324\324bbb\15\15\15\0\0\0...\377" + "\377\377\214\214\214\2\2\3\2\2\3\2\2\2>>>\254\254\254\375\375\375\377\377" + "\377\377\377\377\377\377\377766\5\0\0P\4\6\26\26\26\344\343\337\344\343\337" + "\343\342\336\330\327\323\334\333\330\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\327\326\323--,VVV\360\360\360mmm\2\2\2\24\37-2Lo1Jm...\377\377" + "\377\244\244\244\6\11\14Df\2241Kl\26!.\1\1\1""222\322\322\322\377\377\377" + "\377\377\377\35\35\35\0\0\0\0\0\0\12\12\11--,\20\20\17\1\1\1\2\1\1\1\1\1" + "\4\4\4\34\34\34""443llj\314\313\307\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\342\336EEDHHH\342\342\342111\12\17\26""6RxFj\233Fj\2334Nr.." + ".\377\377\377\310\310\310\0\0\0Ab\216Fj\233Fj\233:X\177\20\30\"\11\11\11" + "nnn211\0\0\0\0\0\0\0\0\0\16\2\3j\13\15\250\15\20\275\15\20\306\14\20\303" + "\14\20\266\15\20\237\14\17~\13\15""5\7\10\14\13\13\230\227\224\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\230\230\225\25\25\25\331\331\331&&&\25\40.Be\223" + "Fj\233Fj\233Fj\2334Nr...\377\377\377\364\364\364\4\4\4""0IiFj\233Fj\233B" + "c\220\"2F\2\2\1\0\0\0\0\0\0\0\0\0\12\20\11\36""2\33\16\26\15\0\0\0\24\3\4" + "d\11\13\272\15\21\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\206\14" + "\17\11\5\5\253\252\247\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\33700/\212\212\212IIJ\17\27!Dg\227" + "Fj\233Fj\233Fj\233Fj\2334Nr...\377\377\377\377\377\377BBB\25\37,Fj\2330E" + "c\7\11\14\7\12\16!1F+@]\4\5\10\0\0\0""2V0p\312op\312ob\255`:b7\13\17\11\21" + "\3\3\225\14\17\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20i\12\14$" + "$$\342\341\335\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\323\322\317\2\2\2\223\223\223\3\5\7>^\212Fj\233Fj\233Fj\233" + "Fj\233Fj\2334Nr...\377\377\377\377\377\377\270\271\271\1\1\1\26\37+\5\7\12" + "(<VDf\225Fj\233Fj\2330Hi\0\0\0""9e7p\312op\312op\312op\312ol\300j-H)\6\2" + "\2\222\14\17\313\14\20\313\14\20\313\14\20\313\14\20\302\15\21\16\3\3\251" + "\250\246\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\275\274\271\33\33\33""222!2IFj\233Fj\233Fj\233Fj\233Fj\233Fj\233" + "4Nr...\377\377\377\377\377\377\363\363\363\32\32\31\1\1\1""4NoFj\233Fj\233" + "Fj\233Fj\2333Lm\0\0\0:f8p\312op\312op\312op\312op\312op\312o3S/\12\2\2\255" + "\15\20\313\14\20\313\14\20\313\14\20\313\14\20E\7\10qpn\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\276\275\272\3\3\3\4" + "\6\11?_\213Fj\233Fj\233Fj\233Fj\233Fj\233Fj\2334Nr...\377\377\377\374\373" + "\373FEELKK???\3\5\7#5K;Y\2006Rw\37.B\3\4\5\0\0\0.P,p\312op\312op\312op\312" + "op\312op\312oo\307m\30%\26A\7\10\313\14\20\313\14\20\313\14\20\313\14\20" + "l\11\13TSR\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\226\225\222!0D=\\\207Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" + "4Nr+++\377\377\377\206\205\205GFF\374\374\374\372\373\372\204\205\204\25" + "\25\25\0\0\0\0\0\0\"#\"EDD\0\0\0\31(\26p\312op\312op\312op\312op\312op\312" + "op\312oK\203I\35\3\4\313\14\20\313\14\20\313\14\20\313\14\20p\11\13SRQ\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337yyv/" + "GhFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\2337Sz\14\14\14\346\345\345" + ",++\357\356\356\377\377\377\377\377\377\377\377\377\373\373\373\331\331\331" + "\332\332\332\375\376\376\206\205\205\6\3\3\2\2\1d\257ap\312op\312op\312o" + "p\312op\312op\312oP\216N!\3\4\313\14\20\313\14\20\313\14\20\313\14\20Q\10" + "\12fec\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337yxv0IkFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Df\225\2\3\5SR" + "S\267\266\266\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\377\377\377\377\377\377\377\377\377qpp<\6\7\34\4\5,H)p\312op\312op\312o" + "p\312op\312op\312o-N,=\5\6\313\14\20\313\14\20\313\14\20\313\14\20\37\5\6" + "\233\232\230\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337~}{-EeFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" + "\23\35+/..\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\377\377\377\377\377\377\377\377\377\377\377]\\\\P\6\10\221\14\17\2\1\1>" + "f:p\310np\312op\312oo\307nDr@\2\1\1\213\13\15\313\14\20\313\14\20\313\14" + "\20\254\14\17\4\4\4\323\322\316\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\232\231\227#4MFj\233Fj\233Fj\233Fj\233Fj\233" + "Fj\233Fj\233Fj\233Fj\2335Pv\6\5\6\312\312\312\377\377\377\377\377\377\377" + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377IHH`" + "\7\11\313\14\20\177\14\16\4\1\1\26\"\24""5Y2.M,\17\26\15\3\1\1p\12\14\313" + "\14\20\313\14\20\313\14\20\313\14\20V\10\12DDC\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\315\314\310\23\33" + "'Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233\36.D\37\37" + "\37\345\345\346\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\377\377\377\377\377\377433p\10\12\313\14\20\313\14\20\250\15\20Y\10\12C" + "\7\10F\7\10h\11\13\260\15\20\313\14\20\313\14\20\313\14\20\313\14\20\261" + "\15\20\7\1\1\256\255\252\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337:::=\\\207Fj\233Fj\233Fj" + "\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Eh\230\26!1\40\40\40\304\304\304" + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + "\40\37\37\200\11\13\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" + "\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\312\14\20""8\7\10" + "NML\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\226\226\223\34+>Fj\233Fj\233Fj\233F" + "j\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Dh\230\37/D\2\2\3QQQ\256\256\256" + "\344\344\344\361\361\361\335\335\335\247\247\247\11\10\10r\7\11\313\14\20" + "\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" + "\14\20\313\14\20\313\14\20j\13\15\32\32\31\323\322\316\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\342\341\3359982LpFj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj" + "\233Fj\233Fj\233Fj\233Fj\2339V}\33)<\7\13\20\0\0\1\0\0\0\1\1\2\11\15\23\16" + "\25\36*\4\5\312\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\313" + "\14\20\313\14\20\313\14\20\313\14\20s\14\16\17\16\16\265\264\261\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343" + "\337\344\343\337\344\343\337\344\343\337\344\343\337\312\311\306\31\34\37" + ";Z\203Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" + "Fj\233Fj\233Dg\227Dg\227Eh\230Ei\232\"-;\4\4\3w\14\16\313\14\20\313\14\20" + "\313\14\20\313\14\20\313\14\20\313\14\20\313\14\20\271\15\21E\11\12\22\22" + "\21\263\262\257\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\263\262\257\24\30\36""8U}Fj\233Fj\233Fj\233Fj\233" + "Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Dg\226\30$4g" + "fd\250\247\244\13\12\12Y\11\13\266\16\21\313\14\20\313\14\20\313\14\20\262" + "\16\21d\12\14\15\3\3>=<\314\313\307\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\274" + "\273\270$%&(<XEi\231Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233Fj\233" + "Fj\233Fj\2339V~\22\31\"}}z\344\343\337\344\343\337\267\266\263876\4\2\2+" + "\5\5A\5\6&\5\6\3\2\2""887\236\236\233\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\331\330\324hhf\23\30\37*?]Ac\220Fj\233" + "Fj\233Fj\233Fj\233Fj\233Fj\233Ei\2324Os\27\"2998\266\265\262\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\305\304\300\224\223\220" + "\210\210\206\232\231\226\313\312\307\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337" + "\344\343\337\316\315\312xwu000\21\30\"\33)<!2H!3J\35,@\24\36,\34\36!YXW\255" + "\254\251\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\331\330\324\270\267\264\250\247\244\247\246\243\263" + "\262\257\314\313\307\344\342\336\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344\343\337\344" + "\343\337\344\343\337\344\343\337\344\343\337"; + + //replicate to make 256x256x3 pixels + for (int line=0; line<256; line++) + { + memcpy(((unsigned char *) buffer)+line*256*3, logo+(line % 64)*64*3, 64*3); + memcpy(((unsigned char *) buffer)+line*256*3+64*3, logo+(line % 64)*64*3, 64*3); + memcpy(((unsigned char *) buffer)+line*256*3+64*3*2, logo+(line % 64)*64*3, 64*3); + memcpy(((unsigned char *) buffer)+line*256*3+64*3*3, logo+(line % 64)*64*3, 64*3); } +} + } // end namespace otb diff --git a/Code/IO/otbTileMapImageIO.h b/Code/IO/otbTileMapImageIO.h index 2d43e7aaf09ad06a0e11b560cb0993e304ea7a8e..67525cb16a8590704a1ba77edeead300ef8b261d 100644 --- a/Code/IO/otbTileMapImageIO.h +++ b/Code/IO/otbTileMapImageIO.h @@ -55,147 +55,156 @@ namespace otb * \ingroup IOFilters * */ - class ITK_EXPORT TileMapImageIO : public itk::ImageIOBase, - public MetaDataKey - { - public: +class ITK_EXPORT TileMapImageIO : public itk::ImageIOBase, + public MetaDataKey +{ +public: - typedef unsigned char InputPixelType; + typedef unsigned char InputPixelType; - /** Standard class typedefs. */ - typedef TileMapImageIO Self; - typedef itk::ImageIOBase Superclass; - typedef itk::SmartPointer<Self> Pointer; + /** Standard class typedefs. */ + typedef TileMapImageIO Self; + typedef itk::ImageIOBase Superclass; + typedef itk::SmartPointer<Self> Pointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(TileMapImageIO, itk::ImageIOBase); + /** Run-time type information (and related methods). */ + itkTypeMacro(TileMapImageIO, itk::ImageIOBase); /** Set/Get the level of compression for the output images. * 0-9; 0 = none, 9 = maximum. */ - itkSetMacro(CompressionLevel, int); - itkGetMacro(CompressionLevel, int); - - virtual void SetCacheDirectory (const char* _arg) - { - if ( _arg && (_arg == this->m_CacheDirectory) ) { return;} - if (_arg) - { - this->m_CacheDirectory = _arg; - this->useCache=true; - } - else - { - this->m_CacheDirectory = ""; - this->useCache=false; - } - this->Modified(); - } - - virtual void SetCacheDirectory (const std::string & _arg) - { - this->SetCacheDirectory( _arg.c_str() ); - this->useCache=true; - } - - itkSetMacro(Depth, int); - itkGetMacro(Depth, int); - - itkGetStringMacro(CacheDirectory); - - /*-------- This part of the interface deals with reading data. ------ */ + itkSetMacro(CompressionLevel, int); + itkGetMacro(CompressionLevel, int); + + virtual void SetCacheDirectory (const char* _arg) + { + if ( _arg && (_arg == this->m_CacheDirectory) ) + { + return; + } + if (_arg) + { + this->m_CacheDirectory = _arg; + this->useCache=true; + } + else + { + this->m_CacheDirectory = ""; + this->useCache=false; + } + this->Modified(); + } + + virtual void SetCacheDirectory (const std::string & _arg) + { + this->SetCacheDirectory( _arg.c_str() ); + this->useCache=true; + } + + itkSetMacro(Depth, int); + itkGetMacro(Depth, int); + + itkGetStringMacro(CacheDirectory); + + /*-------- This part of the interface deals with reading data. ------ */ /** Determine the file type. Returns true if this ImageIO can read the * file specified. */ - virtual bool CanReadFile(const char*); + virtual bool CanReadFile(const char*); - /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ - virtual bool CanStreamRead(){ return true; }; + /** Determine the file type. Returns true if the ImageIO can stream read the specified file */ + virtual bool CanStreamRead() + { + return true; + }; - /** Set the spacing and dimention information for the set filename. */ - virtual void ReadImageInformation(); + /** Set the spacing and dimention information for the set filename. */ + virtual void ReadImageInformation(); - /** Reads the data from disk into the memory buffer provided. */ - virtual void Read(void* buffer); + /** Reads the data from disk into the memory buffer provided. */ + virtual void Read(void* buffer); - /** Reads 3D data from multiple files assuming one slice per file. */ - virtual void ReadVolume(void* buffer); + /** Reads 3D data from multiple files assuming one slice per file. */ + virtual void ReadVolume(void* buffer); - /*-------- This part of the interfaces deals with writing data. ----- */ + /*-------- This part of the interfaces deals with writing data. ----- */ /** Determine the file type. Returns true if this ImageIO can read the * file specified. */ - virtual bool CanWriteFile(const char*); + virtual bool CanWriteFile(const char*); - /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ + /** Determine the file type. Returns true if the ImageIO can stream write the specified file */ //THOMAS - virtual bool CanStreamWrite() { return true; }; + virtual bool CanStreamWrite() + { + return true; + }; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ - virtual void WriteImageInformation(); + virtual void WriteImageInformation(); /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegion has been set properly. */ - virtual void Write(const void* buffer); + virtual void Write(const void* buffer); // JULIEN: NOT USED, NOT IMPLEMENTED //void SampleImage(void* buffer,int XBegin, int YBegin, int SizeXRead, int SizeYRead, int XSample, int YSample); - protected: - /** Construtor.*/ - TileMapImageIO(); - /** Destructor.*/ - ~TileMapImageIO(); - - void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Read all information on the image*/ - void InternalReadImageInformation(); - /** Write all information on the image*/ - void InternalWriteImageInformation(); - /** Dimension along Ox of the image*/ - int m_width; - /** Dimension along Oy of the image*/ - int m_height; - /** Number of bands of the image*/ - int m_NbBands; - /** Buffer*/ +protected: + /** Construtor.*/ + TileMapImageIO(); + /** Destructor.*/ + ~TileMapImageIO(); + + void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Read all information on the image*/ + void InternalReadImageInformation(); + /** Write all information on the image*/ + void InternalWriteImageInformation(); + /** Dimension along Ox of the image*/ + int m_width; + /** Dimension along Oy of the image*/ + int m_height; + /** Number of bands of the image*/ + int m_NbBands; + /** Buffer*/ //float **pafimas; /** Determines the level of compression for written files. * Range 0-9; 0 = none, 9 = maximum , default = 4 */ - int m_CompressionLevel; - const char* m_currentfile; - - private: - TileMapImageIO(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - void InternalRead(double x, double y, void* buffer); - void InternalWrite(double x, double y, const void* buffer); - void BuildFileName(std::ostringstream& quad, std::ostringstream& filename); - void GetFromNetGM(std::ostringstream& filename, double x, double y); - void GetFromNetOSM(std::ostringstream& filename, double x, double y); - void FillCacheFaults(void* buffer); - int XYToQuadTree(double x, double y, std::ostringstream& quad); - int XYToQuadTree2(double x, double y, std::ostringstream& quad); - - /** Nombre d'octets par pixel */ - int m_NbOctetPixel; - - /** Resolution depth*/ - int m_Depth; - bool useCache; - std::string m_CacheDirectory; - std::string m_ServerName; - std::string m_FileSuffix; - std::string m_AddressMode; - - bool m_FlagWriteImageInformation; - - }; + int m_CompressionLevel; + const char* m_currentfile; + +private: + TileMapImageIO(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + void InternalRead(double x, double y, void* buffer); + void InternalWrite(double x, double y, const void* buffer); + void BuildFileName(std::ostringstream& quad, std::ostringstream& filename); + void GetFromNetGM(std::ostringstream& filename, double x, double y); + void GetFromNetOSM(std::ostringstream& filename, double x, double y); + void FillCacheFaults(void* buffer); + int XYToQuadTree(double x, double y, std::ostringstream& quad); + int XYToQuadTree2(double x, double y, std::ostringstream& quad); + + /** Nombre d'octets par pixel */ + int m_NbOctetPixel; + + /** Resolution depth*/ + int m_Depth; + bool useCache; + std::string m_CacheDirectory; + std::string m_ServerName; + std::string m_FileSuffix; + std::string m_AddressMode; + + bool m_FlagWriteImageInformation; + +}; } // end namespace otb diff --git a/Code/IO/otbVectorDataFileReader.h b/Code/IO/otbVectorDataFileReader.h index 1951a93ff8d98eeb19555bd3b3b8108d0d9a9ec8..4337903c1cdf721203bcc89be90738730baf0009 100644 --- a/Code/IO/otbVectorDataFileReader.h +++ b/Code/IO/otbVectorDataFileReader.h @@ -36,17 +36,17 @@ public: /** Constructor. */ VectorDataFileReaderException(const char *file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown") : - itk::ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown") : + itk::ExceptionObject(file, line, message, loc) { } /** Constructor. */ VectorDataFileReaderException(const std::string &file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown") : - itk::ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown") : + itk::ExceptionObject(file, line, message, loc) { } }; diff --git a/Code/IO/otbVectorDataFileReader.txx b/Code/IO/otbVectorDataFileReader.txx index 937ee63a625ba721c84f750ab1d60a63c4a877e5..d1a9f348e9fb3932ea57ac19ff03873b3358f5cc 100644 --- a/Code/IO/otbVectorDataFileReader.txx +++ b/Code/IO/otbVectorDataFileReader.txx @@ -48,49 +48,49 @@ VectorDataFileReader<TOutputVectorData> { } - /** Test whether the given filename exist and it is readable, - this is intended to be called before attempting to use - VectorDataIO classes for actually reading the file. If the file - doesn't exist or it is not readable, and exception with an - approriate message will be thrown. */ +/** Test whether the given filename exist and it is readable, + this is intended to be called before attempting to use + VectorDataIO classes for actually reading the file. If the file + doesn't exist or it is not readable, and exception with an + approriate message will be thrown. */ template <class TOutputVectorData> void VectorDataFileReader<TOutputVectorData> ::TestFileExistanceAndReadability() { - // Test if the file exists. - if( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) - { - VectorDataFileReaderException e(__FILE__, __LINE__); + // Test if the file exists. + if ( ! itksys::SystemTools::FileExists( this->m_FileName.c_str() ) ) + { + VectorDataFileReaderException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg <<"The file doesn't exists. " + << std::endl << "Filename = " << this->m_FileName + << std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; + } + + // Test if the file can be open for reading access. + //Only if m_FileName speciy a filname (not a dirname) + if ( System::IsAFileName( this->m_FileName ) == true ) + { + std::ifstream readTester; + readTester.open( this->m_FileName.c_str() ); + if ( readTester.fail() ) + { + readTester.close(); itk::OStringStream msg; - msg <<"The file doesn't exists. " - << std::endl << "Filename = " << this->m_FileName - << std::endl; - e.SetDescription(msg.str().c_str()); + msg <<"The file couldn't be opened for reading. " + << std::endl << "Filename: " << this->m_FileName + << std::endl; + VectorDataFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); throw e; return; - } - // Test if the file can be open for reading access. - //Only if m_FileName speciy a filname (not a dirname) - if( System::IsAFileName( this->m_FileName ) == true ) - { - std::ifstream readTester; - readTester.open( this->m_FileName.c_str() ); - if( readTester.fail() ) - { - readTester.close(); - itk::OStringStream msg; - msg <<"The file couldn't be opened for reading. " - << std::endl << "Filename: " << this->m_FileName - << std::endl; - VectorDataFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); - throw e; - return; - - } - readTester.close(); } + readTester.close(); + } } template <class TOutputVectorData> @@ -100,10 +100,10 @@ VectorDataFileReader<TOutputVectorData> { itkDebugMacro("setting VectorDataIO to " << vectorDataIO ); if (this->m_VectorDataIO != vectorDataIO ) - { + { this->m_VectorDataIO = vectorDataIO; this->Modified(); - } + } m_UserSpecifiedVectorDataIO = true; } @@ -120,55 +120,55 @@ VectorDataFileReader<TOutputVectorData> // Check to see if we can read the file given the name or prefix // if ( m_FileName == "" ) - { + { throw VectorDataFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); - } + } // Test if the file exist and if it can be open. // and exception will be thrown otherwise. // try - { + { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); - } - catch(itk::ExceptionObject &err) - { + } + catch (itk::ExceptionObject &err) + { m_ExceptionMessage = err.GetDescription(); - } + } if ( m_UserSpecifiedVectorDataIO == false ) //try creating via factory - { + { m_VectorDataIO = VectorDataIOFactory<TOutputVectorData>::CreateVectorDataIO( m_FileName.c_str(), VectorDataIOFactory<TOutputVectorData>::ReadMode ); - } + } if ( m_VectorDataIO.IsNull() ) - { + { itk::OStringStream msg; msg << " Could not create IO object for file " - << m_FileName.c_str() << std::endl; + << m_FileName.c_str() << std::endl; if (m_ExceptionMessage.size()) - { + { msg << m_ExceptionMessage; - } + } else - { + { msg << " Tried to create one of the following:" << std::endl; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbVectorDataIOBase"); - for(std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { VectorDataIOBase<TOutputVectorData>* io = dynamic_cast<VectorDataIOBase<TOutputVectorData>*>(i->GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; - } + } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; - } + } VectorDataFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; - } + } m_VectorDataIO->SetFileName(m_FileName.c_str()); @@ -192,14 +192,14 @@ VectorDataFileReader<TOutputVectorData> // Test if the file exist and if it can be open. // and exception will be thrown otherwise. try - { + { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); - } - catch(itk::ExceptionObject &err) - { + } + catch (itk::ExceptionObject &err) + { m_ExceptionMessage = err.GetDescription(); - } + } // Tell the VectorDataIO to read the file // @@ -220,14 +220,14 @@ VectorDataFileReader<TOutputVectorData> Superclass::PrintSelf(os, indent); if (m_VectorDataIO) - { + { os << indent << "VectorDataIO: \n"; m_VectorDataIO->Print(os, indent.GetNextIndent()); - } + } else - { + { os << indent << "m_VectorDataIO: (null)" << "\n"; - } + } os << indent << "UserSpecifiedVectorDataIO flag: " << m_UserSpecifiedVectorDataIO << "\n"; os << indent << "m_FileName: " << m_FileName << "\n"; diff --git a/Code/IO/otbVectorDataFileWriter.h b/Code/IO/otbVectorDataFileWriter.h index 5875ff257d334b44b3e164ee6e95371a7cc79523..424307cfd87133a89aaeab23267849a1b1aaa856 100644 --- a/Code/IO/otbVectorDataFileWriter.h +++ b/Code/IO/otbVectorDataFileWriter.h @@ -36,27 +36,27 @@ public: /** Constructor. */ VectorDataFileWriterException(const char *file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) { } /** Constructor. */ VectorDataFileWriterException(const std::string &file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) { } }; - /** \class VectorDataFileWriter - * \brief This class writes vector data file format (shapefile and KML) - * - * \ingroup IO - */ +/** \class VectorDataFileWriter + * \brief This class writes vector data file format (shapefile and KML) + * + * \ingroup IO + */ template <class TInputVectorData> class ITK_EXPORT VectorDataFileWriter : public itk::ProcessObject @@ -89,7 +89,10 @@ public : virtual void GenerateData(); - virtual void Update() { this->Write(); } + virtual void Update() + { + this->Write(); + } /** Specify the name of the output shapefile to write. */ diff --git a/Code/IO/otbVectorDataFileWriter.txx b/Code/IO/otbVectorDataFileWriter.txx index 3b25c5d4c7bce4a59cd323fa0a703ac99fba8779..33a54294a860ce0018dbdab0d5797f122465c245 100644 --- a/Code/IO/otbVectorDataFileWriter.txx +++ b/Code/IO/otbVectorDataFileWriter.txx @@ -33,8 +33,8 @@ namespace otb template <class TInputVectorData> VectorDataFileWriter<TInputVectorData> ::VectorDataFileWriter() : m_FileName(""), - m_VectorDataIO(0), - m_UserSpecifiedVectorDataIO(false) + m_VectorDataIO(0), + m_UserSpecifiedVectorDataIO(false) { } /** @@ -66,12 +66,12 @@ VectorDataFileWriter<TInputVectorData> ::GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } + } return static_cast<TInputVectorData*> - (this->ProcessObject::GetInput(0)); + (this->ProcessObject::GetInput(0)); } //--------------------------------------------------------- @@ -95,60 +95,60 @@ VectorDataFileWriter<TInputVectorData> // Make sure input is available if ( input == 0 ) - { + { itkExceptionMacro(<< "No input to writer!"); - } + } // Make sure that we can write the file given the name // if ( m_FileName == "" ) - { + { itkExceptionMacro(<<"No filename was specified"); - } + } if ( m_VectorDataIO.IsNull() ) //try creating via factory - { + { itkDebugMacro(<<"Attempting factory creation of VectorDataIO for file: " << m_FileName); m_VectorDataIO = VectorDataIOFactory<TInputVectorData>::CreateVectorDataIO( m_FileName.c_str(), - VectorDataIOFactory<TInputVectorData>::WriteMode ); + VectorDataIOFactory<TInputVectorData>::WriteMode ); m_FactorySpecifiedVectorDataIO = true; - } + } else + { + if ( m_FactorySpecifiedVectorDataIO && !m_VectorDataIO->CanWriteFile( m_FileName.c_str() ) ) { - if( m_FactorySpecifiedVectorDataIO && !m_VectorDataIO->CanWriteFile( m_FileName.c_str() ) ) - { itkDebugMacro(<<"VectorDataIO exists but doesn't know how to write file:" << m_FileName ); itkDebugMacro(<<"Attempting creation of VectorDataIO with a factory for file:" << m_FileName); m_VectorDataIO = VectorDataIOFactory<TInputVectorData>::CreateVectorDataIO( m_FileName.c_str(), - VectorDataIOFactory<TInputVectorData>::WriteMode ); + VectorDataIOFactory<TInputVectorData>::WriteMode ); m_FactorySpecifiedVectorDataIO = true; - } } + } if ( m_VectorDataIO.IsNull() ) - { + { VectorDataFileWriterException e(__FILE__, __LINE__); itk::OStringStream msg; msg << " Could not create IO object for file " - << m_FileName.c_str() << std::endl; + << m_FileName.c_str() << std::endl; msg << " Tried to create one of the following:" << std::endl; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbVectorDataIOBase"); - for(std::list<LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { VectorDataIOBase<TInputVectorData>* io = dynamic_cast<VectorDataIOBase<TInputVectorData>*>(i->GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; - } + } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; e.SetDescription(msg.str().c_str()); e.SetLocation(ITK_LOCATION); throw e; - } + } // NOTE: this const_cast<> is due to the lack of const-correctness // of the ProcessObject. @@ -156,9 +156,9 @@ VectorDataFileWriter<TInputVectorData> // Make sure the data is up-to-date. - if( nonConstVectorData->GetSource() ) + if ( nonConstVectorData->GetSource() ) { - nonConstVectorData->GetSource()->Update(); + nonConstVectorData->GetSource()->Update(); } // Notify start event observers @@ -172,9 +172,9 @@ VectorDataFileWriter<TInputVectorData> // Release upstream data if requested if ( input->ShouldIReleaseData() ) - { + { nonConstVectorData->ReleaseData(); - } + } } diff --git a/Code/IO/otbVectorDataIOBase.h b/Code/IO/otbVectorDataIOBase.h index 7312e669b1276aec506f228d06bdb83a4ee7019e..d98b371da9a3ccccaff35c601a1dc1de462cb041 100644 --- a/Code/IO/otbVectorDataIOBase.h +++ b/Code/IO/otbVectorDataIOBase.h @@ -94,13 +94,13 @@ public: itkSetEnumMacro(ByteOrder,ByteOrder); itkGetEnumMacro(ByteOrder,ByteOrder); void SetByteOrderToBigEndian() - { + { this->SetByteOrder(BigEndian); - } + } void SetByteOrderToLittleEndian() - { + { this->SetByteOrder(LittleEndian); - } + } /** Convenience method returns the ByteOrder as a string. This can be * used for writing output files. */ @@ -118,13 +118,13 @@ public: /** Determine if the VectorDataIO can stream reading from this file. Default is false. */ virtual bool CanStreamRead() - { + { return false; - } + } -/* /\** Read the spacing and dimentions of the VectorData. */ -/* * Assumes SetFileName has been called with a valid file name. *\/ */ -/* virtual void ReadVectorDataInformation() = 0; */ + /* /\** Read the spacing and dimentions of the VectorData. */ + /* * Assumes SetFileName has been called with a valid file name. *\/ */ + /* virtual void ReadVectorDataInformation() = 0; */ /** Reads the data from disk into the memory buffer provided. */ virtual void Read(VectorDataPointerType data) = 0; @@ -139,13 +139,13 @@ public: /** Determine if the ImageIO can stream writing to this file. Default is false. */ virtual bool CanStreamWrite() - { + { return false; - } + } -/* /\** Writes the spacing and dimentions of the VectorData. */ -/* * Assumes SetFileName has been called with a valid file name. *\/ */ -/* virtual void WriteVectorDataInformation() = 0; */ + /* /\** Writes the spacing and dimentions of the VectorData. */ + /* * Assumes SetFileName has been called with a valid file name. *\/ */ + /* virtual void WriteVectorDataInformation() = 0; */ /** 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 diff --git a/Code/IO/otbVectorDataIOBase.txx b/Code/IO/otbVectorDataIOBase.txx index a36703c9b901debc8e72d6058ebd63301fac0570..f36c23582cf7cbbc376048361dc1af13cb9fb15b 100644 --- a/Code/IO/otbVectorDataIOBase.txx +++ b/Code/IO/otbVectorDataIOBase.txx @@ -28,7 +28,7 @@ namespace otb template <class TData> VectorDataIOBase<TData> ::VectorDataIOBase() : - m_ByteOrder(OrderNotApplicable) + m_ByteOrder(OrderNotApplicable) { Reset(false); } @@ -55,16 +55,16 @@ VectorDataIOBase<TData> ::GetByteOrderAsString(ByteOrder t) const { std::string s; - switch(t) - { - case BigEndian: - return s = "BigEndian"; - case LittleEndian: - return s = "LittleEndian"; - case OrderNotApplicable: - default: - return s = "OrderNotApplicable"; - } + switch (t) + { + case BigEndian: + return s = "BigEndian"; + case LittleEndian: + return s = "LittleEndian"; + case OrderNotApplicable: + default: + return s = "OrderNotApplicable"; + } return s="OrderNotApplicable"; } diff --git a/Code/IO/otbVectorDataIOFactory.txx b/Code/IO/otbVectorDataIOFactory.txx index 425f10c3c3f673e76553adad8580819c15fe19ef..949cb2cbdb5e3bcf17478da813ee60a8fb0eb6db 100644 --- a/Code/IO/otbVectorDataIOFactory.txx +++ b/Code/IO/otbVectorDataIOFactory.txx @@ -42,39 +42,39 @@ VectorDataIOFactory<TData> std::list<VectorDataIOBasePointerType> possibleVectorDataIO; std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbVectorDataIOBase"); - for(std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); - i != allobjects.end(); ++i) - { + for (std::list<itk::LightObject::Pointer>::iterator i = allobjects.begin(); + i != allobjects.end(); ++i) + { VectorDataIOBaseType * io = dynamic_cast<VectorDataIOBaseType*>(i->GetPointer()); - if(io) - { + if (io) + { possibleVectorDataIO.push_back(io); - } + } else - { - itkGenericExceptionMacro(<< "Error VectorDataIO factory did not return an VectorDataIOBase: " - << (*i)->GetNameOfClass()); - } + { + itkGenericExceptionMacro(<< "Error VectorDataIO factory did not return an VectorDataIOBase: " + << (*i)->GetNameOfClass()); } - for(typename std::list<VectorDataIOBasePointerType>::iterator k = possibleVectorDataIO.begin(); - k != possibleVectorDataIO.end(); ++k) + } + for (typename std::list<VectorDataIOBasePointerType>::iterator k = possibleVectorDataIO.begin(); + k != possibleVectorDataIO.end(); ++k) + { + if ( mode == ReadMode ) { - if( mode == ReadMode ) + if ((*k)->CanReadFile(path)) { - if((*k)->CanReadFile(path)) - { return *k; - } } - else if( mode == WriteMode ) + } + else if ( mode == WriteMode ) + { + if ((*k)->CanWriteFile(path)) { - if((*k)->CanWriteFile(path)) - { return *k; - } - } + } + } return 0; } template <class TData> @@ -85,17 +85,17 @@ VectorDataIOFactory<TData> static bool firstTime = true; static itk::SimpleMutexLock mutex; - { + { // This helper class makes sure the Mutex is unlocked // in the event an exception is thrown. itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder( mutex ); - if( firstTime ) - { - itk::ObjectFactoryBase::RegisterFactory( SHPVectorDataIOFactory<TData>::New() ); - itk::ObjectFactoryBase::RegisterFactory( KMLVectorDataIOFactory<TData>::New() ); + if ( firstTime ) + { + itk::ObjectFactoryBase::RegisterFactory( SHPVectorDataIOFactory<TData>::New() ); + itk::ObjectFactoryBase::RegisterFactory( KMLVectorDataIOFactory<TData>::New() ); firstTime = false; - } } + } } } // end namespace otb diff --git a/Code/IO/otbVectorImage.h b/Code/IO/otbVectorImage.h index ea319b6b1e1988a74da66d5e3247f02d7017834e..590d0f9b9dd299813f08c439b9c5ac3bc4533f29 100644 --- a/Code/IO/otbVectorImage.h +++ b/Code/IO/otbVectorImage.h @@ -40,7 +40,7 @@ namespace otb */ template <class TPixel, unsigned int VImageDimension=2> class ITK_EXPORT VectorImage : public itk::VectorImage<TPixel, VImageDimension>, - public ImageBase + public ImageBase { public: @@ -75,8 +75,8 @@ public: typedef typename Superclass::IOPixelType IOPixelType; - /** Accessor type that convert data between internal and external - * representations. */ + /** Accessor type that convert data between internal and external + * representations. */ typedef itk::DefaultVectorPixelAccessor< InternalPixelType > AccessorType; /** Functor to provide a common API between DefaultPixelAccessor and @@ -85,7 +85,7 @@ public: /** Tyepdef for the functor used to access a neighborhood of pixel pointers.*/ typedef itk::VectorImageNeighborhoodAccessorFunctor< - Self > NeighborhoodAccessorFunctorType; + Self > NeighborhoodAccessorFunctorType; /** Dimension of the image. This constant is used by functions that are * templated over image type (as opposed to being templated over pixel type @@ -158,23 +158,31 @@ public: /** Return the Pixel Accessor object */ AccessorType GetPixelAccessor( void ) - { return AccessorType( this->GetNumberOfComponentsPerPixel() ); } + { + return AccessorType( this->GetNumberOfComponentsPerPixel() ); + } /** Return the Pixel Accesor object */ const AccessorType GetPixelAccessor( void ) const - { return AccessorType( this->GetNumberOfComponentsPerPixel() ); } + { + return AccessorType( this->GetNumberOfComponentsPerPixel() ); + } /** Return the NeighborhoodAccessor functor */ NeighborhoodAccessorFunctorType GetNeighborhoodAccessor() - { return NeighborhoodAccessorFunctorType( this->GetNumberOfComponentsPerPixel() ); } + { + return NeighborhoodAccessorFunctorType( this->GetNumberOfComponentsPerPixel() ); + } /** Return the NeighborhoodAccessor functor */ const NeighborhoodAccessorFunctorType GetNeighborhoodAccessor() const - { return NeighborhoodAccessorFunctorType(this->GetNumberOfComponentsPerPixel()); } + { + return NeighborhoodAccessorFunctorType(this->GetNumberOfComponentsPerPixel()); + } protected: VectorImage(); - virtual ~VectorImage(){}; + virtual ~VectorImage() {}; private: VectorImage(const Self&); //purposely not implemented diff --git a/Code/IO/otbVectorImage.txx b/Code/IO/otbVectorImage.txx index ff30066bad8d4f7fad0fbaf76f42023984fcb8bc..6c1ee3837758d7a698dcd57b1e573cfa5794bf5c 100644 --- a/Code/IO/otbVectorImage.txx +++ b/Code/IO/otbVectorImage.txx @@ -34,109 +34,109 @@ VectorImage<TPixel,VImageDimension>::VectorImage() } template <class TPixel, unsigned int VImageDimension> - std::string VectorImage<TPixel, VImageDimension>::GetProjectionRef( void ) const +std::string VectorImage<TPixel, VImageDimension>::GetProjectionRef( void ) const { - return ( ImageBase::GetProjectionRef( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetProjectionRef( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - std::string VectorImage<TPixel, VImageDimension>::GetGCPProjection( void ) const +std::string VectorImage<TPixel, VImageDimension>::GetGCPProjection( void ) const { - return ( ImageBase::GetGCPProjection( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetGCPProjection( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - unsigned int VectorImage<TPixel, VImageDimension>::GetGCPCount( void ) const +unsigned int VectorImage<TPixel, VImageDimension>::GetGCPCount( void ) const { - return ( ImageBase::GetGCPCount( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetGCPCount( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - OTB_GCP & VectorImage<TPixel, VImageDimension>::GetGCPs ( unsigned int GCPnum ) +OTB_GCP & VectorImage<TPixel, VImageDimension>::GetGCPs ( unsigned int GCPnum ) { - return ( this->ImageBase::GetGCPs( this->GetMetaDataDictionary(), GCPnum ) ); + return ( this->ImageBase::GetGCPs( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - std::string VectorImage<TPixel, VImageDimension>::GetGCPId( unsigned int GCPnum ) const +std::string VectorImage<TPixel, VImageDimension>::GetGCPId( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPId( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPId( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - std::string VectorImage<TPixel, VImageDimension>::GetGCPInfo( unsigned int GCPnum ) const +std::string VectorImage<TPixel, VImageDimension>::GetGCPInfo( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPInfo( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPInfo( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double VectorImage<TPixel, VImageDimension>::GetGCPRow( unsigned int GCPnum ) const +double VectorImage<TPixel, VImageDimension>::GetGCPRow( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPRow( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPRow( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double VectorImage<TPixel, VImageDimension>::GetGCPCol( unsigned int GCPnum ) const +double VectorImage<TPixel, VImageDimension>::GetGCPCol( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPCol( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPCol( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double VectorImage<TPixel, VImageDimension>::GetGCPX( unsigned int GCPnum ) const +double VectorImage<TPixel, VImageDimension>::GetGCPX( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPX( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPX( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double VectorImage<TPixel, VImageDimension>::GetGCPY( unsigned int GCPnum ) const +double VectorImage<TPixel, VImageDimension>::GetGCPY( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPY( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPY( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - double VectorImage<TPixel, VImageDimension>::GetGCPZ( unsigned int GCPnum ) const +double VectorImage<TPixel, VImageDimension>::GetGCPZ( unsigned int GCPnum ) const { - return ( ImageBase::GetGCPZ( this->GetMetaDataDictionary(), GCPnum ) ); + return ( ImageBase::GetGCPZ( this->GetMetaDataDictionary(), GCPnum ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetGeoTransform( void ) const +ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetGeoTransform( void ) const { - return ( ImageBase::GetGeoTransform( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetGeoTransform( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetUpperLeftCorner( void ) const +ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetUpperLeftCorner( void ) const { - return ( ImageBase::GetUpperLeftCorner( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetUpperLeftCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetUpperRightCorner( void ) const +ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetUpperRightCorner( void ) const { - return ( ImageBase::GetUpperRightCorner( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetUpperRightCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetLowerLeftCorner( void ) const +ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetLowerLeftCorner( void ) const { - return ( ImageBase::GetLowerLeftCorner( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetLowerLeftCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetLowerRightCorner( void ) const +ImageBase::VectorType VectorImage<TPixel, VImageDimension>::GetLowerRightCorner( void ) const { - return ( ImageBase::GetLowerRightCorner( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetLowerRightCorner( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - ImageBase::ImageKeywordlistType VectorImage<TPixel, VImageDimension>::GetImageKeywordlist( void ) +ImageBase::ImageKeywordlistType VectorImage<TPixel, VImageDimension>::GetImageKeywordlist( void ) { - return ( ImageBase::GetImageKeywordlist( this->GetMetaDataDictionary() ) ); + return ( ImageBase::GetImageKeywordlist( this->GetMetaDataDictionary() ) ); } template <class TPixel, unsigned int VImageDimension> - const ImageBase::ImageKeywordlistType VectorImage<TPixel, VImageDimension>::GetImageKeywordlist( void ) const +const ImageBase::ImageKeywordlistType VectorImage<TPixel, VImageDimension>::GetImageKeywordlist( void ) const { return ( ImageBase::GetImageKeywordlist( this->GetMetaDataDictionary() ) ); } diff --git a/Code/Learning/otbChangeProfileKernelFunctor.cxx b/Code/Learning/otbChangeProfileKernelFunctor.cxx index c67e9c3e98cc9a2c075923c124dd62392b73e42d..daa9754433ceaa4e1e4404fd8b8fae7031f56f35 100644 --- a/Code/Learning/otbChangeProfileKernelFunctor.cxx +++ b/Code/Learning/otbChangeProfileKernelFunctor.cxx @@ -48,14 +48,14 @@ ChangeProfileKernelFunctor double ChangeProfileKernelFunctor ::operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const + const svm_parameter & param ) const { double theMax(0.); double theCur(0.); - while(x->index != -1 && y->index != -1) + while (x->index != -1 && y->index != -1) { - if(x->index == y->index) + if (x->index == y->index) { theCur = fabs( x->value - y->value ); ++x; @@ -63,7 +63,7 @@ ChangeProfileKernelFunctor } else { - if(x->index > y->index) + if (x->index > y->index) ++y; else ++x; diff --git a/Code/Learning/otbChangeProfileKernelFunctor.h b/Code/Learning/otbChangeProfileKernelFunctor.h index f62a9cadf3b3fc870c5bd7039e7e63f1ecb451d1..e167c7960c60bcb74d46b3d7cc9bd6e3767c69c6 100644 --- a/Code/Learning/otbChangeProfileKernelFunctor.h +++ b/Code/Learning/otbChangeProfileKernelFunctor.h @@ -25,27 +25,27 @@ namespace otb { - /** \class ChangeProfileKernelFunctor - * \brief Change Profile Kernel. - * Performs a decision point of view dedicated to the multiscale - * change profile delivered by - * \subdoxygen{otb}{KullbackLeiblerProfileImageFilter}. - * - * It is implemented as a polynomial kernel: - * \f$ \exp - \left( \gamma \left( \max_i | x_i - y_i | \right)^\textrm{degree} + \textrm{coef} \right) \f$. - * - * The parameters \f$ \gamma \f$, \f$ \textrm{coef} \f$ and \f$ \textrm{degree} \f$ are - * to be fixed through \code SetValue \endcode with keywords: Gamma (def 1.0), - * Coef (def 1.0) and Degree (def 1.0). - */ +/** \class ChangeProfileKernelFunctor + * \brief Change Profile Kernel. + * Performs a decision point of view dedicated to the multiscale + * change profile delivered by + * \subdoxygen{otb}{KullbackLeiblerProfileImageFilter}. + * + * It is implemented as a polynomial kernel: + * \f$ \exp - \left( \gamma \left( \max_i | x_i - y_i | \right)^\textrm{degree} + \textrm{coef} \right) \f$. + * + * The parameters \f$ \gamma \f$, \f$ \textrm{coef} \f$ and \f$ \textrm{degree} \f$ are + * to be fixed through \code SetValue \endcode with keywords: Gamma (def 1.0), + * Coef (def 1.0) and Degree (def 1.0). + */ class ChangeProfileKernelFunctor - : public GenericKernelFunctorBase + : public GenericKernelFunctorBase { public: double operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const; + const svm_parameter & param ) const; ChangeProfileKernelFunctor (); virtual ~ChangeProfileKernelFunctor () { } diff --git a/Code/Learning/otbCzihoSOMLearningBehaviorFunctor.h b/Code/Learning/otbCzihoSOMLearningBehaviorFunctor.h index 2e6e1581a043a895df61422cb0823965ed7cc03f..0d0d34756a51151250c831a479d406b61524cb72 100644 --- a/Code/Learning/otbCzihoSOMLearningBehaviorFunctor.h +++ b/Code/Learning/otbCzihoSOMLearningBehaviorFunctor.h @@ -23,84 +23,92 @@ PURPOSE. See the above copyright notices for more information. #include "itkSize.h" -namespace otb { - -namespace Functor { - - /** \class CzihoSOMLearningBehaviorFunctor - * \brief Beta behavior over SOM training phase - * - * This class implements an evolution of the \f$ \beta \f$ weightening - * coefficient over the SOM training. It is issued from A. Cziho's PhD: - * "Compression d'images et analyse de contenu par quantification vectorielle" - * PhD dissertation, University of Rennes I, Rennes, France. May 5th, 1999. - * - * Its behavior is decomposed into two steps depending on the number of iterations: - * \f[ - \beta = - \begin{cases} \beta_0 \left( 1 - \frac{t}{t_0} \right) & \textrm{if} t \lt t_0} - \\ - \beta_{\textrm{end}} \left( 1- \frac{t-t_O}{t_{\textrm{end}}-t_0} \right) & \textrm{ if $ t_0 \leqslant t \lt t_{\textrm{end}}$} - \end{cases} - \f] - * where \f$ t_0 \f$ stands for IterationThreshold. - * - * CzihoSOMLearningBehaviorFunctor uses some parameters of the SOM class such as: - * BetaInit, BetaEnd, NumberOfIterations, but also NeighborhoodSizeInit which may be - * (surprisingly) required for the IterationThreshold. - * - * The functor function uses \code NumberOfIterations \endcode, \code BetaInit \endcode, \code BetaEnd \endcode parameters, that is - * why it is necessary to call a specific method for \code IterationThreshold \endcode intialisation. - * - * \sa SOM - */ - class CzihoSOMLearningBehaviorFunctor +namespace otb +{ + +namespace Functor +{ + +/** \class CzihoSOMLearningBehaviorFunctor +* \brief Beta behavior over SOM training phase +* +* This class implements an evolution of the \f$ \beta \f$ weightening +* coefficient over the SOM training. It is issued from A. Cziho's PhD: +* "Compression d'images et analyse de contenu par quantification vectorielle" +* PhD dissertation, University of Rennes I, Rennes, France. May 5th, 1999. +* +* Its behavior is decomposed into two steps depending on the number of iterations: +* \f[ + \beta = + \begin{cases} \beta_0 \left( 1 - \frac{t}{t_0} \right) & \textrm{if} t \lt t_0} + \\ + \beta_{\textrm{end}} \left( 1- \frac{t-t_O}{t_{\textrm{end}}-t_0} \right) & \textrm{ if $ t_0 \leqslant t \lt t_{\textrm{end}}$} + \end{cases} + \f] + * where \f$ t_0 \f$ stands for IterationThreshold. +* +* CzihoSOMLearningBehaviorFunctor uses some parameters of the SOM class such as: +* BetaInit, BetaEnd, NumberOfIterations, but also NeighborhoodSizeInit which may be +* (surprisingly) required for the IterationThreshold. +* +* The functor function uses \code NumberOfIterations \endcode, \code BetaInit \endcode, \code BetaEnd \endcode parameters, that is +* why it is necessary to call a specific method for \code IterationThreshold \endcode intialisation. +* +* \sa SOM +*/ +class CzihoSOMLearningBehaviorFunctor +{ +public : + /** Empty constructor / descructor */ + CzihoSOMLearningBehaviorFunctor () { - public : - /** Empty constructor / descructor */ - CzihoSOMLearningBehaviorFunctor () { m_IterationThreshold = 0; } - virtual ~CzihoSOMLearningBehaviorFunctor() { } - - /** Accessors */ - unsigned int GetIterationThreshold () { return this->m_IterationThreshold; } - - template < unsigned int VDimension > - void SetIterationThreshold ( const itk::Size<VDimension> & sizeInit, unsigned int iterMax ) - { - double V0 = static_cast<double>( sizeInit[0] ); - for (unsigned int i = 1; i < VDimension; i++ ) - { - if ( V0 < static_cast<double>( sizeInit[i] ) ) - V0 = static_cast<double>( sizeInit[i] ); - } - - m_IterationThreshold = static_cast<unsigned int>( - static_cast<double>( iterMax ) * ( 1.0 - 1.0 / ::vcl_sqrt( V0 ) ) ); - } - - /** Functor */ - virtual double operator() ( unsigned int currentIteration, - unsigned int numberOfIterations, - double betaInit, double betaEnd ) - { - if ( currentIteration < m_IterationThreshold ) - { - return betaInit * ( 1.0 - - static_cast<double>( currentIteration ) - / static_cast<double>( numberOfIterations ) ); - } - else - { - return betaEnd * ( 1.0 - - static_cast<double>( currentIteration - m_IterationThreshold ) - / static_cast<double>( numberOfIterations - m_IterationThreshold ) ); - } - } - - private: - unsigned int m_IterationThreshold; - - }; // end of class CzihoSOMLearningBehaviorFunctor + m_IterationThreshold = 0; + } + virtual ~CzihoSOMLearningBehaviorFunctor() { } + + /** Accessors */ + unsigned int GetIterationThreshold () + { + return this->m_IterationThreshold; + } + + template < unsigned int VDimension > + void SetIterationThreshold ( const itk::Size<VDimension> & sizeInit, unsigned int iterMax ) + { + double V0 = static_cast<double>( sizeInit[0] ); + for (unsigned int i = 1; i < VDimension; i++ ) + { + if ( V0 < static_cast<double>( sizeInit[i] ) ) + V0 = static_cast<double>( sizeInit[i] ); + } + + m_IterationThreshold = static_cast<unsigned int>( + static_cast<double>( iterMax ) * ( 1.0 - 1.0 / ::vcl_sqrt( V0 ) ) ); + } + + /** Functor */ + virtual double operator() ( unsigned int currentIteration, + unsigned int numberOfIterations, + double betaInit, double betaEnd ) + { + if ( currentIteration < m_IterationThreshold ) + { + return betaInit * ( 1.0 + - static_cast<double>( currentIteration ) + / static_cast<double>( numberOfIterations ) ); + } + else + { + return betaEnd * ( 1.0 + - static_cast<double>( currentIteration - m_IterationThreshold ) + / static_cast<double>( numberOfIterations - m_IterationThreshold ) ); + } + } + +private: + unsigned int m_IterationThreshold; + +}; // end of class CzihoSOMLearningBehaviorFunctor } // end namespace Functor diff --git a/Code/Learning/otbCzihoSOMNeighborhoodBehaviorFunctor.h b/Code/Learning/otbCzihoSOMNeighborhoodBehaviorFunctor.h index fe8f6efaf2e3952a97d911b3e1a07b11ccef29fd..201e2d5dd79fc73deacce226b200f399ee0cf966 100644 --- a/Code/Learning/otbCzihoSOMNeighborhoodBehaviorFunctor.h +++ b/Code/Learning/otbCzihoSOMNeighborhoodBehaviorFunctor.h @@ -22,57 +22,59 @@ PURPOSE. See the above copyright notices for more information. #define __otbCzihoSOMNeighborhoodBehaviorFunctor_h -namespace otb { - -namespace Functor { - - /** \class CzihoSOMNeighborhoodBehaviorFunctor - * \brief Neighborhood size behavior over SOM training phase - * - * This class implements an evolution of the neighborhood size - * over the SOM training. It is issued from A. Cziho's PhD: - * "Compression d'images et analyse de contenu par quantification vectorielle" - * PhD dissertation, University of Rennes I, Rennes, France. May 5th, 1999. - * - * The behavior of the radius r (\em ie. \code SizeType \endcode component 0, 1,...) is given by: - * \f$ - r = r_{\textrm{init}} \left( 1 - \frac{t}{t_{\textrm{end}}} \right)^2 - \f$ - * - * CzihoSOMNeighborhoodBehaviorFunctor uses some parameters of the SOM class such as: - * \code NeighborhoodSizeInit \endcode, \code NumberOfIterations \endcode which are parameters of the functor function. - * \code operator() \endcode is templated with the dimension of the neighborhoodSize. - * - * \sa SOM - */ - class CzihoSOMNeighborhoodBehaviorFunctor +namespace otb +{ + +namespace Functor +{ + +/** \class CzihoSOMNeighborhoodBehaviorFunctor +* \brief Neighborhood size behavior over SOM training phase +* +* This class implements an evolution of the neighborhood size +* over the SOM training. It is issued from A. Cziho's PhD: +* "Compression d'images et analyse de contenu par quantification vectorielle" +* PhD dissertation, University of Rennes I, Rennes, France. May 5th, 1999. +* +* The behavior of the radius r (\em ie. \code SizeType \endcode component 0, 1,...) is given by: +* \f$ + r = r_{\textrm{init}} \left( 1 - \frac{t}{t_{\textrm{end}}} \right)^2 + \f$ +* +* CzihoSOMNeighborhoodBehaviorFunctor uses some parameters of the SOM class such as: +* \code NeighborhoodSizeInit \endcode, \code NumberOfIterations \endcode which are parameters of the functor function. +* \code operator() \endcode is templated with the dimension of the neighborhoodSize. +* +* \sa SOM +*/ +class CzihoSOMNeighborhoodBehaviorFunctor +{ +public : + /** Empty constructor / descructor */ + CzihoSOMNeighborhoodBehaviorFunctor () { } + virtual ~CzihoSOMNeighborhoodBehaviorFunctor() { } + + /** Functor */ + template < unsigned int VDimension > + itk::Size<VDimension> operator() ( unsigned int currentIteration, + unsigned int numberOfIterations, + const itk::Size<VDimension> & sizeInit ) { - public : - /** Empty constructor / descructor */ - CzihoSOMNeighborhoodBehaviorFunctor () { } - virtual ~CzihoSOMNeighborhoodBehaviorFunctor() { } - - /** Functor */ - template < unsigned int VDimension > - itk::Size<VDimension> operator() ( unsigned int currentIteration, - unsigned int numberOfIterations, - const itk::Size<VDimension> & sizeInit ) - { - itk::Size<VDimension> theSize; - double weightening = ::vcl_pow( 1.0 - - static_cast<double>( currentIteration ) - / static_cast<double>( numberOfIterations ), - 2.0 ); - for (unsigned int i = 0; i < VDimension; i++ ) - { - theSize[i] = static_cast<typename itk::Size<VDimension>::SizeValueType> ( - static_cast<double>( sizeInit[i] ) * weightening ); - } - - return theSize; - } - - }; // end of class CzihoSOMNeighborhoodBehaviorFunctor + itk::Size<VDimension> theSize; + double weightening = ::vcl_pow( 1.0 + - static_cast<double>( currentIteration ) + / static_cast<double>( numberOfIterations ), + 2.0 ); + for (unsigned int i = 0; i < VDimension; i++ ) + { + theSize[i] = static_cast<typename itk::Size<VDimension>::SizeValueType> ( + static_cast<double>( sizeInit[i] ) * weightening ); + } + + return theSize; + } + +}; // end of class CzihoSOMNeighborhoodBehaviorFunctor } // end namespace Functor diff --git a/Code/Learning/otbGaussianModelComponent.h b/Code/Learning/otbGaussianModelComponent.h index bf288938f6d70653ef5f7976fd075cded95f3d7e..729d053d8d0ac57532f1acc11d576b0f3c439118 100644 --- a/Code/Learning/otbGaussianModelComponent.h +++ b/Code/Learning/otbGaussianModelComponent.h @@ -26,8 +26,10 @@ #include "otbModelComponentBase.h" -namespace otb { -namespace Statistics { +namespace otb +{ +namespace Statistics +{ /** \class GaussianModelComponent * \brief is a component (derived from ModelComponentBase) for @@ -41,7 +43,7 @@ namespace Statistics { template< class TSample > class ITK_EXPORT GaussianModelComponent : - public ModelComponentBase< TSample > + public ModelComponentBase< TSample > { public: /**Standard class typedefs. */ @@ -57,19 +59,19 @@ public: /** Typedefs from the superclass */ typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::MeasurementVectorSizeType - MeasurementVectorSizeType; + MeasurementVectorSizeType; typedef typename Superclass::MembershipFunctionType MembershipFunctionType; typedef typename Superclass::ParametersType ParametersType; /** Type of the membership function. Gaussian density function */ typedef itk::Statistics::GaussianDensityFunction< MeasurementVectorType > - NativeMembershipFunctionType; + NativeMembershipFunctionType; /** Types of the mean and the covariance calculator that will update * this component's distribution parameters */ typedef itk::Statistics::MeanCalculator< TSample > MeanEstimatorType; typedef itk::Statistics::CovarianceCalculator< TSample > - CovarianceEstimatorType; + CovarianceEstimatorType; /** types of the mean and covariance to be used by * NativeMembershipFunctionType */ diff --git a/Code/Learning/otbGaussianModelComponent.txx b/Code/Learning/otbGaussianModelComponent.txx index 815dae28b9ea4b8a80c28108139592134feb9330..2a44da55e2fd23ddb0c666e36fa9f9a8d24a9faf 100644 --- a/Code/Learning/otbGaussianModelComponent.txx +++ b/Code/Learning/otbGaussianModelComponent.txx @@ -26,8 +26,10 @@ #include "otbMacro.h" #include "otbGaussianModelComponent.h" -namespace otb { -namespace Statistics { +namespace otb +{ +namespace Statistics +{ template< class TSample > GaussianModelComponent< TSample > @@ -78,10 +80,10 @@ GaussianModelComponent< TSample > Superclass::SetSample(sample); const MeasurementVectorSizeType measurementVectorLength - = sample->GetMeasurementVectorSize(); + = sample->GetMeasurementVectorSize(); this->m_Parameters.SetSize( measurementVectorLength - * ( 1 + measurementVectorLength ) ); + * ( 1 + measurementVectorLength ) ); m_Mean.SetSize( measurementVectorLength ); @@ -90,7 +92,7 @@ GaussianModelComponent< TSample > //m_MeanEstimator->Update(); m_Covariance.SetSize( measurementVectorLength, - measurementVectorLength ); + measurementVectorLength ); m_CovarianceEstimator = CovarianceEstimatorType::New(); m_CovarianceEstimator->SetInputSample(sample); @@ -100,9 +102,9 @@ GaussianModelComponent< TSample > m_GaussianDensityFunction = NativeMembershipFunctionType::New(); this->m_PdfFunction = (MembershipFunctionType *) m_GaussianDensityFunction; m_GaussianDensityFunction->SetMeasurementVectorSize( - measurementVectorLength ); + measurementVectorLength ); this->SetPdfMembershipFunction( (MembershipFunctionType *) - m_GaussianDensityFunction.GetPointer() ); + m_GaussianDensityFunction.GetPointer() ); } @@ -117,7 +119,7 @@ GaussianModelComponent< TSample > unsigned int i, j; MeasurementVectorSizeType measurementVectorSize - = this->GetSample()->GetMeasurementVectorSize(); + = this->GetSample()->GetMeasurementVectorSize(); m_Mean.SetSize ( measurementVectorSize ); for ( i = 0; i < measurementVectorSize; i++) @@ -148,7 +150,7 @@ GaussianModelComponent< TSample > return; MeasurementVectorSizeType measurementVectorSize - = this->GetSample()->GetMeasurementVectorSize(); + = this->GetSample()->GetMeasurementVectorSize(); unsigned int i, j; int paramIndex = 0; @@ -174,7 +176,7 @@ GaussianModelComponent< TSample > for ( j = 0; j < measurementVectorSize; j++ ) { this->m_Parameters[paramIndex] - = m_Covariance(i,j) + = m_Covariance(i,j) = covariance->GetVnlMatrix().get(i, j); ++paramIndex; } diff --git a/Code/Learning/otbKMeansImageClassificationFilter.h b/Code/Learning/otbKMeansImageClassificationFilter.h index b0123d4c1e42196205e96a01f8f7d4ed2b85c11a..dc9f6b0f3e9833965fec6e1cd281e3f79470ac9b 100644 --- a/Code/Learning/otbKMeansImageClassificationFilter.h +++ b/Code/Learning/otbKMeansImageClassificationFilter.h @@ -26,104 +26,104 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class KMeansImageClassificationFilter - * \brief This filter performs the classification of a VectorImage using a KMeans estimation result. - * - * This filter is streamed and threaded, allowing to classify huge images. Because the - * internal sample type has to be an itk::FixedArray, one must specify at compilation time - * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently - * high to integrate all its features. This filter internally use one SVMClassifier per thread. - * - * \sa SVMClassifier - * \ingroup Streamed - * \ingroup Threaded +/** \class KMeansImageClassificationFilter + * \brief This filter performs the classification of a VectorImage using a KMeans estimation result. + * + * This filter is streamed and threaded, allowing to classify huge images. Because the + * internal sample type has to be an itk::FixedArray, one must specify at compilation time + * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently + * high to integrate all its features. This filter internally use one SVMClassifier per thread. + * + * \sa SVMClassifier + * \ingroup Streamed + * \ingroup Threaded + */ +template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension = 10, class TMaskImage = TOutputImage> +class ITK_EXPORT KMeansImageClassificationFilter + : public itk::InPlaceImageFilter<TInputImage,TOutputImage> +{ +public: + /** Standard typedefs */ + typedef KMeansImageClassificationFilter Self; + typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(KMeansImageClassificationFilter,InPlaceImageFilter); + + /** The max dimension of the sample to classify. + * This filter internally uses itk::FixedArray as input for the classifier, + * so the max sample size has to be fixed at compilation time. + */ + itkStaticConstMacro(MaxSampleDimension,unsigned int,VMaxSampleDimension); + + typedef TInputImage InputImageType; + typedef typename InputImageType::ConstPointer InputImageConstPointerType; + typedef typename InputImageType::InternalPixelType ValueType; + + typedef TMaskImage MaskImageType; + typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; + typedef typename MaskImageType::Pointer MaskImagePointerType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType LabelType; + + + typedef itk::FixedArray<ValueType,MaxSampleDimension> SampleType; + typedef itk::Array<double> KMeansParametersType; + typedef std::map<LabelType,SampleType> CentroidsMapType; + typedef itk::Statistics::EuclideanDistance<SampleType> DistanceType; + + /** Set/Get the centroids */ + itkSetMacro(Centroids,KMeansParametersType); + itkGetConstReferenceMacro(Centroids,KMeansParametersType); + + /** Set/Get the default label */ + itkSetMacro(DefaultLabel,LabelType); + itkGetMacro(DefaultLabel,LabelType); + + /** + * If set, only pixels within the mask will be classified. + * \param mask The input mask. + */ + void SetInputMask(const MaskImageType * mask); + + /** + * Get the input mask. + * \return The mask. */ - template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension = 10, class TMaskImage = TOutputImage> - class ITK_EXPORT KMeansImageClassificationFilter - : public itk::InPlaceImageFilter<TInputImage,TOutputImage> - { - public: - /** Standard typedefs */ - typedef KMeansImageClassificationFilter Self; - typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(KMeansImageClassificationFilter,InPlaceImageFilter); - - /** The max dimension of the sample to classify. - * This filter internally uses itk::FixedArray as input for the classifier, - * so the max sample size has to be fixed at compilation time. - */ - itkStaticConstMacro(MaxSampleDimension,unsigned int,VMaxSampleDimension); - - typedef TInputImage InputImageType; - typedef typename InputImageType::ConstPointer InputImageConstPointerType; - typedef typename InputImageType::InternalPixelType ValueType; - - typedef TMaskImage MaskImageType; - typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; - typedef typename MaskImageType::Pointer MaskImagePointerType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::PixelType LabelType; - - - typedef itk::FixedArray<ValueType,MaxSampleDimension> SampleType; - typedef itk::Array<double> KMeansParametersType; - typedef std::map<LabelType,SampleType> CentroidsMapType; - typedef itk::Statistics::EuclideanDistance<SampleType> DistanceType; - - /** Set/Get the centroids */ - itkSetMacro(Centroids,KMeansParametersType); - itkGetConstReferenceMacro(Centroids,KMeansParametersType); - - /** Set/Get the default label */ - itkSetMacro(DefaultLabel,LabelType); - itkGetMacro(DefaultLabel,LabelType); - - /** - * If set, only pixels within the mask will be classified. - * \param mask The input mask. - */ - void SetInputMask(const MaskImageType * mask); - - /** - * Get the input mask. - * \return The mask. - */ - const MaskImageType * GetInputMask(void); - - protected: - /** Constructor */ - KMeansImageClassificationFilter(); - /** Destructor */ - virtual ~KMeansImageClassificationFilter() {}; - - /** Threaded generate data */ - virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); - /** Before threaded generate data */ - virtual void BeforeThreadedGenerateData(); - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - KMeansImageClassificationFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** Centroids used for classification */ - KMeansParametersType m_Centroids; - /** Default label for invalid pixels (when using a mask) */ - LabelType m_DefaultLabel; - /** Centroids - labels map */ - CentroidsMapType m_CentroidsMap; - }; + const MaskImageType * GetInputMask(void); + +protected: + /** Constructor */ + KMeansImageClassificationFilter(); + /** Destructor */ + virtual ~KMeansImageClassificationFilter() {}; + + /** Threaded generate data */ + virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); + /** Before threaded generate data */ + virtual void BeforeThreadedGenerateData(); + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + KMeansImageClassificationFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Centroids used for classification */ + KMeansParametersType m_Centroids; + /** Default label for invalid pixels (when using a mask) */ + LabelType m_DefaultLabel; + /** Centroids - labels map */ + CentroidsMapType m_CentroidsMap; +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbKMeansImageClassificationFilter.txx" diff --git a/Code/Learning/otbKMeansImageClassificationFilter.txx b/Code/Learning/otbKMeansImageClassificationFilter.txx index 354acdbc0218126497c3d9807224bbd3f1047f4f..c57f3bd46f30265bbf7bedf9ab03f55b8878ee24 100644 --- a/Code/Learning/otbKMeansImageClassificationFilter.txx +++ b/Code/Learning/otbKMeansImageClassificationFilter.txx @@ -50,10 +50,10 @@ const typename KMeansImageClassificationFilter<TInputImage,TOutputImage,VMaxSamp KMeansImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMaskImage> ::GetInputMask() { - if(this->GetNumberOfInputs()<2) - { - return 0; - } + if (this->GetNumberOfInputs()<2) + { + return 0; + } return static_cast<const MaskImageType *>(this->itk::ProcessObject::GetInput(1)); } @@ -65,17 +65,17 @@ KMeansImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMa unsigned int sample_size = MaxSampleDimension; unsigned int nb_classes = m_Centroids.Size()/sample_size; - for(LabelType label = 1;label<=static_cast<LabelType>(nb_classes);++label) - { - SampleType new_centroid; - new_centroid.Fill(0); - m_CentroidsMap[label]=new_centroid; - - for(unsigned int i=0;i<MaxSampleDimension;++i) + for (LabelType label = 1;label<=static_cast<LabelType>(nb_classes);++label) { - m_CentroidsMap[label][i] = static_cast<ValueType>(m_Centroids[MaxSampleDimension*(static_cast<unsigned int>(label)-1)+i]); - } + SampleType new_centroid; + new_centroid.Fill(0); + m_CentroidsMap[label]=new_centroid; + + for (unsigned int i=0;i<MaxSampleDimension;++i) + { + m_CentroidsMap[label][i] = static_cast<ValueType>(m_Centroids[MaxSampleDimension*(static_cast<unsigned int>(label)-1)+i]); } + } } template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension, class TMaskImage> @@ -95,63 +95,63 @@ KMeansImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMa OutputIteratorType outIt(outputPtr,outputRegionForThread); MaskIteratorType maskIt; - if(inputMaskPtr) - { - maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); - maskIt.GoToBegin(); - } + if (inputMaskPtr) + { + maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); + maskIt.GoToBegin(); + } unsigned int maxDimension = SampleType::Dimension; unsigned int sampleSize = std::min(inputPtr->GetNumberOfComponentsPerPixel(), - maxDimension); + maxDimension); bool validPoint = true; - while(!outIt.IsAtEnd()) - { - outIt.Set(m_DefaultLabel); - ++outIt; - } + while (!outIt.IsAtEnd()) + { + outIt.Set(m_DefaultLabel); + ++outIt; + } outIt.GoToBegin(); - validPoint = true; - - typename DistanceType::Pointer distance = DistanceType::New(); - - while(!outIt.IsAtEnd()&&(!inIt.IsAtEnd())) - { - if(inputMaskPtr) - { - validPoint = maskIt.Get()>0; - ++maskIt; - } - if(validPoint) - { - LabelType label =1; - LabelType current_label =1; - SampleType pixel; - pixel.Fill(0); - for(unsigned int i=0;i<sampleSize;++i) - { - pixel[i]=inIt.Get()[i]; - } - - double current_distance = distance->Evaluate(pixel,m_CentroidsMap[label]); - - for(label=2;label<=static_cast<LabelType>(m_CentroidsMap.size());++label) - { - double tmp_dist = distance->Evaluate(pixel,m_CentroidsMap[label]); - if(tmp_dist<current_distance) - { - current_label = label; - current_distance = tmp_dist; - } - } - outIt.Set(current_label); - } - ++outIt; - ++inIt; - } + validPoint = true; + + typename DistanceType::Pointer distance = DistanceType::New(); + + while (!outIt.IsAtEnd()&&(!inIt.IsAtEnd())) + { + if (inputMaskPtr) + { + validPoint = maskIt.Get()>0; + ++maskIt; + } + if (validPoint) + { + LabelType label =1; + LabelType current_label =1; + SampleType pixel; + pixel.Fill(0); + for (unsigned int i=0;i<sampleSize;++i) + { + pixel[i]=inIt.Get()[i]; + } + + double current_distance = distance->Evaluate(pixel,m_CentroidsMap[label]); + + for (label=2;label<=static_cast<LabelType>(m_CentroidsMap.size());++label) + { + double tmp_dist = distance->Evaluate(pixel,m_CentroidsMap[label]); + if (tmp_dist<current_distance) + { + current_label = label; + current_distance = tmp_dist; + } + } + outIt.Set(current_label); + } + ++outIt; + ++inIt; + } } /** * PrintSelf Method diff --git a/Code/Learning/otbMixturePolyRBFKernelFunctor.cxx b/Code/Learning/otbMixturePolyRBFKernelFunctor.cxx index 6f2f554d7474cac8d0a4698c09376599669d0e99..9965435496b450217843ba7610e1486d31b1315c 100644 --- a/Code/Learning/otbMixturePolyRBFKernelFunctor.cxx +++ b/Code/Learning/otbMixturePolyRBFKernelFunctor.cxx @@ -25,7 +25,7 @@ namespace otb MixturePolyRBFKernelFunctor ::MixturePolyRBFKernelFunctor () - : GenericKernelFunctorBase () + : GenericKernelFunctorBase () { m_Mixture = 0.5; m_GammaPoly = 1.0; @@ -43,12 +43,12 @@ MixturePolyRBFKernelFunctor double MixturePolyRBFKernelFunctor ::operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const + const svm_parameter & param ) const { double kernel_poly = 0.0; if ( m_Mixture > 0.0 ) kernel_poly = powi( m_GammaPoly * this->dot( x, y ) + m_CoefPoly, - m_DegreePoly ); + m_DegreePoly ); double kernel_rbf = 0.0; if ( m_Mixture < 1.0 ) @@ -113,9 +113,9 @@ MixturePolyRBFKernelFunctor { double tmp = base, ret = 1.0; - for(int t=times; t>0; t/=2) + for (int t=times; t>0; t/=2) { - if(t%2==1) ret*=tmp; + if (t%2==1) ret*=tmp; tmp = tmp * tmp; } return ret; diff --git a/Code/Learning/otbMixturePolyRBFKernelFunctor.h b/Code/Learning/otbMixturePolyRBFKernelFunctor.h index ddef2f393a8903c9dfca63eb7f0fedc6f6b964d6..50df61c5ed1d3a0d329a55eeb3d10ce2d6e1499f 100644 --- a/Code/Learning/otbMixturePolyRBFKernelFunctor.h +++ b/Code/Learning/otbMixturePolyRBFKernelFunctor.h @@ -25,25 +25,25 @@ namespace otb { - /** \class MixturePolyRBFKernelFunctor - * \brief Mixture of kernels. - * - * Performs the mixture of kind: \f$ \mu k_1(x,y) + (1-\mu) k_2(x,y) \f$ - * with \f$ k_1(x,y)=\left( \gamma_1 x\cdot y + c_0 \right) ^d \f$ a - * polynomial kernel and - * \f$ k_2(x,y) = \exp\left( - \gamma_2 \| x-y\-^2 \right) \f$ an RBF one. - * - * Variable to be instanciated (through \code SetValue \endcode) are: - * Mixture (def=0.5), GammaPoly (def=1.0), CoefPoly (def=1.0), - * DegreePoly (def=2), GammaRBF (def=1.0) - */ +/** \class MixturePolyRBFKernelFunctor + * \brief Mixture of kernels. + * + * Performs the mixture of kind: \f$ \mu k_1(x,y) + (1-\mu) k_2(x,y) \f$ + * with \f$ k_1(x,y)=\left( \gamma_1 x\cdot y + c_0 \right) ^d \f$ a + * polynomial kernel and + * \f$ k_2(x,y) = \exp\left( - \gamma_2 \| x-y\-^2 \right) \f$ an RBF one. + * + * Variable to be instanciated (through \code SetValue \endcode) are: + * Mixture (def=0.5), GammaPoly (def=1.0), CoefPoly (def=1.0), + * DegreePoly (def=2), GammaRBF (def=1.0) + */ class MixturePolyRBFKernelFunctor - : public GenericKernelFunctorBase + : public GenericKernelFunctorBase { - public: +public: double operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const; + const svm_parameter & param ) const; MixturePolyRBFKernelFunctor (); virtual ~MixturePolyRBFKernelFunctor () { } diff --git a/Code/Learning/otbModelComponentBase.h b/Code/Learning/otbModelComponentBase.h index 08a8763c6d601c4af4cf46868c10c23fe2c6dae9..ec57e6bd8b0570a4be05a0c3e5d8aa437fb69c30 100644 --- a/Code/Learning/otbModelComponentBase.h +++ b/Code/Learning/otbModelComponentBase.h @@ -27,8 +27,10 @@ #include "itkArray.h" #include "itkMembershipFunctionBase.h" -namespace otb { -namespace Statistics { +namespace otb +{ +namespace Statistics +{ /** \class ModelComponentBase * \brief base class for distribution representation that supports @@ -57,7 +59,7 @@ namespace Statistics { template< class TSample > class ITK_EXPORT ModelComponentBase : - public itk::Object + public itk::Object { public: /**Standard class typedefs. */ @@ -75,7 +77,7 @@ public: /** typedef for the MembershipFunctionBase */ typedef itk::Statistics::MembershipFunctionBase< MeasurementVectorType > - MembershipFunctionType; + MembershipFunctionType; typedef itk::Array< double > ParametersType; @@ -101,7 +103,10 @@ public: /** Gets/Sets the parameter(s) required for the component */ void SetParameters(const ParametersType ¶meters); - ParametersType GetParameters() { return m_Parameters; } + ParametersType GetParameters() + { + return m_Parameters; + } /** returns the pdf of the "measurements" vector */ double Evaluate ( MeasurementVectorType & measurements ); diff --git a/Code/Learning/otbNonGaussianRBFKernelFunctor.cxx b/Code/Learning/otbNonGaussianRBFKernelFunctor.cxx index 70a2cdf6b56b9ce6ac848c0393580f32c9b99748..f58aef68e09a52ceb7d93a970df53c892e830ef4 100644 --- a/Code/Learning/otbNonGaussianRBFKernelFunctor.cxx +++ b/Code/Learning/otbNonGaussianRBFKernelFunctor.cxx @@ -20,11 +20,12 @@ #include <cmath> #include "otbNonGaussianRBFKernelFunctor.h" -namespace otb { +namespace otb +{ NonGaussianRBFKernelFunctor ::NonGaussianRBFKernelFunctor () - : GenericKernelFunctorBase () + : GenericKernelFunctorBase () { m_Alpha = 1.0; m_Beta = 2.0; @@ -38,7 +39,7 @@ NonGaussianRBFKernelFunctor double NonGaussianRBFKernelFunctor ::operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const + const svm_parameter & param ) const { double pr_x, pr_y, diff, sum = 0.0; diff --git a/Code/Learning/otbNonGaussianRBFKernelFunctor.h b/Code/Learning/otbNonGaussianRBFKernelFunctor.h index e6559799c38ccffb50ef8112d3155ce2e93036b8..40e71fe7d9aa707d6d2f8010b72c3d70d63ca570 100644 --- a/Code/Learning/otbNonGaussianRBFKernelFunctor.h +++ b/Code/Learning/otbNonGaussianRBFKernelFunctor.h @@ -25,25 +25,25 @@ //FIXME: shouldn't it be in the Functor namespace? namespace otb { - /** \class NonGaussianRBFKernelFunctor - * \brief Performs an RBF kernel evaluation that better suit sample distribution with high Kurtosis. - * - * It is of kind - * \f$ \exp\left( - \gamma \sum_i | x_i^\alpha - y_i^\alpha |^\beta \right) \f$ - * where \f$ 0 \leqslant \alpha \leqslant 1 \f$ and - * \f$ 0 \leqslant \beta \leqslant 2 \f$. - * - * Variables to be instanciated (through \code SetValue \endcode) are: - * Alpha (def=1), Beta (def=2) and Gamma (def 1.0). - * - */ +/** \class NonGaussianRBFKernelFunctor + * \brief Performs an RBF kernel evaluation that better suit sample distribution with high Kurtosis. + * + * It is of kind + * \f$ \exp\left( - \gamma \sum_i | x_i^\alpha - y_i^\alpha |^\beta \right) \f$ + * where \f$ 0 \leqslant \alpha \leqslant 1 \f$ and + * \f$ 0 \leqslant \beta \leqslant 2 \f$. + * + * Variables to be instanciated (through \code SetValue \endcode) are: + * Alpha (def=1), Beta (def=2) and Gamma (def 1.0). + * + */ class NonGaussianRBFKernelFunctor - : public GenericKernelFunctorBase + : public GenericKernelFunctorBase { public: double operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const; + const svm_parameter & param ) const; NonGaussianRBFKernelFunctor (); virtual ~NonGaussianRBFKernelFunctor () { } diff --git a/Code/Learning/otbPeriodicSOM.h b/Code/Learning/otbPeriodicSOM.h index 50b71c00feee1402ed9ed824c63fa682493d0745..4f3a26a98c658d20ad6530041f456a452555d54c 100644 --- a/Code/Learning/otbPeriodicSOM.h +++ b/Code/Learning/otbPeriodicSOM.h @@ -23,7 +23,8 @@ #include "otbSOM.h" -namespace otb { +namespace otb +{ /** * \class PeriodicSOM @@ -52,17 +53,17 @@ namespace otb { * \sa CzihoSOMNeighborhoodBehaviorFunctor */ template <class TListSample, class TMap, - class TSOMLearningBehaviorFunctor = Functor::CzihoSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor = Functor::CzihoSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor = Functor::CzihoSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor = Functor::CzihoSOMNeighborhoodBehaviorFunctor > class ITK_EXPORT PeriodicSOM - : public SOM< TListSample, TMap, TSOMLearningBehaviorFunctor, TSOMNeighborhoodBehaviorFunctor > + : public SOM< TListSample, TMap, TSOMLearningBehaviorFunctor, TSOMNeighborhoodBehaviorFunctor > { public: /** Standard typedefs */ typedef PeriodicSOM Self; typedef SOM< TListSample, TMap, - TSOMLearningBehaviorFunctor, - TSOMNeighborhoodBehaviorFunctor > Superclass; + TSOMLearningBehaviorFunctor, + TSOMNeighborhoodBehaviorFunctor > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -88,14 +89,20 @@ protected: /** Destructor */ virtual ~PeriodicSOM() {} /** Output information redefinition */ - virtual void GenerateOutputInformation () { - Superclass::GenerateOutputInformation (); } + virtual void GenerateOutputInformation () + { + Superclass::GenerateOutputInformation (); + } /** Output allocation redefinition */ - virtual void AllocateOutputs() { - Superclass::AllocateOutputs(); } + virtual void AllocateOutputs() + { + Superclass::AllocateOutputs(); + } /** Main computation method */ - virtual void GenerateData(void) { - Superclass::GenerateData(); } + virtual void GenerateData(void) + { + Superclass::GenerateData(); + } /** * Update the output map with a new sample. * \param sample The new sample to learn, @@ -106,11 +113,15 @@ protected: /** * Step one iteration. */ - virtual void Step(unsigned int currentIteration) { - Superclass::Step( currentIteration ); } + virtual void Step(unsigned int currentIteration) + { + Superclass::Step( currentIteration ); + } /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const { - Superclass::PrintSelf(os,indent); } + void PrintSelf(std::ostream& os, itk::Indent indent) const + { + Superclass::PrintSelf(os,indent); + } private: PeriodicSOM(const Self&); // purposely not implemented diff --git a/Code/Learning/otbPeriodicSOM.txx b/Code/Learning/otbPeriodicSOM.txx index 9774d8569db46200ddb40de7aa44fb101a21d8ae..e159fb0edf85d13789f1bf1637f2ff41b14d8c2c 100644 --- a/Code/Learning/otbPeriodicSOM.txx +++ b/Code/Learning/otbPeriodicSOM.txx @@ -27,7 +27,8 @@ #include "otbPeriodicSOM.h" -namespace otb { +namespace otb +{ /** * Update the output map with a new sample. @@ -36,8 +37,8 @@ namespace otb { * \param radius The radius of the neighbourhood. */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void PeriodicSOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::UpdateMap(const NeuronType& sample, double beta, SizeType& radius) @@ -74,7 +75,7 @@ PeriodicSOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehavio double theDistance = itk::NumericTraits< double >::Zero; for ( j = 0; j < MapType::ImageDimension; j++ ) theDistance += pow( static_cast<double>( offset[j] ), 2.0 ) - / pow( static_cast<double>( radius[j] ), 2.0 ); + / pow( static_cast<double>( radius[j] ), 2.0 ); if ( theDistance <= 1.0 ) { @@ -82,8 +83,8 @@ PeriodicSOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehavio { int pos = offset[j] + position[j]; positionToUpdate[j] = ( pos >= 0 ) ? - pos % mapSize[j] : - ( mapSize[j] - ( (-pos) % mapSize[j] ) ) % mapSize[j]; + pos % mapSize[j] : + ( mapSize[j] - ( (-pos) % mapSize[j] ) ) % mapSize[j]; } NeuronType tempNeuron = it.GetPixel(i); @@ -92,10 +93,10 @@ PeriodicSOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehavio NeuronType newNeuron ( tempNeuron ); double tempBeta = beta / ( 1.0 + theDistance ); - for( j = 0; j < newNeuron.Size(); j++ ) + for ( j = 0; j < newNeuron.Size(); j++ ) { newNeuron[j] += static_cast<typename NeuronType::ValueType>( - ( sample[j] - tempNeuron[j] ) * tempBeta ); + ( sample[j] - tempNeuron[j] ) * tempBeta ); } map->SetPixel(positionToUpdate,newNeuron); } diff --git a/Code/Learning/otbROIdataConversion.h b/Code/Learning/otbROIdataConversion.h index e890e3bacb2b7bf67c96c28fdfdb6f050dfd3c05..60e6268a5c0403a5d8bba697d499b0b769361e65 100644 --- a/Code/Learning/otbROIdataConversion.h +++ b/Code/Learning/otbROIdataConversion.h @@ -25,7 +25,8 @@ #include <otbImage.h> #include <itkImageToImageFilter.h> -namespace otb { +namespace otb +{ /** \class ROIdataConversion * \brief image data to vector conversion. @@ -35,7 +36,7 @@ namespace otb { */ template < class TInputImage, class TInputROIImage > class ROIdataConversion - : public itk::ImageToImageFilter< TInputImage, otb::Image<typename TInputImage::PixelType, 1> > + : public itk::ImageToImageFilter< TInputImage, otb::Image<typename TInputImage::PixelType, 1> > { public: typedef ROIdataConversion Self; @@ -57,18 +58,22 @@ public: typedef typename OutputImageType::SizeType::SizeValueType SizeValueType; /** Gets/Sets the input image */ - const InputImageType * GetInputImage () { + const InputImageType * GetInputImage () + { return this->Superclass::GetInput(); } - void SetInputImage ( const InputImageType * img ) { + void SetInputImage ( const InputImageType * img ) + { this->Superclass::SetInput(img); } /** Gets/Sets the ROI image */ - InputROIImageType * GetROIImage () { + InputROIImageType * GetROIImage () + { return static_cast< InputROIImageType *> (this->itk::ProcessObject::GetInput(1)); } - void SetROIImage ( const InputROIImageType * img ) { + void SetROIImage ( const InputROIImageType * img ) + { this->itk::ProcessObject::SetNthInput( 1, const_cast<InputROIImageType *>(img) ); } @@ -77,7 +82,8 @@ protected: virtual ~ROIdataConversion() { } virtual void GenerateOutputInformation(); virtual void GenerateInputRequestedRegion(); - void PrintSelf(std::ostream& os, itk::Indent indent) const { + void PrintSelf(std::ostream& os, itk::Indent indent) const + { Superclass::PrintSelf( os, indent ); } diff --git a/Code/Learning/otbROIdataConversion.txx b/Code/Learning/otbROIdataConversion.txx index 46b5968e98aee9716cbf05171dc87614a148952d..0a40a8a5173e60193473e51d7401a1b6bdfb4250 100644 --- a/Code/Learning/otbROIdataConversion.txx +++ b/Code/Learning/otbROIdataConversion.txx @@ -26,7 +26,8 @@ #include "otbROIdataConversion.h" -namespace otb { +namespace otb +{ template < class TInputImage, class TInputROIImage > ROIdataConversion< TInputImage, TInputROIImage > @@ -44,7 +45,7 @@ ROIdataConversion< TInputImage, TInputROIImage > { typename OutputImageType::Pointer outputPtr = this->GetOutput(); typename OutputImageType::SizeType outputSize - = outputPtr->GetRequestedRegion().GetSize(); + = outputPtr->GetRequestedRegion().GetSize(); outputSize[0] = GetNumberOfSample(); outputPtr->SetRegions( outputSize ); } @@ -73,11 +74,11 @@ ROIdataConversion< TInputImage, TInputROIImage > typename InputROIImageType::ConstPointer inputROIPtr = this->GetROIImage(); itk::ImageRegionConstIterator< InputImageType > inputIter - ( inputImagePtr, inputImagePtr->GetRequestedRegion() ); + ( inputImagePtr, inputImagePtr->GetRequestedRegion() ); itk::ImageRegionConstIterator< InputROIImageType > trainingIter - ( inputROIPtr, inputROIPtr->GetRequestedRegion() ); + ( inputROIPtr, inputROIPtr->GetRequestedRegion() ); itk::ImageRegionIterator< OutputImageType > outputIter - ( outputPtr, outputPtr->GetRequestedRegion() ); + ( outputPtr, outputPtr->GetRequestedRegion() ); inputIter.GoToBegin(); trainingIter.GoToBegin(); @@ -104,7 +105,7 @@ ROIdataConversion< TInputImage, TInputROIImage > { InputROIImagePointerType inputROIPtr = GetROIImage(); itk::ImageRegionConstIterator< InputROIImageType > trainingIter - ( inputROIPtr, inputROIPtr->GetRequestedRegion() ); + ( inputROIPtr, inputROIPtr->GetRequestedRegion() ); trainingIter.GoToBegin(); diff --git a/Code/Learning/otbSEMClassifier.h b/Code/Learning/otbSEMClassifier.h index b99a9867745136a3646fdcc868aac3085917e903..8841806e4cc01c3241353edccf3941b6fc911c73 100644 --- a/Code/Learning/otbSEMClassifier.h +++ b/Code/Learning/otbSEMClassifier.h @@ -11,7 +11,8 @@ -namespace otb { +namespace otb +{ /** \class SEMClassifier * \brief This class implements the Stochastic Expectation @@ -42,7 +43,7 @@ namespace otb { */ template< class TInputImage, class TOutputImage > class ITK_EXPORT SEMClassifier - : public itk::Statistics::SampleClassifier< + : public itk::Statistics::SampleClassifier< typename itk::Statistics::ListSample< typename TInputImage::PixelType > > { public: @@ -50,8 +51,8 @@ public: typedef SEMClassifier Self; //typedef itk::Object Superclass; typedef itk::Statistics::SampleClassifier< - typename itk::Statistics::ListSample< typename TInputImage::PixelType > > - Superclass; + typename itk::Statistics::ListSample< typename TInputImage::PixelType > > + Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -161,7 +162,7 @@ public: /* Return the classification result (as an image) */ TOutputImage * GetOutputImage(); - protected: +protected: SEMClassifier(); virtual ~SEMClassifier() {} void PrintSelf(std::ostream& os, itk::Indent indent) const; diff --git a/Code/Learning/otbSEMClassifier.txx b/Code/Learning/otbSEMClassifier.txx index 7846d245a9d966bff86f9c2c74edcd04406616b4..2cf395b307eea3c650ba17b7de840e6bdd94c3a7 100644 --- a/Code/Learning/otbSEMClassifier.txx +++ b/Code/Learning/otbSEMClassifier.txx @@ -15,7 +15,8 @@ #include "otbSEMClassifier.h" -namespace otb { +namespace otb +{ template< class TInputImage, class TOutputImage > SEMClassifier< TInputImage, TOutputImage > @@ -100,12 +101,14 @@ SEMClassifier< TInputImage, TOutputImage > typename OutputType::ConstIterator iterLabels = labels->Begin(); typename OutputType::InstanceIdentifier id = 0; - do { + do + { *iterClassLabel = iterLabels->GetClassLabel( id ); ++iterLabels; ++iterClassLabel; id++; - } while ( iterLabels != labels->End() ); + } + while ( iterLabels != labels->End() ); m_ExternalLabels = 1; } else if ( labels.size() == m_NbSamples ) @@ -116,12 +119,14 @@ SEMClassifier< TInputImage, TOutputImage > typename OutputType::iterator iterLabels = labels->Begin(); typename OutputType::InstanceIdentifier id = 0; - do { + do + { *iterClassLabel = iterLabels->GetClassLabel( id ); ++iterLabels; ++iterClassLabel; id++; - } while ( iterLabels != labels->End() ); + } + while ( iterLabels != labels->End() ); m_ExternalLabels = 1; } else @@ -154,11 +159,13 @@ SEMClassifier< TInputImage, TOutputImage > ClassLabelVectorType::iterator iterClassLabel = m_ClassLabels.begin(); - do { + do + { *iterClassLabel = imgLabelIter.Get(); ++imgLabelIter; ++iterClassLabel; - } while ( imgLabelIter != imgLabelIterEnd ); + } + while ( imgLabelIter != imgLabelIterEnd ); m_ExternalLabels = 1; } else if ( theSize == m_NbSamples ) @@ -174,11 +181,13 @@ SEMClassifier< TInputImage, TOutputImage > ClassLabelVectorType::iterator iterClassLabel = m_ClassLabels.begin(); - do { + do + { *iterClassLabel = imgLabelIter.Get(); ++imgLabelIter; ++iterClassLabel; - } while ( imgLabelIter != imgLabelIterEnd ); + } + while ( imgLabelIter != imgLabelIterEnd ); m_ExternalLabels = 1; } @@ -217,24 +226,26 @@ SEMClassifier< TInputImage, TOutputImage > m_SampleList->SetMeasurementVectorSize( m_Sample->GetVectorLength() ); itk::ImageRegionIterator< TInputImage > imgIter ( (TInputImage *) m_Sample, - m_Sample->GetBufferedRegion() ); + m_Sample->GetBufferedRegion() ); imgIter.GoToBegin(); itk::ImageRegionIterator< TInputImage > imgIterEnd ( (TInputImage *) m_Sample, - m_Sample->GetBufferedRegion() ); + m_Sample->GetBufferedRegion() ); imgIterEnd.GoToEnd(); - do { + do + { m_SampleList->PushBack( imgIter.Get() ); ++m_NbSamples; ++imgIter; - } while ( imgIter != imgIterEnd ); + } + while ( imgIter != imgIterEnd ); if ( m_ExternalLabels ) { typename TInputImage::SizeType size = m_Sample->GetBufferedRegion().GetSize(); if ( ( size[0] * size[1] ) != m_ClassLabels.size() ) throw itk::ExceptionObject( __FILE__, __LINE__, - "Vector size missmatch", ITK_LOCATION ); + "Vector size missmatch", ITK_LOCATION ); } } @@ -318,14 +329,14 @@ SEMClassifier< TInputImage, TOutputImage > ::InitParameters() { if ( !m_ExternalLabels ) - { + { m_ClassLabels.resize( m_NbSamples ); if ( static_cast<int>(m_InitialProportions.size()) != m_NbClasses ) { int label; for ( typename ClassLabelVectorType::iterator labelIter = m_ClassLabels.begin(); - labelIter != m_ClassLabels.end(); - ++labelIter ) + labelIter != m_ClassLabels.end(); + ++labelIter ) { //label = (int) floor( 0.5 + nbClassesDbl * ran / double(RAND_MAX+1) ); label = rand() % m_NbClasses; @@ -341,15 +352,17 @@ SEMClassifier< TInputImage, TOutputImage > // Be sure, the sum of intial proportion remains to 1 double sumProportion = 0.0; typename ProportionVectorType::iterator iterProportion = m_InitialProportions.begin(); - do { + do + { sumProportion += *iterProportion; - } while ( ++iterProportion != m_InitialProportions.end() ); + } + while ( ++iterProportion != m_InitialProportions.end() ); if ( sumProportion != 1.0 ) { for ( iterProportion = m_InitialProportions.begin(); - iterProportion != m_InitialProportions.end(); - ++iterProportion ) + iterProportion != m_InitialProportions.end(); + ++iterProportion ) *iterProportion /= sumProportion; } @@ -357,8 +370,8 @@ SEMClassifier< TInputImage, TOutputImage > double sample; double cumulativeProportion; for ( typename ClassLabelVectorType::iterator labelIter = m_ClassLabels.begin(); - labelIter != m_ClassLabels.end(); - ++labelIter ) + labelIter != m_ClassLabels.end(); + ++labelIter ) { cumulativeProportion = 0.0; sample = double( rand() ) / ( double( RAND_MAX) + 1.0 ); @@ -367,7 +380,7 @@ SEMClassifier< TInputImage, TOutputImage > for ( int componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) { if ( cumulativeProportion <= sample - && sample < cumulativeProportion + m_InitialProportions[componentIndex] ) + && sample < cumulativeProportion + m_InitialProportions[componentIndex] ) { *labelIter = componentIndex; break; @@ -387,7 +400,7 @@ SEMClassifier< TInputImage, TOutputImage > if ( !m_ComponentDeclared ) { otbMsgDebugMacro( << "default mixture initialisation with " << m_NbClasses - << " Gaussian components" ); + << " Gaussian components" ); typedef otb::Statistics::GaussianModelComponent< ClassSampleType > GaussianType; for ( int componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) @@ -412,8 +425,8 @@ SEMClassifier< TInputImage, TOutputImage > int posSample = 0; for ( typename ClassLabelVectorType::iterator iter = m_ClassLabels.begin(); - iter != m_ClassLabels.end(); - ++iter ) + iter != m_ClassLabels.end(); + ++iter ) { x = double( rand() ) / ( double(RAND_MAX) + 1.0 ); z = 0.0; @@ -437,12 +450,13 @@ SEMClassifier< TInputImage, TOutputImage > switch ( GetCurrentIteration() ) { - case 0 : case 1 : - otbMsgDebugMacro( << "Doing iteration " << GetCurrentIteration() ); - break; - default : - otbMsgDebugMacro( << m_NbChange << " sample change at iteration " - << GetCurrentIteration() ); + case 0 : + case 1 : + otbMsgDebugMacro( << "Doing iteration " << GetCurrentIteration() ); + break; + default : + otbMsgDebugMacro( << m_NbChange << " sample change at iteration " + << GetCurrentIteration() ); } } @@ -473,11 +487,13 @@ SEMClassifier< TInputImage, TOutputImage > typename SampleType::InstanceIdentifier id = 0; - do { + do + { coeffByClass[ *iterLabel ]->AddInstance( id ); m_Proportions[ *iterLabel ] += 1.0; id++; - } while ( ++iterSample != lastSample && ++iterLabel != lastLabel ); + } + while ( ++iterSample != lastSample && ++iterLabel != lastLabel ); for ( componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) { @@ -524,7 +540,8 @@ SEMClassifier< TInputImage, TOutputImage > typename SampleType::InstanceIdentifier id = 0; - do { + do + { id = iterSample.GetInstanceIdentifier(); for ( componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) @@ -547,14 +564,14 @@ SEMClassifier< TInputImage, TOutputImage > for ( componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) localWeight[ componentIndex ] = localCount[ componentIndex ] - / neighborhoodWeight; + / neighborhoodWeight; sumPdf = 0.0; for ( componentIndex = 0; componentIndex < m_NbClasses; componentIndex++ ) { measurementVector = iterSample.GetMeasurementVector(); aPdf = localWeight[ componentIndex ] - * m_ComponentVector[componentIndex]->Pdf( measurementVector ); + * m_ComponentVector[componentIndex]->Pdf( measurementVector ); sumPdf += aPdf; pdf[componentIndex] = aPdf; } @@ -565,10 +582,11 @@ SEMClassifier< TInputImage, TOutputImage > m_Proba[componentIndex][iterSample.GetInstanceIdentifier()] = 0.0; else m_Proba[componentIndex][iterSample.GetInstanceIdentifier()] - = pdf[componentIndex] / sumPdf; + = pdf[componentIndex] / sumPdf; } - } while ( ++iterSample != lastSample ); + } + while ( ++iterSample != lastSample ); } template < class TInputImage, class TOutputImage > @@ -603,21 +621,23 @@ SEMClassifier< TInputImage, TOutputImage > imgOutputIterEnd.GoToEnd(); - do { + do + { cluster = 0; for ( componentIndex = 1; componentIndex < m_NbClasses; componentIndex++ ) { if ( m_Proba[componentIndex][sampleIter.GetInstanceIdentifier()] - > m_Proba[cluster][sampleIter.GetInstanceIdentifier()] ) + > m_Proba[cluster][sampleIter.GetInstanceIdentifier()] ) cluster = componentIndex; } m_Output->AddInstance( cluster, sampleIter.GetInstanceIdentifier() ); imgOutputIter.Set( cluster ); - } while ( ++sampleIter != sampleIterEnd - && ++outputIter != outputIterEnd - && ++imgOutputIter != imgOutputIterEnd ); + } + while ( ++sampleIter != sampleIterEnd + && ++outputIter != outputIterEnd + && ++imgOutputIter != imgOutputIterEnd ); } template< class TInputImage, class TOutputImage > @@ -634,7 +654,8 @@ SEMClassifier< TInputImage, TOutputImage > int oldNbChange = 0; double step; - do { + do + { oldNbChange = m_NbChange; PerformStochasticProcess(); @@ -645,14 +666,15 @@ SEMClassifier< TInputImage, TOutputImage > if ( step >= 0.0 ) { if ( ( step / static_cast<double>( m_NbSamples ) ) - < GetTerminationThreshold() ) + < GetTerminationThreshold() ) { m_TerminationCode = CONVERGED; if ( oldNbChange != 0 ) break; } } - } while (++m_CurrentIteration < m_MaximumIteration); + } + while (++m_CurrentIteration < m_MaximumIteration); GetMaximumAposterioriLabels(); } diff --git a/Code/Learning/otbSOM.h b/Code/Learning/otbSOM.h index f8dbd996cd7b64abad8b8aab7c6de16a6b0b93fa..ffe677848389f3a39c8384bd19bdd8424830ba68 100644 --- a/Code/Learning/otbSOM.h +++ b/Code/Learning/otbSOM.h @@ -52,12 +52,12 @@ namespace otb * \sa CzihoSOMNeighborhoodBehaviorFunctor */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor = Functor::CzihoSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor = Functor::CzihoSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor = Functor::CzihoSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor = Functor::CzihoSOMNeighborhoodBehaviorFunctor > class ITK_EXPORT SOM -: public itk::ImageSource<TMap> + : public itk::ImageSource<TMap> { - public: +public: /** Standard typedefs */ typedef SOM Self; typedef itk::ImageSource<TMap> Superclass; @@ -107,13 +107,17 @@ class ITK_EXPORT SOM itkGetObjectMacro(ListSample,ListSampleType); itkSetObjectMacro(ListSample,ListSampleType); - void SetBetaFunctor ( const SOMLearningBehaviorFunctorType & functor ) { - m_BetaFunctor = functor; } + void SetBetaFunctor ( const SOMLearningBehaviorFunctorType & functor ) + { + m_BetaFunctor = functor; + } - void SetNeighborhoodSizeFunctor ( const SOMNeighborhoodBehaviorFunctorType & functor ) { - m_NeighborhoodSizeFunctor = functor; } + void SetNeighborhoodSizeFunctor ( const SOMNeighborhoodBehaviorFunctorType & functor ) + { + m_NeighborhoodSizeFunctor = functor; + } - protected: +protected: /** Constructor */ SOM(); /** Destructor */ @@ -138,7 +142,7 @@ class ITK_EXPORT SOM /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: SOM(const Self&); // purposely not implemented void operator=(const Self&); // purposely not implemented /** Size of the neurons map */ diff --git a/Code/Learning/otbSOM.txx b/Code/Learning/otbSOM.txx index 208f54ee254335ba44361e97019eb8db9baac92c..9f6baf619761752ce2b3c8d77a92193f28e5c1d0 100644 --- a/Code/Learning/otbSOM.txx +++ b/Code/Learning/otbSOM.txx @@ -35,8 +35,8 @@ namespace otb * Constructor */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::SOM() { @@ -57,8 +57,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * Destructor */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::~SOM() { @@ -70,8 +70,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * \param radius The radius of the nieghbourhood. */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::UpdateMap( const NeuronType& sample, double beta, SizeType& radius ) @@ -93,7 +93,7 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor RegionType localRegion; IndexType localIndex = position-radius; SizeType localSize; - for(unsigned int i=0;i<MapType::ImageDimension;++i) + for (unsigned int i=0;i<MapType::ImageDimension;++i) { localSize[i]= 2*radius[i]+1; } @@ -104,20 +104,20 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor // Walk through the map, and evolve each neuron depending on its // distance to the winner. - for(it.GoToBegin();!it.IsAtEnd();++it) + for (it.GoToBegin();!it.IsAtEnd();++it) { NeuronType tempNeuron = it.Get(); NeuronType newNeuron ( tempNeuron.Size() ); double tempBeta = beta - / ( 1 + - distance->Evaluate( ContinuousIndexType(position), - ContinuousIndexType(it.GetIndex()) ) ); + / ( 1 + + distance->Evaluate( ContinuousIndexType(position), + ContinuousIndexType(it.GetIndex()) ) ); - for(unsigned int i = 0; i < newNeuron.Size();++i) + for (unsigned int i = 0; i < newNeuron.Size();++i) { newNeuron[i] = tempNeuron[i] - +static_cast<typename NeuronType::ValueType>( - ( sample[i] - tempNeuron[i] ) * tempBeta ); + +static_cast<typename NeuronType::ValueType>( + ( sample[i] - tempNeuron[i] ) * tempBeta ); } it.Set(newNeuron); @@ -127,25 +127,25 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * Step one iteration. */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::Step(unsigned int currentIteration) { // Compute the new learning coefficient double newBeta = m_BetaFunctor( - currentIteration, m_NumberOfIterations, m_BetaInit, m_BetaEnd ); + currentIteration, m_NumberOfIterations, m_BetaInit, m_BetaEnd ); // Compute the new neighborhood size SizeType newSize = m_NeighborhoodSizeFunctor( - currentIteration, m_NumberOfIterations, m_NeighborhoodSizeInit ); + currentIteration, m_NumberOfIterations, m_NeighborhoodSizeInit ); // update the neurons map with each example of the training set. otbMsgDebugMacro(<<"Beta: "<<newBeta<<", radius: "<<newSize); for ( typename ListSampleType::Iterator it = m_ListSample->Begin(); - it != m_ListSample->End(); - ++it ) + it != m_ListSample->End(); + ++it ) { UpdateMap( it.GetMeasurementVector(), newBeta, newSize ); } @@ -154,8 +154,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * Output information redefinition */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::GenerateOutputInformation () @@ -177,8 +177,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * Output redefinition */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::AllocateOutputs() @@ -195,8 +195,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor * Main computation method */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::GenerateData(void) @@ -218,11 +218,11 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor for ( it.GoToBegin(); !it.IsAtEnd(); ++it ) { - for(unsigned int i=0;i< neuronInit.Size();++i) + for (unsigned int i=0;i< neuronInit.Size();++i) { neuronInit[i]=static_cast<typename NeuronType::ValueType>( - generator->GetUniformVariate(static_cast<double>(m_MinWeight), - static_cast<double>(m_MaxWeight)) ); + generator->GetUniformVariate(static_cast<double>(m_MinWeight), + static_cast<double>(m_MaxWeight)) ); } it.Set(neuronInit); } @@ -235,7 +235,7 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor } // Step through the iterations - for(unsigned int i = 0;i<m_NumberOfIterations;++i) + for (unsigned int i = 0;i<m_NumberOfIterations;++i) { //otbMsgDebugMacro(<<"Step "<<i+1<<" / "<<m_NumberOfIterations); std::cerr << "Step "<< i+1 <<" / "<<m_NumberOfIterations << " \r"; @@ -248,8 +248,8 @@ SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor *PrintSelf method */ template < class TListSample, class TMap, - class TSOMLearningBehaviorFunctor, - class TSOMNeighborhoodBehaviorFunctor > +class TSOMLearningBehaviorFunctor, +class TSOMNeighborhoodBehaviorFunctor > void SOM<TListSample,TMap,TSOMLearningBehaviorFunctor,TSOMNeighborhoodBehaviorFunctor> ::PrintSelf(std::ostream& os, itk::Indent indent) const diff --git a/Code/Learning/otbSOMActivationBuilder.h b/Code/Learning/otbSOMActivationBuilder.h index b596b9b9e9d3e2fc19b3d77426cb4868508d835b..f0d3f58ee32ab253d5e62f69342634242ab030ee 100644 --- a/Code/Learning/otbSOMActivationBuilder.h +++ b/Code/Learning/otbSOMActivationBuilder.h @@ -34,9 +34,9 @@ namespace otb */ template <class TListSample, class TInputMap, class TOutputImage> class ITK_EXPORT SOMActivationBuilder - : public itk::ImageToImageFilter<TInputMap,TOutputImage> + : public itk::ImageToImageFilter<TInputMap,TOutputImage> { - public: +public: /** Standard typedefs */ typedef SOMActivationBuilder Self; typedef itk::ImageToImageFilter<TInputMap,TOutputImage> Superclass; @@ -65,7 +65,7 @@ class ITK_EXPORT SOMActivationBuilder itkSetObjectMacro(ListSample,ListSampleType); itkGetObjectMacro(ListSample,ListSampleType); - protected: +protected: /** Constructor */ SOMActivationBuilder(); /** Destructor */ @@ -75,7 +75,7 @@ class ITK_EXPORT SOMActivationBuilder /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: SOMActivationBuilder(const Self&); // purposely not implemented void operator=(const Self&);// purposely not implemented /** ListSample object */ diff --git a/Code/Learning/otbSOMActivationBuilder.txx b/Code/Learning/otbSOMActivationBuilder.txx index 3e0cb8da55c1162b0e22aee624d87ec918898b6b..cd6fd0802c4feb1cdfa1f6c1197cc02d954b1a26 100644 --- a/Code/Learning/otbSOMActivationBuilder.txx +++ b/Code/Learning/otbSOMActivationBuilder.txx @@ -64,15 +64,15 @@ SOMActivationBuilder<TInputImage,TInputMap,TOutputImage> OutputIteratorType outIt(output,output->GetLargestPossibleRegion()); // For each vector in the set - for(typename ListSampleType::Iterator it = m_ListSample->Begin(); - it!=m_ListSample->End();++it) - { - // Retrieve the index of the winner - index = map->GetWinner(it.GetMeasurementVector()); - // increment the activation map - outIt.SetIndex(index); - outIt.Set(outIt.Get()+1); - } + for (typename ListSampleType::Iterator it = m_ListSample->Begin(); + it!=m_ListSample->End();++it) + { + // Retrieve the index of the winner + index = map->GetWinner(it.GetMeasurementVector()); + // increment the activation map + outIt.SetIndex(index); + outIt.Set(outIt.Get()+1); + } } /** *PrintSelf method diff --git a/Code/Learning/otbSOMClassifier.h b/Code/Learning/otbSOMClassifier.h index d72acea125dc291b216552a58485bb5e41b41966..4f8f832f4b6338bd312f2feb1dcf6e130b3cb180 100644 --- a/Code/Learning/otbSOMClassifier.h +++ b/Code/Learning/otbSOMClassifier.h @@ -49,7 +49,7 @@ public: typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - /** Standard macros */ + /** Standard macros */ itkTypeMacro(SOMClassifier, itk::ProcessObject); itkNewMacro(Self); @@ -89,7 +89,7 @@ protected: /** Starts the classification process */ void GenerateData(); - private: +private: /// The input sample SamplePointerType m_Sample; /// The output membership sample. diff --git a/Code/Learning/otbSOMClassifier.txx b/Code/Learning/otbSOMClassifier.txx index 688dc81c446e8691eeee995a1222904e9c4e9ae2..4c662e876ea975f3ac6ff961029a06da4bf356ab 100644 --- a/Code/Learning/otbSOMClassifier.txx +++ b/Code/Learning/otbSOMClassifier.txx @@ -79,12 +79,12 @@ SOMClassifier< TSample, TSOMMap, TLabel > typename OutputType::Pointer outputPtr = this->GetOutput(); outputPtr->SetSample(this->GetSample()); outputPtr->Resize( this->GetSample()->Size()); - typename SOMMapType::SizeType size = this->GetMap()->GetLargestPossibleRegion().GetSize(); - unsigned int numberOfClasses = 1; - for(unsigned int i=0; i<SOMMapType::ImageDimension;++i) - { - numberOfClasses*=size[i]; - } + typename SOMMapType::SizeType size = this->GetMap()->GetLargestPossibleRegion().GetSize(); + unsigned int numberOfClasses = 1; + for (unsigned int i=0; i<SOMMapType::ImageDimension;++i) + { + numberOfClasses*=size[i]; + } outputPtr->SetNumberOfClasses(numberOfClasses); typename TSample::Iterator iter = this->GetSample()->Begin(); @@ -99,9 +99,9 @@ SOMClassifier< TSample, TSOMMap, TLabel > SOMMapPointerType somMap = this->GetMap(); - otbMsgDebugMacro( << "Starting iterations " ); + otbMsgDebugMacro( << "Starting iterations " ); while (iter != end && iterO != endO) - { + { measurements = iter.GetMeasurementVector(); index = somMap->GetWinner(measurements); @@ -109,7 +109,7 @@ SOMClassifier< TSample, TSOMMap, TLabel > outputPtr->AddInstance(classLabel, iterO.GetInstanceIdentifier()); ++iter; ++iterO; - } + } } } // end of namespace otb diff --git a/Code/Learning/otbSOMImageClassificationFilter.h b/Code/Learning/otbSOMImageClassificationFilter.h index b2c4cb09e1e7b65a62e04c33420f618dd86712fb..14b446352998bb8d3a573af5702d3142cff9c73d 100644 --- a/Code/Learning/otbSOMImageClassificationFilter.h +++ b/Code/Learning/otbSOMImageClassificationFilter.h @@ -25,101 +25,101 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SOMImageClassificationFilter - * \brief This filter performs the classification of a VectorImage using a given SOM map. - * - * This filter is streamed and threaded, allowing to classify huge images. Because the - * internal sample type has to be an itk::FixedArray, one must specify at compilation time - * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently - * high to integrate all its features. This filter internally use one SVMClassifier per thread. - * - * \sa SVMClassifier - * \ingroup Streamed - * \ingroup Threaded +/** \class SOMImageClassificationFilter + * \brief This filter performs the classification of a VectorImage using a given SOM map. + * + * This filter is streamed and threaded, allowing to classify huge images. Because the + * internal sample type has to be an itk::FixedArray, one must specify at compilation time + * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently + * high to integrate all its features. This filter internally use one SVMClassifier per thread. + * + * \sa SVMClassifier + * \ingroup Streamed + * \ingroup Threaded + */ +template <class TInputImage, class TOutputImage,class TSOMMap, class TMaskImage = TOutputImage> +class ITK_EXPORT SOMImageClassificationFilter + : public itk::InPlaceImageFilter<TInputImage,TOutputImage> +{ +public: + /** Standard typedefs */ + typedef SOMImageClassificationFilter Self; + typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(SOMImageClassificationFilter,InPlaceImageFilter); + + typedef TInputImage InputImageType; + typedef typename InputImageType::ConstPointer InputImageConstPointerType; + typedef typename InputImageType::InternalPixelType ValueType; + + typedef TMaskImage MaskImageType; + typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; + typedef typename MaskImageType::Pointer MaskImagePointerType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType LabelType; + + typedef TSOMMap SOMMapType; + typedef typename SOMMapType::Pointer SOMMapPointerType; + typedef typename SOMMapType::PixelType SampleType; + + typedef itk::Statistics::ListSample<SampleType> ListSampleType; + typedef typename ListSampleType::Pointer ListSamplePointerType; + typedef otb::SOMClassifier<ListSampleType,SOMMapType,LabelType> ClassifierType; + typedef typename ClassifierType::Pointer ClassifierPointerType; + + /** Set/Get the svm model */ + itkSetObjectMacro(Map,SOMMapType); + itkGetObjectMacro(Map,SOMMapType); + + /** Set/Get the default label */ + itkSetMacro(DefaultLabel,LabelType); + itkGetMacro(DefaultLabel,LabelType); + + /** + * If set, only pixels within the mask will be classified. + * \param mask The input mask. + */ + void SetInputMask(const MaskImageType * mask); + + /** + * Get the input mask. + * \return The mask. */ - template <class TInputImage, class TOutputImage,class TSOMMap, class TMaskImage = TOutputImage> - class ITK_EXPORT SOMImageClassificationFilter - : public itk::InPlaceImageFilter<TInputImage,TOutputImage> - { - public: - /** Standard typedefs */ - typedef SOMImageClassificationFilter Self; - typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(SOMImageClassificationFilter,InPlaceImageFilter); - - typedef TInputImage InputImageType; - typedef typename InputImageType::ConstPointer InputImageConstPointerType; - typedef typename InputImageType::InternalPixelType ValueType; - - typedef TMaskImage MaskImageType; - typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; - typedef typename MaskImageType::Pointer MaskImagePointerType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::PixelType LabelType; - - typedef TSOMMap SOMMapType; - typedef typename SOMMapType::Pointer SOMMapPointerType; - typedef typename SOMMapType::PixelType SampleType; - - typedef itk::Statistics::ListSample<SampleType> ListSampleType; - typedef typename ListSampleType::Pointer ListSamplePointerType; - typedef otb::SOMClassifier<ListSampleType,SOMMapType,LabelType> ClassifierType; - typedef typename ClassifierType::Pointer ClassifierPointerType; - - /** Set/Get the svm model */ - itkSetObjectMacro(Map,SOMMapType); - itkGetObjectMacro(Map,SOMMapType); - - /** Set/Get the default label */ - itkSetMacro(DefaultLabel,LabelType); - itkGetMacro(DefaultLabel,LabelType); - - /** - * If set, only pixels within the mask will be classified. - * \param mask The input mask. - */ - void SetInputMask(const MaskImageType * mask); - - /** - * Get the input mask. - * \return The mask. - */ - const MaskImageType * GetInputMask(void); - - protected: - /** Constructor */ - SOMImageClassificationFilter(); - /** Destructor */ - virtual ~SOMImageClassificationFilter() {}; - - /** Threaded generate data */ - virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); - /** Before threaded generate data */ - virtual void BeforeThreadedGenerateData(); - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - SOMImageClassificationFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** The SOM model used for classification */ - SOMMapPointerType m_Map; - /** Default label for invalid pixels (when using a mask) */ - LabelType m_DefaultLabel; - - - }; + const MaskImageType * GetInputMask(void); + +protected: + /** Constructor */ + SOMImageClassificationFilter(); + /** Destructor */ + virtual ~SOMImageClassificationFilter() {}; + + /** Threaded generate data */ + virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); + /** Before threaded generate data */ + virtual void BeforeThreadedGenerateData(); + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + SOMImageClassificationFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** The SOM model used for classification */ + SOMMapPointerType m_Map; + /** Default label for invalid pixels (when using a mask) */ + LabelType m_DefaultLabel; + + +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbSOMImageClassificationFilter.txx" diff --git a/Code/Learning/otbSOMImageClassificationFilter.txx b/Code/Learning/otbSOMImageClassificationFilter.txx index 521078b19495140878bc98c4c6a762b52ff5a11c..e2d134085e55f0be054ff9d54973dc5c436236e3 100644 --- a/Code/Learning/otbSOMImageClassificationFilter.txx +++ b/Code/Learning/otbSOMImageClassificationFilter.txx @@ -50,10 +50,10 @@ const typename SOMImageClassificationFilter<TInputImage,TOutputImage,TSOMMap,TMa SOMImageClassificationFilter<TInputImage,TOutputImage,TSOMMap,TMaskImage> ::GetInputMask() { - if(this->GetNumberOfInputs()<2) - { - return 0; - } + if (this->GetNumberOfInputs()<2) + { + return 0; + } return static_cast<const MaskImageType *>(this->itk::ProcessObject::GetInput(1)); } @@ -62,10 +62,10 @@ void SOMImageClassificationFilter<TInputImage,TOutputImage,TSOMMap,TMaskImage> ::BeforeThreadedGenerateData() { - if(!m_Map) - { - itkGenericExceptionMacro(<<"No model for classification"); - } + if (!m_Map) + { + itkGenericExceptionMacro(<<"No model for classification"); + } } template <class TInputImage, class TOutputImage, class TSOMMap, class TMaskImage> @@ -86,35 +86,35 @@ SOMImageClassificationFilter<TInputImage,TOutputImage,TSOMMap,TMaskImage> InputIteratorType inIt(inputPtr,outputRegionForThread); MaskIteratorType maskIt; - if(inputMaskPtr) - { - maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); - maskIt.GoToBegin(); - } + if (inputMaskPtr) + { + maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); + maskIt.GoToBegin(); + } unsigned int maxDimension = m_Map->GetNumberOfComponentsPerPixel(); unsigned int sampleSize = std::min(inputPtr->GetNumberOfComponentsPerPixel(), - maxDimension); + maxDimension); bool validPoint = true; - for(inIt.GoToBegin();!inIt.IsAtEnd();++inIt) - { - if(inputMaskPtr) - { - validPoint = maskIt.Get()>0; - ++maskIt; - } - if(validPoint) + for (inIt.GoToBegin();!inIt.IsAtEnd();++inIt) { - SampleType sample; - sample.SetSize(sampleSize); - sample.Fill(itk::NumericTraits<ValueType>::ZeroValue()); - for(unsigned int i=0;i<sampleSize;i++) + if (inputMaskPtr) + { + validPoint = maskIt.Get()>0; + ++maskIt; + } + if (validPoint) + { + SampleType sample; + sample.SetSize(sampleSize); + sample.Fill(itk::NumericTraits<ValueType>::ZeroValue()); + for (unsigned int i=0;i<sampleSize;i++) { sample[i]=inIt.Get()[i]; } - listSample->PushBack(sample); - } + listSample->PushBack(sample); } + } ClassifierPointerType classifier =ClassifierType::New(); classifier->SetMap(m_Map); classifier->SetSample(listSample); @@ -128,34 +128,34 @@ SOMImageClassificationFilter<TInputImage,TOutputImage,TSOMMap,TMaskImage> outIt.GoToBegin(); - while(!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) - { - outIt.Set(m_DefaultLabel); - ++outIt; - } + while (!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) + { + outIt.Set(m_DefaultLabel); + ++outIt; + } outIt.GoToBegin(); - if(inputMaskPtr) + if (inputMaskPtr) + { + maskIt.GoToBegin(); + } + validPoint = true; + + while (!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) + { + if (inputMaskPtr) { - maskIt.GoToBegin(); + validPoint = maskIt.Get()>0; + ++maskIt; } - validPoint = true; - - while(!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) - { - if(inputMaskPtr) - { - validPoint = maskIt.Get()>0; - ++maskIt; - } - if(validPoint) - { - outIt.Set(sampleIter.GetClassLabel()); - ++sampleIter; - } - ++outIt; - } + if (validPoint) + { + outIt.Set(sampleIter.GetClassLabel()); + ++sampleIter; + } + ++outIt; + } } /** * PrintSelf Method diff --git a/Code/Learning/otbSOMLearningBehaviorFunctor.h b/Code/Learning/otbSOMLearningBehaviorFunctor.h index 77cd14ba70fae7c70142caff16b300546fa2fa5c..0516dc7b2699906d4615b9275e1942f16d76615f 100644 --- a/Code/Learning/otbSOMLearningBehaviorFunctor.h +++ b/Code/Learning/otbSOMLearningBehaviorFunctor.h @@ -22,41 +22,43 @@ PURPOSE. See the above copyright notices for more information. #define __otbSOMLearningBehaviorFunctor_h -namespace otb { - -namespace Functor { - - /** \class SOMLearningBehaviorFunctor - * \brief Classical Beta behavior over SOM training phase - * - * This class implements an standart evolution of the \f$ \beta \f$ weightening - * coefficient over the SOM training. - * - * \f[ - \beta = \beta_0 + \left( \beta_{\textrm{end}} - \beta_0 \right) - \frac{t}{t_{\textrm{end}}} - \f] - * - * \sa SOM - */ - class SOMLearningBehaviorFunctor +namespace otb +{ + +namespace Functor +{ + +/** \class SOMLearningBehaviorFunctor +* \brief Classical Beta behavior over SOM training phase +* +* This class implements an standart evolution of the \f$ \beta \f$ weightening +* coefficient over the SOM training. +* +* \f[ + \beta = \beta_0 + \left( \beta_{\textrm{end}} - \beta_0 \right) + \frac{t}{t_{\textrm{end}}} + \f] +* +* \sa SOM +*/ +class SOMLearningBehaviorFunctor +{ +public : + /** Empty constructor / descructor */ + CzihoSOMLearningBehaviorFunctor () { } + virtual ~CzihoSOMLearningBehaviorFunctor() { } + + /** Functor */ + virtual double operator() ( unsigned int currentIteration, + unsigned int numberOfIterations, + double betaInit, double betaEnd ) { - public : - /** Empty constructor / descructor */ - CzihoSOMLearningBehaviorFunctor () { } - virtual ~CzihoSOMLearningBehaviorFunctor() { } - - /** Functor */ - virtual double operator() ( unsigned int currentIteration, - unsigned int numberOfIterations, - double betaInit, double betaEnd ) - { - return betaInit + ( betaEnd - betaInit ) - * static_cast<double>( currentIteration ) - / static_cast<double>( numberOfIterations ); - } - - }; // end of class SOMLearningBehaviorFunctor + return betaInit + ( betaEnd - betaInit ) + * static_cast<double>( currentIteration ) + / static_cast<double>( numberOfIterations ); + } + +}; // end of class SOMLearningBehaviorFunctor } // end namespace Functor diff --git a/Code/Learning/otbSOMMap.h b/Code/Learning/otbSOMMap.h index 64a23c6cb9fcc911f9de14863747502d96316d30..3ee3746cfb0e118042aca70f03ed849c5980577c 100644 --- a/Code/Learning/otbSOMMap.h +++ b/Code/Learning/otbSOMMap.h @@ -46,12 +46,12 @@ namespace otb * \sa SOMActivationBuilder */ template <class TNeuron=itk::VariableLengthVector<double>, - class TDistance=itk::Statistics::EuclideanDistance<TNeuron>, - unsigned int VMapDimension=2> +class TDistance=itk::Statistics::EuclideanDistance<TNeuron>, +unsigned int VMapDimension=2> class ITK_EXPORT SOMMap -: public otb::VectorImage<typename TNeuron::ComponentType,VMapDimension> + : public otb::VectorImage<typename TNeuron::ComponentType,VMapDimension> { - public: +public: /** Standard typedefs */ typedef SOMMap Self; typedef otb::VectorImage<typename TNeuron::ComponentType,VMapDimension> Superclass; @@ -85,7 +85,7 @@ class ITK_EXPORT SOMMap */ IndexType GetWinner(const NeuronType& sample); - protected: +protected: /** Constructor */ SOMMap(); /** Destructor */ @@ -93,7 +93,7 @@ class ITK_EXPORT SOMMap /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: SOMMap(const Self&); // purposely not implemented void operator=(const Self&); // purposely not implemented }; diff --git a/Code/Learning/otbSOMMap.txx b/Code/Learning/otbSOMMap.txx index 11a7df602380380fbf4dbb8aadcac1fba3ae8b19..0c25fd86601f805e66129d38cf5c98a2290d024b 100644 --- a/Code/Learning/otbSOMMap.txx +++ b/Code/Learning/otbSOMMap.txx @@ -66,15 +66,15 @@ SOMMap<TNeuron,TDistance,VMapDimension> double minDistance = activation->Evaluate(sample,it.Get()); // Iterate through the map to get the minimum distance position - for(;!it.IsAtEnd();++it) - { - double tempDistance = activation->Evaluate(sample,it.Get()); - if(tempDistance<=minDistance) + for (;!it.IsAtEnd();++it) { - minDistance = tempDistance; - minPos = it.GetIndex(); - } + double tempDistance = activation->Evaluate(sample,it.Get()); + if (tempDistance<=minDistance) + { + minDistance = tempDistance; + minPos = it.GetIndex(); } + } // Return the index of the winner return minPos; } diff --git a/Code/Learning/otbSVMClassifier.h b/Code/Learning/otbSVMClassifier.h index 405814887d2e6ef0566a60d702b4c451d9a52dd2..4e3675761e9ab14e68f0613eaa7a95666a12467a 100644 --- a/Code/Learning/otbSVMClassifier.h +++ b/Code/Learning/otbSVMClassifier.h @@ -57,7 +57,7 @@ public: typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - /** Standard macros */ + /** Standard macros */ itkTypeMacro(SVMClassifier, itk::Statistics::SampleClassifier); itkNewMacro(Self); @@ -73,13 +73,13 @@ public: /** typedefs from Superclass */ typedef typename Superclass::MembershipFunctionPointerVector - MembershipFunctionPointerVector; + MembershipFunctionPointerVector; /** typedef for label type */ typedef TLabel ClassLabelType; - /** Returns the classification result */ + /** Returns the classification result */ OutputType* GetOutput(); void SetOutput(OutputType* output); diff --git a/Code/Learning/otbSVMClassifier.txx b/Code/Learning/otbSVMClassifier.txx index 33a7da847717c63fa2c50b545e8a3690641e0ddf..08257025ee974f85e0dd1648632f77c6b18782af 100644 --- a/Code/Learning/otbSVMClassifier.txx +++ b/Code/Learning/otbSVMClassifier.txx @@ -24,187 +24,187 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template< class TSample, class TLabel > - SVMClassifier< TSample, TLabel > - ::SVMClassifier() - { - m_Output = OutputType::New(); - m_Model = SVMModelType::New(); - } - - template< class TSample, class TLabel > - void - SVMClassifier< TSample, TLabel > - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template< class TSample, class TLabel > +SVMClassifier< TSample, TLabel > +::SVMClassifier() +{ + m_Output = OutputType::New(); + m_Model = SVMModelType::New(); +} + +template< class TSample, class TLabel > +void +SVMClassifier< TSample, TLabel > +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} - template< class TSample, class TLabel > - void - SVMClassifier< TSample, TLabel > - ::Update() - { - this->GenerateData(); - } +template< class TSample, class TLabel > +void +SVMClassifier< TSample, TLabel > +::Update() +{ + this->GenerateData(); +} - template< class TSample, class TLabel > - void - SVMClassifier< TSample, TLabel > - ::GenerateData() - { +template< class TSample, class TLabel > +void +SVMClassifier< TSample, TLabel > +::GenerateData() +{ - m_Output->SetSample(this->GetSample()); - otbMsgDevMacro( << "m_Output " << m_Output ); + m_Output->SetSample(this->GetSample()); + otbMsgDevMacro( << "m_Output " << m_Output ); - m_Output->Resize( this->GetSample()->Size() ); + m_Output->Resize( this->GetSample()->Size() ); - otbMsgDevMacro( << "Resize to " << this->GetSample()->Size() ); - otbMsgDevMacro( << "Resize to " << m_Output->GetSample()->Size() ); + otbMsgDevMacro( << "Resize to " << this->GetSample()->Size() ); + otbMsgDevMacro( << "Resize to " << m_Output->GetSample()->Size() ); - unsigned int numberOfClasses = this->GetNumberOfClasses(); - otbMsgDevMacro( << "NbClass " << numberOfClasses ); + unsigned int numberOfClasses = this->GetNumberOfClasses(); + otbMsgDevMacro( << "NbClass " << numberOfClasses ); - m_Output->SetNumberOfClasses(numberOfClasses); + m_Output->SetNumberOfClasses(numberOfClasses); - otbMsgDevMacro( << "Do Classif " ); - this->DoClassification(); - otbMsgDevMacro( << "End of classif" ); + otbMsgDevMacro( << "Do Classif " ); + this->DoClassification(); + otbMsgDevMacro( << "End of classif" ); - } +} - template< class TSample, class TLabel > - typename SVMClassifier< TSample, TLabel >::OutputType* - SVMClassifier< TSample, TLabel > - ::GetOutput() - { - return m_Output; - } +template< class TSample, class TLabel > +typename SVMClassifier< TSample, TLabel >::OutputType* +SVMClassifier< TSample, TLabel > +::GetOutput() +{ + return m_Output; +} - template< class TSample, class TLabel > - void - SVMClassifier< TSample, TLabel > - ::SetOutput( OutputType * output ) - { - m_Output = output; - } +template< class TSample, class TLabel > +void +SVMClassifier< TSample, TLabel > +::SetOutput( OutputType * output ) +{ + m_Output = output; +} - template< class TSample, class TLabel > - void - SVMClassifier< TSample, TLabel > - ::DoClassification() - { +template< class TSample, class TLabel > +void +SVMClassifier< TSample, TLabel > +::DoClassification() +{ - typename TSample::ConstIterator iter = this->GetSample()->Begin(); - typename TSample::ConstIterator end = this->GetSample()->End(); + typename TSample::ConstIterator iter = this->GetSample()->Begin(); + typename TSample::ConstIterator end = this->GetSample()->End(); - typename OutputType::ConstIterator iterO = m_Output->Begin(); - typename OutputType::ConstIterator endO = m_Output->End(); - typename TSample::MeasurementVectorType measurements; + typename OutputType::ConstIterator iterO = m_Output->Begin(); + typename OutputType::ConstIterator endO = m_Output->End(); + typename TSample::MeasurementVectorType measurements; - int numberOfComponentsPerSample = iter.GetMeasurementVector().Size(); + int numberOfComponentsPerSample = iter.GetMeasurementVector().Size(); - struct svm_node *x; - bool predict_probability = 1; + struct svm_node *x; + bool predict_probability = 1; - const struct svm_model* model = m_Model->GetModel(); + const struct svm_model* model = m_Model->GetModel(); - x = new svm_node[numberOfComponentsPerSample+1]; + x = new svm_node[numberOfComponentsPerSample+1]; - otbMsgDevMacro( << "XSpace Allocated" ); - if(svm_check_probability_model(model)==0) - { - if(m_Model->GetSVMType() == ONE_CLASS) + otbMsgDevMacro( << "XSpace Allocated" ); + if (svm_check_probability_model(model)==0) + { + if (m_Model->GetSVMType() == ONE_CLASS) { predict_probability = 0; } - else + else { throw itk::ExceptionObject(__FILE__, __LINE__, - "Model does not support probabiliy estimates",ITK_LOCATION); + "Model does not support probabiliy estimates",ITK_LOCATION); } - } + } - int svm_type=svm_get_svm_type(model); - otbMsgDevMacro( << "SVM Type = " << svm_type ); + int svm_type=svm_get_svm_type(model); + otbMsgDevMacro( << "SVM Type = " << svm_type ); - int nr_class=svm_get_nr_class(model); - otbMsgDevMacro( << "SVM nr_class = " << nr_class ); + int nr_class=svm_get_nr_class(model); + otbMsgDevMacro( << "SVM nr_class = " << nr_class ); - int *labels=(int *) malloc(nr_class*sizeof(int)); - double *prob_estimates=NULL; + int *labels=(int *) malloc(nr_class*sizeof(int)); + double *prob_estimates=NULL; - if(predict_probability) - { - if (svm_type==NU_SVR || svm_type==EPSILON_SVR) - { - otbMsgDevMacro(<<"Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="<<svm_get_svr_probability(model)); - } - else + if (predict_probability) + { + if (svm_type==NU_SVR || svm_type==EPSILON_SVR) + { + otbMsgDevMacro(<<"Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="<<svm_get_svr_probability(model)); + } + else { svm_get_labels(model,labels); prob_estimates = (double *) malloc(nr_class*sizeof(double)); } - } + } - otbMsgDevMacro( << "Starting iterations " ); - while (iter != end && iterO != endO) - { + otbMsgDevMacro( << "Starting iterations " ); + while (iter != end && iterO != endO) + { - int i = 0; - double v; + int i = 0; + double v; - measurements = iter.GetMeasurementVector(); - // otbMsgDevMacro( << "Loop on components " << svm_type ); - for(i=0; i<numberOfComponentsPerSample; i++) + measurements = iter.GetMeasurementVector(); + // otbMsgDevMacro( << "Loop on components " << svm_type ); + for (i=0; i<numberOfComponentsPerSample; i++) { x[i].index = i+1; x[i].value = measurements[i]; } - x[i].index = -1; + x[i].index = -1; - if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC)) + if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC)) { v = svm_predict_probability(model,x,prob_estimates); } - else + else { v = svm_predict(model,x); } - ClassLabelType classLabel; - // Julien: Event if we support larger type for class labels, - // the AddInstance method wait for an unsigned int, so we cast it here. - classLabel = static_cast<unsigned int>(v); + ClassLabelType classLabel; + // Julien: Event if we support larger type for class labels, + // the AddInstance method wait for an unsigned int, so we cast it here. + classLabel = static_cast<unsigned int>(v); - m_Output->AddInstance(classLabel, iterO.GetInstanceIdentifier()); + m_Output->AddInstance(classLabel, iterO.GetInstanceIdentifier()); - ++iter; - ++iterO; + ++iter; + ++iterO; - } + } - if(predict_probability) - { - free(prob_estimates); - free(labels); - } + if (predict_probability) + { + free(prob_estimates); + free(labels); + } - delete [] x; - } + delete [] x; +} } // end of namespace otb diff --git a/Code/Learning/otbSVMImageClassificationFilter.h b/Code/Learning/otbSVMImageClassificationFilter.h index 424e9c1ef420b42f4ee5af81edf18ffad993b700..a1145249f8894a010cac7e5761de84bc7a840924 100644 --- a/Code/Learning/otbSVMImageClassificationFilter.h +++ b/Code/Learning/otbSVMImageClassificationFilter.h @@ -26,106 +26,106 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SVMImageClassificationFilter - * \brief This filter performs the classification of a VectorImage using a SVM Model. - * - * This filter is streamed and threaded, allowing to classify huge images. Because the - * internal sample type has to be an itk::FixedArray, one must specify at compilation time - * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently - * high to integrate all its features. This filter internally use one SVMClassifier per thread. - * - * \sa SVMClassifier - * \ingroup Streamed - * \ingroup Threaded +/** \class SVMImageClassificationFilter + * \brief This filter performs the classification of a VectorImage using a SVM Model. + * + * This filter is streamed and threaded, allowing to classify huge images. Because the + * internal sample type has to be an itk::FixedArray, one must specify at compilation time + * the maximum sample dimension. It is up to the user to specify a MaxSampleDimension sufficiently + * high to integrate all its features. This filter internally use one SVMClassifier per thread. + * + * \sa SVMClassifier + * \ingroup Streamed + * \ingroup Threaded + */ +template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension = 10, class TMaskImage = TOutputImage> +class ITK_EXPORT SVMImageClassificationFilter + : public itk::InPlaceImageFilter<TInputImage,TOutputImage> +{ +public: + /** Standard typedefs */ + typedef SVMImageClassificationFilter Self; + typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(SVMImageClassificationFilter,InPlaceImageFilter); + + /** The max dimension of the sample to classify. + * This filter internally uses itk::FixedArray as input for the classifier, + * so the max sample size has to be fixed at compilation time. + */ + itkStaticConstMacro(MaxSampleDimension,unsigned int,VMaxSampleDimension); + + typedef TInputImage InputImageType; + typedef typename InputImageType::ConstPointer InputImageConstPointerType; + typedef typename InputImageType::InternalPixelType ValueType; + + typedef TMaskImage MaskImageType; + typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; + typedef typename MaskImageType::Pointer MaskImagePointerType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType LabelType; + + typedef itk::FixedArray<ValueType,VMaxSampleDimension> MeasurementVectorType; + typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; + typedef typename ListSampleType::Pointer ListSamplePointerType; + typedef otb::SVMClassifier<ListSampleType, LabelType> ClassifierType; + typedef typename ClassifierType::Pointer ClassifierPointerType; + typedef SVMModel< ValueType, LabelType > ModelType; + typedef typename ModelType::Pointer ModelPointerType; + + /** Set/Get the svm model */ + itkSetObjectMacro(Model,ModelType); + itkGetObjectMacro(Model,ModelType); + + /** Set/Get the default label */ + itkSetMacro(DefaultLabel,LabelType); + itkGetMacro(DefaultLabel,LabelType); + + /** + * If set, only pixels within the mask will be classified. + * \param mask The input mask. */ - template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension = 10, class TMaskImage = TOutputImage> - class ITK_EXPORT SVMImageClassificationFilter - : public itk::InPlaceImageFilter<TInputImage,TOutputImage> - { - public: - /** Standard typedefs */ - typedef SVMImageClassificationFilter Self; - typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(SVMImageClassificationFilter,InPlaceImageFilter); - - /** The max dimension of the sample to classify. - * This filter internally uses itk::FixedArray as input for the classifier, - * so the max sample size has to be fixed at compilation time. - */ - itkStaticConstMacro(MaxSampleDimension,unsigned int,VMaxSampleDimension); - - typedef TInputImage InputImageType; - typedef typename InputImageType::ConstPointer InputImageConstPointerType; - typedef typename InputImageType::InternalPixelType ValueType; - - typedef TMaskImage MaskImageType; - typedef typename MaskImageType::ConstPointer MaskImageConstPointerType; - typedef typename MaskImageType::Pointer MaskImagePointerType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::PixelType LabelType; - - typedef itk::FixedArray<ValueType,VMaxSampleDimension> MeasurementVectorType; - typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; - typedef typename ListSampleType::Pointer ListSamplePointerType; - typedef otb::SVMClassifier<ListSampleType, LabelType> ClassifierType; - typedef typename ClassifierType::Pointer ClassifierPointerType; - typedef SVMModel< ValueType, LabelType > ModelType; - typedef typename ModelType::Pointer ModelPointerType; - - /** Set/Get the svm model */ - itkSetObjectMacro(Model,ModelType); - itkGetObjectMacro(Model,ModelType); - - /** Set/Get the default label */ - itkSetMacro(DefaultLabel,LabelType); - itkGetMacro(DefaultLabel,LabelType); - - /** - * If set, only pixels within the mask will be classified. - * \param mask The input mask. - */ - void SetInputMask(const MaskImageType * mask); - - /** - * Get the input mask. - * \return The mask. - */ - const MaskImageType * GetInputMask(void); - - protected: - /** Constructor */ - SVMImageClassificationFilter(); - /** Destructor */ - virtual ~SVMImageClassificationFilter() {}; - - /** Threaded generate data */ - virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); - /** Before threaded generate data */ - virtual void BeforeThreadedGenerateData(); - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - SVMImageClassificationFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /** The SVM model used for classification */ - ModelPointerType m_Model; - /** Default label for invalid pixels (when using a mask) */ - LabelType m_DefaultLabel; - - - }; + void SetInputMask(const MaskImageType * mask); + + /** + * Get the input mask. + * \return The mask. + */ + const MaskImageType * GetInputMask(void); + +protected: + /** Constructor */ + SVMImageClassificationFilter(); + /** Destructor */ + virtual ~SVMImageClassificationFilter() {}; + + /** Threaded generate data */ + virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread,int threadId); + /** Before threaded generate data */ + virtual void BeforeThreadedGenerateData(); + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + SVMImageClassificationFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** The SVM model used for classification */ + ModelPointerType m_Model; + /** Default label for invalid pixels (when using a mask) */ + LabelType m_DefaultLabel; + + +}; }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbSVMImageClassificationFilter.txx" diff --git a/Code/Learning/otbSVMImageClassificationFilter.txx b/Code/Learning/otbSVMImageClassificationFilter.txx index bfd67e4bc5b19a9297ea395feea40ad9ac9841d0..c13b4f89f324013f7eea323c06e43dc2929e336c 100644 --- a/Code/Learning/otbSVMImageClassificationFilter.txx +++ b/Code/Learning/otbSVMImageClassificationFilter.txx @@ -50,10 +50,10 @@ const typename SVMImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleD SVMImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMaskImage> ::GetInputMask() { - if(this->GetNumberOfInputs()<2) - { - return 0; - } + if (this->GetNumberOfInputs()<2) + { + return 0; + } return static_cast<const MaskImageType *>(this->itk::ProcessObject::GetInput(1)); } @@ -62,10 +62,10 @@ void SVMImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMaskImage> ::BeforeThreadedGenerateData() { - if(!m_Model) - { - itkGenericExceptionMacro(<<"No model for classification"); - } + if (!m_Model) + { + itkGenericExceptionMacro(<<"No model for classification"); + } } template <class TInputImage, class TOutputImage, unsigned int VMaxSampleDimension, class TMaskImage> @@ -86,35 +86,35 @@ SVMImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMaskI InputIteratorType inIt(inputPtr,outputRegionForThread); MaskIteratorType maskIt; - if(inputMaskPtr) - { - maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); - maskIt.GoToBegin(); - } + if (inputMaskPtr) + { + maskIt = MaskIteratorType(inputMaskPtr,outputRegionForThread); + maskIt.GoToBegin(); + } unsigned int sampleSize = std::min(inputPtr->GetNumberOfComponentsPerPixel(), - VMaxSampleDimension); + VMaxSampleDimension); bool validPoint = true; - for(inIt.GoToBegin();!inIt.IsAtEnd();++inIt) - { - if(inputMaskPtr) - { - validPoint = maskIt.Get()>0; - ++maskIt; - } - if(validPoint) + for (inIt.GoToBegin();!inIt.IsAtEnd();++inIt) { - MeasurementVectorType sample; - sample.Fill(itk::NumericTraits<ValueType>::ZeroValue()); - for(unsigned int i=0;i<sampleSize;i++) + if (inputMaskPtr) + { + validPoint = maskIt.Get()>0; + ++maskIt; + } + if (validPoint) + { + MeasurementVectorType sample; + sample.Fill(itk::NumericTraits<ValueType>::ZeroValue()); + for (unsigned int i=0;i<sampleSize;i++) { sample[i]=inIt.Get()[i]; } - listSample->PushBack(sample); - } + listSample->PushBack(sample); } + } ClassifierPointerType classifier =ClassifierType::New(); classifier->SetModel(m_Model); classifier->SetNumberOfClasses(m_Model->GetNumberOfClasses()); @@ -129,34 +129,34 @@ SVMImageClassificationFilter<TInputImage,TOutputImage,VMaxSampleDimension,TMaskI outIt.GoToBegin(); - while(!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) - { - outIt.Set(m_DefaultLabel); - ++outIt; - } + while (!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) + { + outIt.Set(m_DefaultLabel); + ++outIt; + } outIt.GoToBegin(); - if(inputMaskPtr) + if (inputMaskPtr) + { + maskIt.GoToBegin(); + } + validPoint = true; + + while (!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) + { + if (inputMaskPtr) { - maskIt.GoToBegin(); + validPoint = maskIt.Get()>0; + ++maskIt; } - validPoint = true; - - while(!outIt.IsAtEnd()&&(sampleIter!=sampleLast)) - { - if(inputMaskPtr) - { - validPoint = maskIt.Get()>0; - ++maskIt; - } - if(validPoint) - { - outIt.Set(sampleIter.GetClassLabel()); - ++sampleIter; - } - ++outIt; - } + if (validPoint) + { + outIt.Set(sampleIter.GetClassLabel()); + ++sampleIter; + } + ++outIt; + } } /** * PrintSelf Method diff --git a/Code/Learning/otbSVMImageModelEstimator.h b/Code/Learning/otbSVMImageModelEstimator.h index 84382eafa11e57ad71aae4fcab5bc38fd5f91c48..f81eeb4997e269ab1dd4aeafff48baab028ba71d 100644 --- a/Code/Learning/otbSVMImageModelEstimator.h +++ b/Code/Learning/otbSVMImageModelEstimator.h @@ -46,17 +46,17 @@ namespace otb * \ingroup ClassificationFilters */ template <class TInputImage, - class TTrainingImage> +class TTrainingImage> class ITK_EXPORT SVMImageModelEstimator: -public SVMModelEstimator<ITK_TYPENAME TInputImage::InternalPixelType, ITK_TYPENAME TTrainingImage::PixelType> - //public SVMModelEstimator<ITK_TYPENAME TInputImage::PixelType::ComponentType, ITK_TYPENAME TTrainingImage::PixelType> + public SVMModelEstimator<ITK_TYPENAME TInputImage::InternalPixelType, ITK_TYPENAME TTrainingImage::PixelType> + //public SVMModelEstimator<ITK_TYPENAME TInputImage::PixelType::ComponentType, ITK_TYPENAME TTrainingImage::PixelType> { public: /** Standard class typedefs. */ typedef SVMImageModelEstimator Self; typedef SVMModelEstimator<ITK_TYPENAME TInputImage::PixelType::ComponentType, - ITK_TYPENAME TTrainingImage::PixelType> - Superclass; + ITK_TYPENAME TTrainingImage::PixelType> + Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -68,7 +68,7 @@ public: itkTypeMacro(SVMImageModelEstimator, otb::SVMModelEstimator); /** Type definition for the input image. */ - /** Type definitions for the training image. */ + /** Type definitions for the training image. */ typedef typename TInputImage::Pointer InputImagePointer; /** Type definitions for the training image. */ diff --git a/Code/Learning/otbSVMImageModelEstimator.txx b/Code/Learning/otbSVMImageModelEstimator.txx index fc4e8c7865c7695b9832b83bd491a1347a140948..f6ca87add5255e336d986dff61548ae00fdedcb1 100644 --- a/Code/Learning/otbSVMImageModelEstimator.txx +++ b/Code/Learning/otbSVMImageModelEstimator.txx @@ -33,16 +33,16 @@ SVMImageModelEstimator<TInputImage, TTrainingImage> ::SVMImageModelEstimator() { this->m_NumberOfClasses = 0; - this->m_Model = Superclass::SVMModelType::New(); + this->m_Model = Superclass::SVMModelType::New(); - this->m_Done = 0; + this->m_Done = 0; - this->m_Model->SetSVMType(C_SVC); + this->m_Model->SetSVMType(C_SVC); this->m_Model->SetKernelType(LINEAR); this->m_Model->SetPolynomialKernelDegree(3); this->m_Model->SetKernelGamma(0.); // 1/k this->m_Model->SetKernelCoef0(0); - this->m_Model->SetKernelFunctor(NULL); + this->m_Model->SetKernelFunctor(NULL); this->m_Model->SetNu(0.5); this->m_Model->SetCacheSize(40); this->m_Model->SetC(1); @@ -53,7 +53,7 @@ SVMImageModelEstimator<TInputImage, TTrainingImage> } template<class TInputImage, - class TTrainingImage> +class TTrainingImage> SVMImageModelEstimator<TInputImage, TTrainingImage> ::~SVMImageModelEstimator(void) { @@ -63,7 +63,7 @@ SVMImageModelEstimator<TInputImage, TTrainingImage> * PrintSelf */ template<class TInputImage, - class TTrainingImage> +class TTrainingImage> void SVMImageModelEstimator<TInputImage, TTrainingImage> ::PrintSelf( std::ostream& os, itk::Indent indent ) const @@ -78,36 +78,36 @@ SVMImageModelEstimator<TInputImage, TTrainingImage> template<class TInputImage, - class TTrainingImage> +class TTrainingImage> void SVMImageModelEstimator<TInputImage, TTrainingImage> ::BuildProblem() { - //Do some error checking + //Do some error checking InputImagePointer inputImage = this->GetInputImage(); // Check if the training and input image dimensions are same - if( (int)(TInputImage::ImageDimension) != (int)(TTrainingImage::ImageDimension) ) - { + if ( (int)(TInputImage::ImageDimension) != (int)(TTrainingImage::ImageDimension) ) + { throw itk::ExceptionObject(__FILE__, __LINE__,"Training and input image dimensions are not the same.",ITK_LOCATION); - } + } InputImageSizeType - inputImageSize = inputImage->GetBufferedRegion().GetSize(); + inputImageSize = inputImage->GetBufferedRegion().GetSize(); typedef InputImageSizeType TrainingImageSizeType; TrainingImagePointer trainingImage = this->GetTrainingImage(); TrainingImageSizeType - trainingImageSize = trainingImage->GetBufferedRegion().GetSize(); + trainingImageSize = trainingImage->GetBufferedRegion().GetSize(); // Check if size of the two inputs are same - for( unsigned int i = 0; i < TInputImage::ImageDimension; i++) - { - if( inputImageSize[i] != trainingImageSize[i] ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input image size is not the same as the training image size.",ITK_LOCATION); - } + for ( unsigned int i = 0; i < TInputImage::ImageDimension; i++) + { + if ( inputImageSize[i] != trainingImageSize[i] ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input image size is not the same as the training image size.",ITK_LOCATION); + } // Declaration of the iterators on the input and training images @@ -132,27 +132,27 @@ SVMImageModelEstimator<TInputImage, TTrainingImage> unsigned int numberOfComponents = inIt.Get().Size(); - // otbMsgDevMacro( << " Before while " ); - while(!inIt.IsAtEnd() && !trIt.IsAtEnd()) - { +// otbMsgDevMacro( << " Before while " ); + while (!inIt.IsAtEnd() && !trIt.IsAtEnd()) + { - if(trIt.Get()!=0) - { + if (trIt.Get()!=0) + { this->m_Labels.push_back(trIt.Get()); typename Superclass::MeasurementVectorType v; - for(unsigned int k=0; k<numberOfComponents; k++) - { - v.push_back(inIt.Get()[k]); - } + for (unsigned int k=0; k<numberOfComponents; k++) + { + v.push_back(inIt.Get()[k]); + } this->m_Measures.push_back(v); - } + } ++inIt; ++trIt; - } + } this->PrepareData(); } diff --git a/Code/Learning/otbSVMKernels.h b/Code/Learning/otbSVMKernels.h index 5744d15b7c157d4bf70c792e631739cb90294be4..b314c1cee759904613030560d6bd64abd7c87fdf 100644 --- a/Code/Learning/otbSVMKernels.h +++ b/Code/Learning/otbSVMKernels.h @@ -26,252 +26,264 @@ namespace otb { - /** \class CustomKernelFunctor - * \brief Undocumented - */ +/** \class CustomKernelFunctor + * \brief Undocumented + */ class CustomKernelFunctor : public GenericKernelFunctorBase +{ +public: + CustomKernelFunctor(): GenericKernelFunctorBase() { - public: - CustomKernelFunctor(): GenericKernelFunctorBase() { this->SetName("custom"); }; + this->SetName("custom"); + }; virtual ~CustomKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - return ( dot(x, x) - 2.0 * dot( x, y) + dot(y, y) ); - } - }; + { + return ( dot(x, x) - 2.0 * dot( x, y) + dot(y, y) ); + } +}; - /** \class InvMultiQuadricKernelFunctor - * \brief Undocumented - */ +/** \class InvMultiQuadricKernelFunctor + * \brief Undocumented + */ class InvMultiQuadricKernelFunctor : public GenericKernelFunctorBase - { - public: +{ +public: InvMultiQuadricKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("invMultiQuadric"); - this->SetValue<double>("const_coef", 1); - }; + { + this->SetName("invMultiQuadric"); + this->SetValue<double>("const_coef", 1); + }; virtual ~InvMultiQuadricKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - CustomKernelFunctor custom; - double mq = this->GetValue<double>("const_coef") + custom(x, y, param ); - if ( mq == 0.0 ) { - return itk::NumericTraits<double>::max(); - } - return 1.0 / sqrt( mq ); + CustomKernelFunctor custom; + double mq = this->GetValue<double>("const_coef") + custom(x, y, param ); + if ( mq == 0.0 ) + { + return itk::NumericTraits<double>::max(); } - }; + return 1.0 / sqrt( mq ); + } +}; - /** \class KModKernelFunctor - * \brief Undocumented - */ +/** \class KModKernelFunctor + * \brief Undocumented + */ class KModKernelFunctor : public GenericKernelFunctorBase - { - public: +{ +public: KModKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("KMod"); - this->SetValue<double>("const_coef", 1); - }; + { + this->SetName("KMod"); + this->SetValue<double>("const_coef", 1); + }; virtual ~KModKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - CustomKernelFunctor custom; - double mq = this->GetValue<double>("const_coef") + custom(x, y, param); - - if ( mq == 0.0 ) { - return itk::NumericTraits<double>::max(); - } - return exp( param.gamma / mq ) - 1.0; + CustomKernelFunctor custom; + double mq = this->GetValue<double>("const_coef") + custom(x, y, param); + + if ( mq == 0.0 ) + { + return itk::NumericTraits<double>::max(); } - }; + return exp( param.gamma / mq ) - 1.0; + } +}; - /** \class SAMKernelFunctor - * \brief Undocumented - */ +/** \class SAMKernelFunctor + * \brief Undocumented + */ class SAMKernelFunctor : public GenericKernelFunctorBase +{ +public: + SAMKernelFunctor(): GenericKernelFunctorBase() { - public: - SAMKernelFunctor(): GenericKernelFunctorBase() { this->SetName("SAM"); }; + this->SetName("SAM"); + }; virtual ~SAMKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - double den = dot(x, x) * dot(y, y); - if ( den <= 0. ) { - return 0.0; - } - double ss = dot( x, y ); - return vcl_acos( ss / vcl_sqrt( den ) ); + double den = dot(x, x) * dot(y, y); + if ( den <= 0. ) + { + return 0.0; } - }; + double ss = dot( x, y ); + return vcl_acos( ss / vcl_sqrt( den ) ); + } +}; - /** \class RadialSAMKernelFunctor - * \brief Undocumented - */ +/** \class RadialSAMKernelFunctor + * \brief Undocumented + */ class RadialSAMKernelFunctor : public GenericKernelFunctorBase +{ +public: + RadialSAMKernelFunctor(): GenericKernelFunctorBase() { - public: - RadialSAMKernelFunctor(): GenericKernelFunctorBase() { this->SetName("RadialSAM"); }; - virtual ~RadialSAMKernelFunctor() {}; - - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - SAMKernelFunctor sam; - return vcl_exp( - param.gamma * sam( x, y, param ) ); - } + this->SetName("RadialSAM"); }; + virtual ~RadialSAMKernelFunctor() {}; - /** \class InverseCosSAMKernelFunctor - * \brief Undocumented - */ -class InverseCosSAMKernelFunctor : public GenericKernelFunctorBase + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const { - public: - InverseCosSAMKernelFunctor(): GenericKernelFunctorBase() { this->SetName("InverseCosSAM"); }; - virtual ~InverseCosSAMKernelFunctor() {}; + SAMKernelFunctor sam; + return vcl_exp( - param.gamma * sam( x, y, param ) ); + } +}; - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - SAMKernelFunctor sam; - return 1.0 - vcl_cos( sam( x, y, param ) ); - } +/** \class InverseCosSAMKernelFunctor + * \brief Undocumented + */ +class InverseCosSAMKernelFunctor : public GenericKernelFunctorBase +{ +public: + InverseCosSAMKernelFunctor(): GenericKernelFunctorBase() + { + this->SetName("InverseCosSAM"); }; + virtual ~InverseCosSAMKernelFunctor() {}; + + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const + { + SAMKernelFunctor sam; + return 1.0 - vcl_cos( sam( x, y, param ) ); + } +}; - /** \class InvMultiQuadraticSAMKernelFunctor - * \brief Undocumented - */ +/** \class InvMultiQuadraticSAMKernelFunctor + * \brief Undocumented + */ class InvMultiQuadraticSAMKernelFunctor : public GenericKernelFunctorBase - { - public: +{ +public: InvMultiQuadraticSAMKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("invMultiQuadraticSAM"); - this->SetValue<double>("const_coef", 1); - }; + { + this->SetName("invMultiQuadraticSAM"); + this->SetValue<double>("const_coef", 1); + }; virtual ~InvMultiQuadraticSAMKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - SAMKernelFunctor sam; - double mq = this->GetValue<double>("const_coef") + sam( x, y, param ); - - if ( mq == 0. ) { - return itk::NumericTraits<double>::max(); - } - return 1. / sqrt( mq ); + SAMKernelFunctor sam; + double mq = this->GetValue<double>("const_coef") + sam( x, y, param ); + + if ( mq == 0. ) + { + return itk::NumericTraits<double>::max(); } - }; + return 1. / sqrt( mq ); + } +}; - /** \class KModSAMKernelFunctor - * \brief Undocumented - */ +/** \class KModSAMKernelFunctor + * \brief Undocumented + */ class KModSAMKernelFunctor : public GenericKernelFunctorBase +{ +public: + KModSAMKernelFunctor(): GenericKernelFunctorBase() { - public: - KModSAMKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("KModSAM"); - this->SetValue<double>("const_coef", 1); - }; - virtual ~KModSAMKernelFunctor() {}; + this->SetName("KModSAM"); + this->SetValue<double>("const_coef", 1); + }; + virtual ~KModSAMKernelFunctor() {}; - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - SAMKernelFunctor sam; - double mq = this->GetValue<double>("const_coef") + sam( x, y, param ); + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const + { + SAMKernelFunctor sam; + double mq = this->GetValue<double>("const_coef") + sam( x, y, param ); - if ( mq == 0. ) + if ( mq == 0. ) { return itk::NumericTraits<double>::max(); } - return vcl_exp( param.gamma / mq ) - 1.0; - } - }; + return vcl_exp( param.gamma / mq ) - 1.0; + } +}; - /** \class RBFKernelFunctor - * \brief Undocumented - */ +/** \class RBFKernelFunctor + * \brief Undocumented + */ class RBFKernelFunctor : public GenericKernelFunctorBase +{ +public: + RBFKernelFunctor(): GenericKernelFunctorBase() { - public: - RBFKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("RBF"); - this->SetValue<double>("gamma_coef", 0.5); - }; - virtual ~RBFKernelFunctor() {}; + this->SetName("RBF"); + this->SetValue<double>("gamma_coef", 0.5); + }; + virtual ~RBFKernelFunctor() {}; - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - CustomKernelFunctor custom; - double res = this->GetValue<double>("gamma_coef") * custom( x, y, param ); + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const + { + CustomKernelFunctor custom; + double res = this->GetValue<double>("gamma_coef") * custom( x, y, param ); - return vcl_exp(-res); - } + return vcl_exp(-res); + } - virtual double derivative(const svm_node *x, const svm_node *y, const svm_parameter& param, int degree, int index, bool isAtEnd, double constValue)const - { - double gamma = this->GetValue<double>("gamma_coef"); - double kernelValue = 0.; - double xval = 0.; - double yval = 0.; - int compt = 0; + virtual double derivative(const svm_node *x, const svm_node *y, const svm_parameter& param, int degree, int index, bool isAtEnd, double constValue)const + { + double gamma = this->GetValue<double>("gamma_coef"); + double kernelValue = 0.; + double xval = 0.; + double yval = 0.; + int compt = 0; - const svm_node *xtemp = x; - const svm_node *ytemp = y; + const svm_node *xtemp = x; + const svm_node *ytemp = y; - bool stop = false; - while(xtemp->index != -1 && ytemp->index != -1 && stop == false) + bool stop = false; + while (xtemp->index != -1 && ytemp->index != -1 && stop == false) { - if(xtemp->index == ytemp->index) - { - if (compt == index) + if (xtemp->index == ytemp->index) { - xval = xtemp->value; - yval = ytemp->value; - stop = true; - } - else - { - compt++; - ++ytemp; - ++xtemp; - } + if (compt == index) + { + xval = xtemp->value; + yval = ytemp->value; + stop = true; } - else + else { - if(xtemp->index > ytemp->index) - ++ytemp; - else - ++xtemp; + compt++; + ++ytemp; + ++xtemp; } + } + else + { + if (xtemp->index > ytemp->index) + ++ytemp; + else + ++xtemp; + } } - if (isAtEnd == true) + if (isAtEnd == true) { kernelValue = this->operator()(x, y, param); } - else + else { kernelValue = constValue; } - if (degree < 0) + if (degree < 0) { return 0; } - switch (degree) + switch (degree) { case 0: return kernelValue; @@ -284,206 +296,215 @@ class RBFKernelFunctor : public GenericKernelFunctorBase break; } - } + } - }; +}; - /** \class RBFRBFSAMKernelFunctor - * \brief Undocumented - */ +/** \class RBFRBFSAMKernelFunctor +* \brief Undocumented + */ class RBFRBFSAMKernelFunctor : public GenericKernelFunctorBase - { - public: +{ +public: RBFRBFSAMKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("RBFRBFSAM"); - this->SetValue<double>("lin_coef", 1.); - }; + { + this->SetName("RBFRBFSAM"); + this->SetValue<double>("lin_coef", 1.); + }; virtual ~RBFRBFSAMKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - CustomKernelFunctor custom; - RadialSAMKernelFunctor radialSam; - return ( this->GetValue<double>("lin_coef") * vcl_exp( -param.gamma * custom(x, y, param) ) - + ( 1.0 - this->GetValue<double>("lin_coef") ) * radialSam( x, y, param ) ); - } - }; + { + CustomKernelFunctor custom; + RadialSAMKernelFunctor radialSam; + return ( this->GetValue<double>("lin_coef") * vcl_exp( -param.gamma * custom(x, y, param) ) + + ( 1.0 - this->GetValue<double>("lin_coef") ) * radialSam( x, y, param ) ); + } +}; - /** \class PolyRBFSAMKernelFunctor - * \brief Undocumented - */ +/** \class PolyRBFSAMKernelFunctor +* \brief Undocumented + */ class PolyRBFSAMKernelFunctor : public GenericKernelFunctorBase - { - public: +{ +public: PolyRBFSAMKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("polyRBFSAM"); - this->SetValue<double>("const_coef", 1); - this->SetValue<double>("lin_coef", 1); - }; + { + this->SetName("polyRBFSAM"); + this->SetValue<double>("const_coef", 1); + this->SetValue<double>("lin_coef", 1); + }; virtual ~PolyRBFSAMKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - RadialSAMKernelFunctor radialSam; - return this->GetValue<double>("const_lin") * vcl_pow( dot(x, y)+this->GetValue<double>("const_coef") , param.degree) - + ( 1.0 - this->GetValue<double>("const_coef") ) - * radialSam( x, y, param ); - } - }; + { + RadialSAMKernelFunctor radialSam; + return this->GetValue<double>("const_lin") * vcl_pow( dot(x, y)+this->GetValue<double>("const_coef") , param.degree) + + ( 1.0 - this->GetValue<double>("const_coef") ) + * radialSam( x, y, param ); + } +}; - /** \class RBFDiffKernelFunctor - * \brief Undocumented - */ +/** \class RBFDiffKernelFunctor +* \brief Undocumented + */ class RBFDiffKernelFunctor : public GenericKernelFunctorBase +{ +public: + RBFDiffKernelFunctor(): GenericKernelFunctorBase() { - public: - RBFDiffKernelFunctor(): GenericKernelFunctorBase() { this->SetName("RBFDiff"); }; + this->SetName("RBFDiff"); + }; virtual ~RBFDiffKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { + { - double total = 0.; + double total = 0.; - while (x->index != -1 && y->index != -1) - { - if (x->index == y->index) + while (x->index != -1 && y->index != -1) + { + if (x->index == y->index) { total = total + vcl_exp(-param.gamma*(x->value - y->value)); ++x; ++y; } - else + else { - if(x->index < y->index) - { - ++x; - } + if (x->index < y->index) + { + ++x; + } else - { - ++y; - } + { + ++y; + } } - } - return total; } - }; + return total; + } +}; - /** \class CustomLinearKernelFunctor - * \brief Undocumented - */ +/** \class CustomLinearKernelFunctor +* \brief Undocumented + */ class CustomLinearKernelFunctor : public GenericKernelFunctorBase +{ +public: + CustomLinearKernelFunctor(): GenericKernelFunctorBase() { - public: - CustomLinearKernelFunctor(): GenericKernelFunctorBase() { this->SetName("customLinear"); }; + this->SetName("customLinear"); + }; virtual ~CustomLinearKernelFunctor() {}; virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - CustomKernelFunctor custom; - return( vcl_exp(-param.gamma*custom(x, y, param)) ); - } - }; + { + CustomKernelFunctor custom; + return( vcl_exp(-param.gamma*custom(x, y, param)) ); + } +}; - /** \class GroupedRBFKernelFunctor - * \brief Undocumented - */ +/** \class GroupedRBFKernelFunctor +* \brief Undocumented + */ class GroupedRBFKernelFunctor : public GenericKernelFunctorBase +{ +public: + GroupedRBFKernelFunctor(): GenericKernelFunctorBase() { - public: - GroupedRBFKernelFunctor(): GenericKernelFunctorBase() { this->SetName("groupedRBF"); }; - virtual ~GroupedRBFKernelFunctor() {}; + this->SetName("groupedRBF"); + }; + virtual ~GroupedRBFKernelFunctor() {}; - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - const char *parameters = param.custom; - const char * twoPoints = ":"; - const char * position = strpbrk (parameters, twoPoints); - int twoPointsPosition = 0; - double total = 0.; - double value = 0.; - int numberOfGroups = atoi(parameters); + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const + { + const char *parameters = param.custom; + const char * twoPoints = ":"; + const char * position = strpbrk (parameters, twoPoints); + int twoPointsPosition = 0; + double total = 0.; + double value = 0.; + int numberOfGroups = atoi(parameters); - twoPointsPosition = position - parameters; + twoPointsPosition = position - parameters; - parameters = parameters + twoPointsPosition + 1; + parameters = parameters + twoPointsPosition + 1; - int i,j; - std::vector<int> begin; - begin.resize(numberOfGroups); - std::vector<int> end; - end.resize(numberOfGroups); + int i,j; + std::vector<int> begin; + begin.resize(numberOfGroups); + std::vector<int> end; + end.resize(numberOfGroups); - for (i = 0; i < numberOfGroups; i++) - { - begin[i] = atoi(parameters); - position = strpbrk (parameters, twoPoints); - twoPointsPosition = position - parameters; - parameters = parameters + twoPointsPosition + 1; + for (i = 0; i < numberOfGroups; i++) + { + begin[i] = atoi(parameters); + position = strpbrk (parameters, twoPoints); + twoPointsPosition = position - parameters; + parameters = parameters + twoPointsPosition + 1; - end[i] = atoi(parameters); - parameters = parameters + twoPointsPosition + 1; - } + end[i] = atoi(parameters); + parameters = parameters + twoPointsPosition + 1; + } - const svm_node * xBuff = x; - const svm_node * yBuff = y; + const svm_node * xBuff = x; + const svm_node * yBuff = y; - int sizeX = 0; - int sizeY = 0; + int sizeX = 0; + int sizeY = 0; - while (xBuff->index != 1) - { - sizeX++; - ++xBuff; - } + while (xBuff->index != 1) + { + sizeX++; + ++xBuff; + } - while (yBuff->index != 1) - { - sizeY++; - ++yBuff; - } + while (yBuff->index != 1) + { + sizeY++; + ++yBuff; + } - const svm_node * xTemp = NULL; - const svm_node * yTemp = NULL; + const svm_node * xTemp = NULL; + const svm_node * yTemp = NULL; - int index = 0; + int index = 0; - if (sizeX && sizeY) - { - svm_node* xGroup = new svm_node[sizeX]; - svm_node* yGroup = new svm_node[sizeY]; - for (j = 0; j < numberOfGroups; j++) + if (sizeX && sizeY) + { + svm_node* xGroup = new svm_node[sizeX]; + svm_node* yGroup = new svm_node[sizeY]; + for (j = 0; j < numberOfGroups; j++) { xTemp = x; yTemp = y; index = 0; while (xTemp->index != 1 && yTemp->index != 1) - { - xGroup[index].index = xTemp->index; - yGroup[index].index = yTemp->index; - if((xTemp->index < begin[j]) || (xTemp->index > end[j])) - { - xGroup[index].value = 0; - yGroup[index].value = 0; - } - else { - xGroup[index].value = xTemp->value; - yGroup[index].value = yTemp->value; + xGroup[index].index = xTemp->index; + yGroup[index].index = yTemp->index; + if ((xTemp->index < begin[j]) || (xTemp->index > end[j])) + { + xGroup[index].value = 0; + yGroup[index].value = 0; + } + else + { + xGroup[index].value = xTemp->value; + yGroup[index].value = yTemp->value; + } + ++index; + ++xTemp; + ++yTemp; } - ++index; - ++xTemp; - ++yTemp; - } // value can have different value according to j CustomLinearKernelFunctor customLinear; @@ -491,231 +512,231 @@ class GroupedRBFKernelFunctor : public GenericKernelFunctorBase total += value; } - delete [] xGroup; - delete [] yGroup; - } + delete [] xGroup; + delete [] yGroup; + } - else if ((sizeX > 0) && (sizeY == 0)) - { - svm_node* xGroup = new svm_node[sizeX]; - svm_node* yGroup = new svm_node[sizeY]; + else if ((sizeX > 0) && (sizeY == 0)) + { + svm_node* xGroup = new svm_node[sizeX]; + svm_node* yGroup = new svm_node[sizeY]; - for (j = 0; j < numberOfGroups; j++) + for (j = 0; j < numberOfGroups; j++) { xTemp = x; index = 0; while (xTemp->index != -1) - { - xGroup[index].index = xTemp->index; - yGroup[index].index = xTemp->index; - - if((xTemp->index < begin[j]) || (xTemp->index > end[j])) { - xGroup[index].value = 0; - yGroup[index].value = 0; + xGroup[index].index = xTemp->index; + yGroup[index].index = xTemp->index; + + if ((xTemp->index < begin[j]) || (xTemp->index > end[j])) + { + xGroup[index].value = 0; + yGroup[index].value = 0; + } + else + { + xGroup[index].value = xTemp->value; + yGroup[index].value = 0; + } + ++index; + ++xTemp; } - else - { - xGroup[index].value = xTemp->value; - yGroup[index].value = 0; - } - ++index; - ++xTemp; - } - // value can have different value according to j + // value can have different value according to j CustomLinearKernelFunctor customLinear; value = customLinear(xGroup, yGroup, param); total += value; } - delete [] xGroup; - delete [] yGroup; - } + delete [] xGroup; + delete [] yGroup; + } - else - { - CustomLinearKernelFunctor customLinear; - total = static_cast<double>(numberOfGroups) * customLinear(x, y, param); - } + else + { + CustomLinearKernelFunctor customLinear; + total = static_cast<double>(numberOfGroups) * customLinear(x, y, param); + } - if(xTemp != NULL) - delete xTemp; - if(yTemp != NULL) - delete yTemp; + if (xTemp != NULL) + delete xTemp; + if (yTemp != NULL) + delete yTemp; - return total; - } - }; + return total; + } +}; - /** \class GroupingAdaptiveKernelFunctor - * \brief Undocumented - */ +/** \class GroupingAdaptiveKernelFunctor + * \brief Undocumented + */ class GroupingAdaptiveKernelFunctor : public GenericKernelFunctorBase +{ +public: + GroupingAdaptiveKernelFunctor(): GenericKernelFunctorBase() { - public: - GroupingAdaptiveKernelFunctor(): GenericKernelFunctorBase() - { - this->SetName("groupingAdaptive"); - this->SetValue<double>("lin_coef", 1.); - this->SetValue<double>("const_coef", 1.); - }; - virtual ~GroupingAdaptiveKernelFunctor() {}; + this->SetName("groupingAdaptive"); + this->SetValue<double>("lin_coef", 1.); + this->SetValue<double>("const_coef", 1.); + }; + virtual ~GroupingAdaptiveKernelFunctor() {}; - virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const - { - const char * parameters = param.custom; - const char * twoPoints = ":"; - const char * position = strpbrk (parameters, twoPoints); - int twoPointsPosition = 0; - double total = 0.; - double value = 0.; - int numberOfGroups = atoi(parameters); + virtual double operator()(const svm_node *x, const svm_node *y, const svm_parameter& param)const + { + const char * parameters = param.custom; + const char * twoPoints = ":"; + const char * position = strpbrk (parameters, twoPoints); + int twoPointsPosition = 0; + double total = 0.; + double value = 0.; + int numberOfGroups = atoi(parameters); - twoPointsPosition = position - parameters; + twoPointsPosition = position - parameters; - parameters = parameters + twoPointsPosition + 1; + parameters = parameters + twoPointsPosition + 1; - int i,j; + int i,j; std::vector<int> begin; begin.resize(numberOfGroups); std::vector<int> end; end.resize(numberOfGroups); - for (i = 0; i < numberOfGroups; i++) - { - begin[i] = atoi(parameters); - position = strpbrk (parameters, twoPoints); - twoPointsPosition = position - parameters; - parameters = parameters + twoPointsPosition + 1; + for (i = 0; i < numberOfGroups; i++) + { + begin[i] = atoi(parameters); + position = strpbrk (parameters, twoPoints); + twoPointsPosition = position - parameters; + parameters = parameters + twoPointsPosition + 1; + + end[i] = atoi(parameters); + parameters = parameters + twoPointsPosition + 1; + } + + + const svm_node * xBuff = x; + const svm_node * yBuff = y; + + int sizeX = 0; + int sizeY = 0; + + while (xBuff->index != 1) + { + sizeX++; + ++xBuff; + } + + while (yBuff->index != 1) + { + sizeY++; + ++yBuff; + } + + + const svm_node * xTemp = NULL; + const svm_node * yTemp = NULL; + + int index = 0; - end[i] = atoi(parameters); - parameters = parameters + twoPointsPosition + 1; - } + if (sizeX && sizeY) + { + svm_node* xGroup = new svm_node[sizeX]; + svm_node* yGroup = new svm_node[sizeY]; + + for (j = 0; j < numberOfGroups; j++) + { + xTemp = x; + yTemp = y; + index = 0; + + while (xTemp->index != 1 && yTemp->index != 1) + { + xGroup[index].index = xTemp->index; + yGroup[index].index = yTemp->index; + if ((xTemp->index < begin[j]) || (xTemp->index > end[j])) + { + xGroup[index].value = 0; + yGroup[index].value = 0; + } + else + { + xGroup[index].value = xTemp->value; + yGroup[index].value = yTemp->value; + } + ++index; + ++xTemp; + ++yTemp; + } + + // value can have different value according to j + value = vcl_pow(this->GetValue<double>("lin_coef")*dot(xGroup,yGroup)+this->GetValue<double>("const_coef"),static_cast<double>(param.degree)); - const svm_node * xBuff = x; - const svm_node * yBuff = y; - - int sizeX = 0; - int sizeY = 0; - - while (xBuff->index != 1) - { - sizeX++; - ++xBuff; - } - - while (yBuff->index != 1) - { - sizeY++; - ++yBuff; - } - - - const svm_node * xTemp = NULL; - const svm_node * yTemp = NULL; - - int index = 0; - - - if (sizeX && sizeY) - { - svm_node* xGroup = new svm_node[sizeX]; - svm_node* yGroup = new svm_node[sizeY]; - - for (j = 0; j < numberOfGroups; j++) - { - xTemp = x; - yTemp = y; - index = 0; - - while (xTemp->index != 1 && yTemp->index != 1) - { - xGroup[index].index = xTemp->index; - yGroup[index].index = yTemp->index; - if((xTemp->index < begin[j]) || (xTemp->index > end[j])) - { - xGroup[index].value = 0; - yGroup[index].value = 0; - } - else - { - xGroup[index].value = xTemp->value; - yGroup[index].value = yTemp->value; - } - ++index; - ++xTemp; - ++yTemp; - } - - // value can have different value according to j - value = vcl_pow(this->GetValue<double>("lin_coef")*dot(xGroup,yGroup)+this->GetValue<double>("const_coef"),static_cast<double>(param.degree)); - - total += value; - } - delete [] xGroup; - delete [] yGroup; + total += value; } + delete [] xGroup; + delete [] yGroup; + } - else if ((sizeX > 0) && (sizeY == 0)) - { - svm_node* xGroup = new svm_node[sizeX]; - svm_node* yGroup = new svm_node[sizeY]; - - for (j = 0; j < numberOfGroups; j++) - { - xTemp = x; - index = 0; - - while (xTemp->index != 1) - { - xGroup[index].index = xTemp->index; - yGroup[index].index = xTemp->index; - - if((xTemp->index < begin[j]) || (xTemp->index > end[j])) - { - xGroup[index].value = 0; - yGroup[index].value = 0; - } - else - { - xGroup[index].value = xTemp->value; - yGroup[index].value = 0; - } - ++index; - ++xTemp; - } - - // value can have different value according to j - value = vcl_pow(this->GetValue<double>("lin_coef")*dot(xGroup,yGroup)+this->GetValue<double>("const_coef"),static_cast<double>(param.degree)); - - total += value; - } - delete [] xGroup; - delete [] yGroup; - } - - else - { - CustomKernelFunctor custom; - total = static_cast<double>(numberOfGroups) * custom(x, y, param); - } - - return total; + else if ((sizeX > 0) && (sizeY == 0)) + { + svm_node* xGroup = new svm_node[sizeX]; + svm_node* yGroup = new svm_node[sizeY]; + + for (j = 0; j < numberOfGroups; j++) + { + xTemp = x; + index = 0; + + while (xTemp->index != 1) + { + xGroup[index].index = xTemp->index; + yGroup[index].index = xTemp->index; + + if ((xTemp->index < begin[j]) || (xTemp->index > end[j])) + { + xGroup[index].value = 0; + yGroup[index].value = 0; + } + else + { + xGroup[index].value = xTemp->value; + yGroup[index].value = 0; + } + ++index; + ++xTemp; + } + + // value can have different value according to j + value = vcl_pow(this->GetValue<double>("lin_coef")*dot(xGroup,yGroup)+this->GetValue<double>("const_coef"),static_cast<double>(param.degree)); + + total += value; } - }; + delete [] xGroup; + delete [] yGroup; + } + + else + { + CustomKernelFunctor custom; + total = static_cast<double>(numberOfGroups) * custom(x, y, param); + } + + return total; + } +}; } #endif diff --git a/Code/Learning/otbSVMModel.h b/Code/Learning/otbSVMModel.h index 62a7e0b875512ecdfff16f3998cd3ca46f97b28e..aa7c17a5033931bf8c2a1eab40a61048538ae5e6 100644 --- a/Code/Learning/otbSVMModel.h +++ b/Code/Learning/otbSVMModel.h @@ -134,36 +134,36 @@ public: // itkSetMacro(NumberOfClasses, unsigned int); void SetNumberOfClasses(const unsigned int nr_class) { - m_Model->nr_class = (int)nr_class; + m_Model->nr_class = (int)nr_class; } /** Get the number of classes. */ unsigned int GetNumberOfClasses(void) { - return (unsigned int)(m_Model->nr_class); + return (unsigned int)(m_Model->nr_class); } /** Get the number of hyperplane. */ unsigned int GetNumberOfHyperplane(void) { - return (unsigned int)(m_Model->nr_class - 1); + return (unsigned int)(m_Model->nr_class - 1); } /** Gets the problem */ struct svm_problem & GetProblem() { - return m_Problem; + return m_Problem; } /** Sets the x space */ void SetXSpace(struct svm_node* x_space) { - m_XSpace = x_space; + m_XSpace = x_space; } /** Gets the x space */ struct svm_node* GetXSpace() { - return m_XSpace; + return m_XSpace; } /** Allocates the problem */ @@ -187,10 +187,10 @@ public: } /** Gets the parameters */ const struct svm_parameter & GetParameters() const - { - //return m_Parameters; - return m_Model->param; - } + { + //return m_Parameters; + return m_Model->param; + } /** Saves the model to a file */ @@ -200,7 +200,7 @@ public: /** Loads the model from a file */ void LoadModel(const char* model_file_name); - /** Copy the model */ + /** Copy the model */ Pointer GetCopy(); /** Set the SVM type to C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR */ @@ -260,7 +260,7 @@ public: m_Model->param.gamma = gamma; this->Modified(); } - /** Get the gamma parameter for poly/rbf/sigmoid kernels */ + /** Get the gamma parameter for poly/rbf/sigmoid kernels */ double GetKernelGamma(void) { //return m_Parameters.gamma; @@ -286,16 +286,16 @@ public: void SetNu(double nu) { //m_Parameters.nu = nu; - m_Model->param.nu = nu; + m_Model->param.nu = nu; this->Modified(); } /** Set the Nu parameter for the training */ double GetNu(void) - { - //return m_Parameters.nu; - return m_Model->param.nu; - } + { + //return m_Parameters.nu; + return m_Model->param.nu; + } /** Set the cache size in MB for the training */ void SetCacheSize(int cSize) @@ -320,7 +320,7 @@ public: this->Modified(); } -/** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ + /** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ double GetC(void) { //return m_Parameters.C; @@ -408,23 +408,23 @@ public: /** Return number of support vectors */ int GetNumberOfSupportVectors(void) { - return m_Model->l; + return m_Model->l; } - /** Set number of support vectors */ + /** Set number of support vectors */ void SetNumberOfSupportVectors(int l) - { - m_Model->l = l; - } + { + m_Model->l = l; + } /** Return rho values */ double * GetRho(void) { - return m_Model->rho; + return m_Model->rho; } /** Return the support vectors */ svm_node ** GetSupportVectors(void) { - return m_Model->SV; + return m_Model->SV; } /** Set the support vectors and changes the l number of support vectors accordind to sv.*/ void SetSupportVectors(svm_node ** sv, int nbOfSupportVector); @@ -432,27 +432,30 @@ public: /** Return the alphas values (SV Coef) */ double ** GetAlpha (void) { - return m_Model->sv_coef; + return m_Model->sv_coef; } - /** Set the alphas values (SV Coef) */ + /** Set the alphas values (SV Coef) */ void SetAlpha( double ** alpha, int nbOfSupportVector ); /** Return the labels lists */ - int * GetLabels(){ return m_Model->label; }; + int * GetLabels() + { + return m_Model->label; + }; /** Set the number of SV per classes */ void SetNumberOfSVPerClasse( int * vect) - { - for(int i=0;i<m_Model->nr_class;i++) - m_Model->nSV[i] = vect[i]; - this->Modified(); - } + { + for (int i=0;i<m_Model->nr_class;i++) + m_Model->nSV[i] = vect[i]; + this->Modified(); + } /** Get the number of SV per classes */ int * GetNumberOfSVPerClasse() - { - return m_Model->nSV; - } + { + return m_Model->nSV; + } /** Evaluate model */ double Evaluate(void); diff --git a/Code/Learning/otbSVMModel.txx b/Code/Learning/otbSVMModel.txx index 8299bbba019025ce29321cddc435e012d413389a..8f1fda727d35a89be3546afb14f672e85d15126d 100644 --- a/Code/Learning/otbSVMModel.txx +++ b/Code/Learning/otbSVMModel.txx @@ -76,7 +76,7 @@ SVMModel<TInputPixel, TLabel>::~SVMModel() delete [] m_XSpace;// otbMsgDevMacro( << "SVMModel destructor - m_XSpace done" ); //free(m_XSpace); -*/ + */ //svm_destroy_model(m_Model); @@ -86,34 +86,34 @@ template <class TInputPixel, class TLabel > void SVMModel<TInputPixel, TLabel> ::AllocateProblem(int l, long int elements) - { - otbMsgDevMacro( << "SVMModel::AllocateProblem - enter" ); - otbMsgDevMacro( << "SVMModel::AllocateProblem - l = " << l ); - otbMsgDevMacro( << "SVMModel::AllocateProblem - elements = " << elements ); - otbMsgDevMacro( << "SVMModel::AllocateProblem - m_Problem.l = " << m_Problem.l ); - m_Problem.l = l; - otbMsgDevMacro( << "SVMModel::AllocateProblem - m_Problem.l = " << m_Problem.l ); - otbMsgDevMacro( << "SVMModel::AllocateProblem - l done" ); - delete [] m_Problem.y; - m_Problem.y = new double[l];//Malloc(double,l); - otbMsgDevMacro( << "SVMModel::AllocateProblem - y done" ); - delete [] m_Problem.x; - m_Problem.x = new struct svm_node*[l];//Malloc(struct svm_node* ,l); - otbMsgDevMacro( << "SVMModel::AllocateProblem - x done" ); - delete [] m_XSpace; - m_XSpace = new struct svm_node[elements]; - - for(long int i = 0;i<elements;++i) - { - m_XSpace[i].value = 0; - m_XSpace[i].index = -1; - } - - //free(m_XSpace); - //m_XSpace = Malloc(struct svm_node,elements); - //otbMsgDevMacro( << "SVMModel::AllocateProblem - m_XSpace done" ); - - } +{ + otbMsgDevMacro( << "SVMModel::AllocateProblem - enter" ); + otbMsgDevMacro( << "SVMModel::AllocateProblem - l = " << l ); + otbMsgDevMacro( << "SVMModel::AllocateProblem - elements = " << elements ); + otbMsgDevMacro( << "SVMModel::AllocateProblem - m_Problem.l = " << m_Problem.l ); + m_Problem.l = l; + otbMsgDevMacro( << "SVMModel::AllocateProblem - m_Problem.l = " << m_Problem.l ); + otbMsgDevMacro( << "SVMModel::AllocateProblem - l done" ); + delete [] m_Problem.y; + m_Problem.y = new double[l];//Malloc(double,l); + otbMsgDevMacro( << "SVMModel::AllocateProblem - y done" ); + delete [] m_Problem.x; + m_Problem.x = new struct svm_node*[l];//Malloc(struct svm_node* ,l); + otbMsgDevMacro( << "SVMModel::AllocateProblem - x done" ); + delete [] m_XSpace; + m_XSpace = new struct svm_node[elements]; + + for (long int i = 0;i<elements;++i) + { + m_XSpace[i].value = 0; + m_XSpace[i].index = -1; + } + + //free(m_XSpace); + //m_XSpace = Malloc(struct svm_node,elements); + //otbMsgDevMacro( << "SVMModel::AllocateProblem - m_XSpace done" ); + +} template <class TInputPixel, class TLabel > @@ -155,11 +155,11 @@ void SVMModel<TInputPixel, TLabel> ::SaveModel(const char* model_file_name) { - if(svm_save_model(model_file_name, m_Model)!=0) - { - itkExceptionMacro( << "Problem while saving SVM model " - << std::string(model_file_name) ); - } + if (svm_save_model(model_file_name, m_Model)!=0) + { + itkExceptionMacro( << "Problem while saving SVM model " + << std::string(model_file_name) ); + } } template <class TInputPixel, class TLabel > @@ -169,11 +169,11 @@ SVMModel<TInputPixel, TLabel> { //m_Model = svm_load_model(model_file_name,m_Parameters.kernel_generic/*m_GenericKernelFunctor*/); m_Model = svm_load_model(model_file_name, m_Model->param.kernel_generic/*m_GenericKernelFunctor*/); - if(m_Model == 0) - { - itkExceptionMacro( << "Problem while loading SVM model " - << std::string(model_file_name) ); - } + if (m_Model == 0) + { + itkExceptionMacro( << "Problem while loading SVM model " + << std::string(model_file_name) ); + } } template <class TInputPixel, class TLabel > @@ -228,10 +228,10 @@ SVMModel<TInputPixel, TLabel> // delete just the first element, it destoyes the whole pointers (cf SV filling with x_space) delete [] (m_Model->SV[0]); - for(int n = 0; n<m_Model->l; n++) - { - m_Model->SV[n] = NULL; - } + for (int n = 0; n<m_Model->l; n++) + { + m_Model->SV[n] = NULL; + } delete[] (m_Model->SV); m_Model->SV = NULL; @@ -244,43 +244,43 @@ SVMModel<TInputPixel, TLabel> // Compute the total number of SV elements. unsigned int elements = 0; for (int p=0; p<nbOfSupportVector; p++) - { - std::cout<<p<<" "; - const svm_node *tempNode = sv[p]; - std::cout<<p<<" "; - while(tempNode->index != -1) { - tempNode++; - elements++; - } - elements++;// for -1 values + std::cout<<p<<" "; + const svm_node *tempNode = sv[p]; + std::cout<<p<<" "; + while (tempNode->index != -1) + { + tempNode++; + elements++; } + elements++;// for -1 values + } - if(m_Model->l>0) - { - SV[0] = Malloc(svm_node,elements); - memcpy( SV[0],sv[0],sizeof(svm_node*)*elements); - } + if (m_Model->l>0) + { + SV[0] = Malloc(svm_node,elements); + memcpy( SV[0],sv[0],sizeof(svm_node*)*elements); + } svm_node *x_space = SV[0]; int j = 0; - for(int i=0; i<m_Model->l; i++) - { - // SV - SV[i] = &x_space[j]; - const svm_node *p = sv[i]; - svm_node *pCpy = SV[i]; - while(p->index != -1) + for (int i=0; i<m_Model->l; i++) { - pCpy->index = p->index; - pCpy->value = p->value; - p++; - pCpy++; - j++; - } - pCpy->index = -1; + // SV + SV[i] = &x_space[j]; + const svm_node *p = sv[i]; + svm_node *pCpy = SV[i]; + while (p->index != -1) + { + pCpy->index = p->index; + pCpy->value = p->value; + p++; + pCpy++; j++; } + pCpy->index = -1; + j++; + } this->Modified(); } @@ -290,28 +290,28 @@ SVMModel<TInputPixel, TLabel> ::SetAlpha( double ** alpha, int nbOfSupportVector ) { // Erase the old sv_coef - for(int i=0; i<m_Model->nr_class-1; i++) - { - delete[] m_Model->sv_coef[i]; - } + for (int i=0; i<m_Model->nr_class-1; i++) + { + delete[] m_Model->sv_coef[i]; + } delete [] m_Model->sv_coef; this->SetNumberOfSupportVectors(nbOfSupportVector); // copy new sv_coef values m_Model->sv_coef = Malloc(double *,m_Model->nr_class-1); - for(int i=0; i<m_Model->nr_class-1; i++) + for (int i=0; i<m_Model->nr_class-1; i++) m_Model->sv_coef[i] = Malloc(double,m_Model->l); - for(int i=0; i<m_Model->l; i++) - { - // sv_coef - for(int k=0; k<m_Model->nr_class-1; k++) + for (int i=0; i<m_Model->l; i++) { - m_Model->sv_coef[k][i] = alpha[k][i]; - } + // sv_coef + for (int k=0; k<m_Model->nr_class-1; k++) + { + m_Model->sv_coef[k][i] = alpha[k][i]; } - this->Modified(); + } + this->Modified(); } diff --git a/Code/Learning/otbSVMModelEstimator.h b/Code/Learning/otbSVMModelEstimator.h index 14834e65830fd458b602f571ae1e897c21bd4515..776303e8a26654eda1d0474270d353c81acbc12f 100644 --- a/Code/Learning/otbSVMModelEstimator.h +++ b/Code/Learning/otbSVMModelEstimator.h @@ -70,7 +70,7 @@ public: itkNewMacro(Self); - /** Set the number of classes. */ + /** Set the number of classes. */ itkSetMacro(NumberOfClasses, unsigned int); /** Get the number of classes. */ @@ -89,12 +89,24 @@ public: itkGetMacro(Model, SVMModelPointer); /** Set/Get the Measures */ - void SetMeasures( TrainingMeasuresType measures ){ m_Measures = measures; }; - TrainingMeasuresType GetMeasures() { return m_Measures;}; + void SetMeasures( TrainingMeasuresType measures ) + { + m_Measures = measures; + }; + TrainingMeasuresType GetMeasures() + { + return m_Measures; + }; /** Set/Get the Labels */ - void SetLabels( TrainingLabelsType labels ){ m_Labels = labels; }; - TrainingLabelsType GetLabels(){ return m_Labels; }; + void SetLabels( TrainingLabelsType labels ) + { + m_Labels = labels; + }; + TrainingLabelsType GetLabels() + { + return m_Labels; + }; /** Get the number of classes. */ itkGetConstReferenceMacro(Model, SVMModelPointer); @@ -126,8 +138,8 @@ public: this->Modified(); } - /** Get the kernel type */ - int GetKernelType(void) + /** Get the kernel type */ + int GetKernelType(void) { return m_Model->GetKernelType(); } @@ -152,7 +164,7 @@ public: m_Model->SetKernelGamma(gamma); this->Modified(); } - /** Get the gamma parameter for poly/rbf/sigmoid kernels */ + /** Get the gamma parameter for poly/rbf/sigmoid kernels */ double GetKernelGamma(void) { return m_Model->GetKernelGamma(); @@ -180,9 +192,9 @@ public: /** Set the Nu parameter for the training */ double GetNu(void) - { - return m_Model->GetNu(); - } + { + return m_Model->GetNu(); + } /** Set the cache size in MB for the training */ void SetCacheSize(int cSize) @@ -204,7 +216,7 @@ public: this->Modified(); } -/** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ + /** Get the C parameter for the training for C_SVC, EPSILON_SVR and NU_SVR */ double GetC(void) { return m_Model->GetC(); @@ -217,7 +229,7 @@ public: this->Modified(); } -/** Get the tolerance for the stopping criterion for the training*/ + /** Get the tolerance for the stopping criterion for the training*/ double GetEpsilon(void) { return m_Model->GetEpsilon(); @@ -271,7 +283,7 @@ public: /** Get/Set methods for generic kernel functor */ virtual GenericKernelFunctorBase * GetKernelFunctor(void)const { - return m_Model->GetKernelFunctor(); + return m_Model->GetKernelFunctor(); } virtual void SetKernelFunctor(GenericKernelFunctorBase* pGenericKernelFunctor) { diff --git a/Code/Learning/otbSVMModelEstimator.txx b/Code/Learning/otbSVMModelEstimator.txx index 6b6aa18843394b1427d81ad97ba0de0590bf58c3..a062e56db2f6fbe186c9a9aab51230df299b5ff5 100644 --- a/Code/Learning/otbSVMModelEstimator.txx +++ b/Code/Learning/otbSVMModelEstimator.txx @@ -28,21 +28,21 @@ namespace otb template<class InputPixelType, class LabelPixelType> SVMModelEstimator<InputPixelType, LabelPixelType> ::SVMModelEstimator(void): -m_NumberOfClasses( 0 ) + m_NumberOfClasses( 0 ) { // FIXME initialize SVMModel - m_Model = SVMModelType::New(); + m_Model = SVMModelType::New(); - m_Done = 0; - // default values + m_Done = 0; + // default values - m_Model->SetSVMType(C_SVC); + m_Model->SetSVMType(C_SVC); m_Model->SetKernelType(LINEAR); m_Model->SetPolynomialKernelDegree(3); m_Model->SetKernelGamma(0.); // 1/k m_Model->SetKernelCoef0(0); - m_Model->SetKernelFunctor(NULL); + m_Model->SetKernelFunctor(NULL); m_Model->SetNu(0.5); m_Model->SetCacheSize(40); m_Model->SetC(1); @@ -58,7 +58,7 @@ template<class InputPixelType, class LabelPixelType> SVMModelEstimator<InputPixelType, LabelPixelType> ::~SVMModelEstimator(void) { - svm_destroy_param(&m_Model->GetParameters()); + svm_destroy_param(&m_Model->GetParameters()); } /* @@ -91,29 +91,29 @@ void SVMModelEstimator<InputPixelType, LabelPixelType> ::GenerateData( ) { - if(m_NumberOfClasses<2) - { - itkExceptionMacro(<<"Can not do SVM estimation with less than 2 classes"); - } - - if(m_Model->GetSVMType() == ONE_CLASS) - { - if(m_NumberOfClasses>2) + if (m_NumberOfClasses<2) { - itkExceptionMacro(<<"Can not do ONE_CLASS SVM estimation with more than 2 classes"); + itkExceptionMacro(<<"Can not do SVM estimation with less than 2 classes"); } - if(m_Model->GetDoProbabilityEstimates()) + + if (m_Model->GetSVMType() == ONE_CLASS) { - otbMsgDebugMacro(<<"Disabling SVM probability estimates for ONE_CLASS SVM type."); - m_Model->DoProbabilityEstimates(false); - } + if (m_NumberOfClasses>2) + { + itkExceptionMacro(<<"Can not do ONE_CLASS SVM estimation with more than 2 classes"); } - - if(!m_Done) + if (m_Model->GetDoProbabilityEstimates()) { + otbMsgDebugMacro(<<"Disabling SVM probability estimates for ONE_CLASS SVM type."); + m_Model->DoProbabilityEstimates(false); + } + } + + if (!m_Done) + { m_Done = 1; this->EstimateModels(); - } + } }// end Generate data @@ -134,10 +134,10 @@ SVMModelEstimator<InputPixelType, LabelPixelType> const char* error_msg = svm_check_parameter(&m_Model->GetProblem(),&m_Model->GetParameters()); - if(error_msg) - { + if (error_msg) + { throw itk::ExceptionObject(__FILE__, __LINE__,error_msg,ITK_LOCATION); - } + } otbMsgDebugMacro( << "Starting training" ); @@ -166,9 +166,9 @@ SVMModelEstimator< InputPixelType, LabelPixelType > struct svm_problem & prob = m_Model->GetProblem(); struct svm_node *x_space = m_Model->GetXSpace(); - otbMsgDebugMacro( << "x_space " << x_space ); - otbMsgDebugMacro( << "prob = " << &prob ); - otbMsgDebugMacro( << "prob.l = " << prob.l ); + otbMsgDebugMacro( << "x_space " << x_space ); + otbMsgDebugMacro( << "prob = " << &prob ); + otbMsgDebugMacro( << "prob.l = " << prob.l ); long int j=0; long int i=0; @@ -180,41 +180,41 @@ SVMModelEstimator< InputPixelType, LabelPixelType > typename TrainingLabelsType::iterator labelsEnd = m_Labels.end(); - while(measIt!=measEnd && labelsIt!=labelsEnd) - { + while (measIt!=measEnd && labelsIt!=labelsEnd) + { - double label = static_cast<double>(*labelsIt); - prob.x[i] = &x_space[j]; - prob.y[i] = label; + double label = static_cast<double>(*labelsIt); + prob.x[i] = &x_space[j]; + prob.y[i] = label; - typename MeasurementVectorType::iterator compIt = (*measIt).begin(); - typename MeasurementVectorType::iterator compEnd = (*measIt).end(); + typename MeasurementVectorType::iterator compIt = (*measIt).begin(); + typename MeasurementVectorType::iterator compEnd = (*measIt).end(); - int k=0; + int k=0; - while(compIt!=compEnd) - { + while (compIt!=compEnd) + { - x_space[j].index = k+1; - x_space[j].value = (*compIt); - ++j; - ++k; - ++compIt; - } - if(j>=1 && x_space[j-1].index > max_index) - max_index = x_space[j-1].index; - x_space[j++].index = -1; - ++i; + x_space[j].index = k+1; + x_space[j].value = (*compIt); + ++j; + ++k; + ++compIt; + } + if (j>=1 && x_space[j-1].index > max_index) + max_index = x_space[j-1].index; + x_space[j++].index = -1; + ++i; - ++measIt; - ++labelsIt; + ++measIt; + ++labelsIt; - } + } otbMsgDebugMacro( << "Processed " << i << " examples" ); - if(m_Model->GetKernelGamma() == 0 && m_Model->GetParameters().kernel_type != COMPOSED && m_Model->GetParameters().kernel_type != GENERIC) + if (m_Model->GetKernelGamma() == 0 && m_Model->GetParameters().kernel_type != COMPOSED && m_Model->GetParameters().kernel_type != GENERIC) m_Model->SetKernelGamma(1.0/static_cast<double>(max_index)); } @@ -222,9 +222,9 @@ template<class InputPixelType, class LabelPixelType > void SVMModelEstimator<InputPixelType, LabelPixelType> ::SaveModel(const char* model_file_name) - { - m_Model->SaveModel(model_file_name); - } +{ + m_Model->SaveModel(model_file_name); +} }//End namespace OTB diff --git a/Code/Learning/otbSVMPointSetModelEstimator.h b/Code/Learning/otbSVMPointSetModelEstimator.h index 37d6b024d290a1383b12c4b877d87433f96c0a89..3d37cb286c68c3182a995a7aa588a96bd63c9c67 100644 --- a/Code/Learning/otbSVMPointSetModelEstimator.h +++ b/Code/Learning/otbSVMPointSetModelEstimator.h @@ -48,16 +48,16 @@ namespace otb * \ingroup ClassificationFilters */ template <class TInputPointSet, - class TTrainingPointSet> +class TTrainingPointSet> class ITK_EXPORT SVMPointSetModelEstimator: - public SVMModelEstimator<typename TInputPointSet::PixelType::value_type, typename TTrainingPointSet::PixelType> + public SVMModelEstimator<typename TInputPointSet::PixelType::value_type, typename TTrainingPointSet::PixelType> { public: /** Standard class typedefs. */ typedef SVMPointSetModelEstimator Self; typedef SVMModelEstimator<typename TInputPointSet::PixelType::value_type, - typename TTrainingPointSet::PixelType> - Superclass; + typename TTrainingPointSet::PixelType> + Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -69,7 +69,7 @@ public: itkTypeMacro(SVMPointSetModelEstimator, SVMModelEstimator); /** Type definition for the input image. */ - /** Type definitions for the training image. */ + /** Type definitions for the training image. */ typedef typename TInputPointSet::Pointer InputPointSetPointer; /** Type definitions for the training image. */ diff --git a/Code/Learning/otbSVMPointSetModelEstimator.txx b/Code/Learning/otbSVMPointSetModelEstimator.txx index b05a40d98db3934f6a4a052c67f31b418d3226c7..0d5a792dbe93fcc919d2b4330000b2200081a7e7 100644 --- a/Code/Learning/otbSVMPointSetModelEstimator.txx +++ b/Code/Learning/otbSVMPointSetModelEstimator.txx @@ -25,7 +25,7 @@ namespace otb { template<class TInputPointSet, - class TTrainingPointSet> +class TTrainingPointSet> SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> ::SVMPointSetModelEstimator(void): SVMModelEstimator<ITK_TYPENAME TInputPointSet::PixelType::value_type, ITK_TYPENAME TTrainingPointSet::PixelType>() @@ -37,7 +37,7 @@ SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> template<class TInputPointSet, - class TTrainingPointSet> +class TTrainingPointSet> SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> ::~SVMPointSetModelEstimator(void) { @@ -47,7 +47,7 @@ SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> * PrintSelf */ template<class TInputPointSet, - class TTrainingPointSet> +class TTrainingPointSet> void SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> ::PrintSelf( std::ostream& os, itk::Indent indent ) const @@ -71,28 +71,28 @@ SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> template<class TInputPointSet, - class TTrainingPointSet> +class TTrainingPointSet> void SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> ::BuildProblem() { - //Do some error checking + //Do some error checking InputPointSetPointer inputPointSet = this->GetInputPointSet(); TrainingPointSetPointer trainingPointSet = this->GetTrainingPointSet(); // Check if the training and input image dimensions are same - if( (int)(TInputPointSet::PointType::Dimension) != (int)(TTrainingPointSet::PointType::Dimension) ) - { + if ( (int)(TInputPointSet::PointType::Dimension) != (int)(TTrainingPointSet::PointType::Dimension) ) + { throw itk::ExceptionObject(__FILE__, __LINE__,"Training and input pointsets dimensions are not the same.",ITK_LOCATION); - } + } int inputPointSetSize = inputPointSet->GetNumberOfPoints(); int trainingPointSetSize = trainingPointSet->GetNumberOfPoints(); // Check if size of the two inputs are same - if( inputPointSetSize != trainingPointSetSize ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input pointset size is not the same as the training pointset size.",ITK_LOCATION); + if ( inputPointSetSize != trainingPointSetSize ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input pointset size is not the same as the training pointset size.",ITK_LOCATION); // Declaration of the iterators on the input and training images @@ -118,8 +118,8 @@ SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> otbMsgDevMacro( << " Before while " ); unsigned int dataId = 0; - while(inIt!=inEnd && trIt!=trEnd) - { + while (inIt!=inEnd && trIt!=trEnd) + { // If label != 0 @@ -127,28 +127,28 @@ SVMPointSetModelEstimator<TInputPointSet, TTrainingPointSet> trainingPointSet->GetPointData( dataId, & label ); this->m_Labels.push_back(label); - otbMsgDevMacro( << " Label " << label ); + otbMsgDevMacro( << " Label " << label ); - typename TInputPointSet::PixelType value; - inputPointSet->GetPointData( dataId, & value ); + typename TInputPointSet::PixelType value; + inputPointSet->GetPointData( dataId, & value ); - typename Superclass::MeasurementVectorType v; + typename Superclass::MeasurementVectorType v; - typename TInputPointSet::PixelType::iterator pIt = value.begin(); - typename TInputPointSet::PixelType::iterator pEnd = value.end(); + typename TInputPointSet::PixelType::iterator pIt = value.begin(); + typename TInputPointSet::PixelType::iterator pEnd = value.end(); - while(pIt!=pEnd) - { - v.push_back(*pIt); - ++pIt; - } + while (pIt!=pEnd) + { + v.push_back(*pIt); + ++pIt; + } - this->m_Measures.push_back(v); + this->m_Measures.push_back(v); ++inIt; ++trIt; ++dataId; - } + } otbMsgDevMacro( << " Before prepare data " ); this->PrepareData(); diff --git a/Code/Learning/otbSVMSampleListModelEstimator.h b/Code/Learning/otbSVMSampleListModelEstimator.h index 3943085424fd42dacd54fd93db013b447b8641cd..11c51cd1851dbd699bd5a7b234a6baa2041c5bc8 100644 --- a/Code/Learning/otbSVMSampleListModelEstimator.h +++ b/Code/Learning/otbSVMSampleListModelEstimator.h @@ -48,16 +48,16 @@ namespace otb * \ingroup ClassificationFilters */ template <class TInputSampleList, - class TTrainingSampleList> +class TTrainingSampleList> class ITK_EXPORT SVMSampleListModelEstimator: - public SVMModelEstimator<typename TInputSampleList::MeasurementType, typename TTrainingSampleList::MeasurementType> + public SVMModelEstimator<typename TInputSampleList::MeasurementType, typename TTrainingSampleList::MeasurementType> { public: /** Standard class typedefs. */ typedef SVMSampleListModelEstimator Self; typedef SVMModelEstimator<typename TInputSampleList::MeasurementType, - typename TTrainingSampleList::MeasurementType> - Superclass; + typename TTrainingSampleList::MeasurementType> + Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -69,7 +69,7 @@ public: itkTypeMacro(SVMSampleListModelEstimator, SVMModelEstimator); /** Type definition for the input image. */ - /** Type definitions for the training image. */ + /** Type definitions for the training image. */ typedef typename TInputSampleList::Pointer InputSampleListPointer; /** Type definitions for the training image. */ diff --git a/Code/Learning/otbSVMSampleListModelEstimator.txx b/Code/Learning/otbSVMSampleListModelEstimator.txx index 86b84bb06b4134c3a9617998e83e452f206f75e9..93a851b7527e2f475f0948fcfba6adeb153b64b2 100644 --- a/Code/Learning/otbSVMSampleListModelEstimator.txx +++ b/Code/Learning/otbSVMSampleListModelEstimator.txx @@ -26,10 +26,10 @@ namespace otb { template<class TInputSampleList, - class TTrainingSampleList> +class TTrainingSampleList> SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> ::SVMSampleListModelEstimator(void): SVMModelEstimator<ITK_TYPENAME TInputSampleList::MeasurementType, - ITK_TYPENAME TTrainingSampleList::MeasurementType>() + ITK_TYPENAME TTrainingSampleList::MeasurementType>() { @@ -38,7 +38,7 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> template<class TInputSampleList, - class TTrainingSampleList> +class TTrainingSampleList> SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> ::~SVMSampleListModelEstimator(void) { @@ -48,7 +48,7 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> * PrintSelf */ template<class TInputSampleList, - class TTrainingSampleList> +class TTrainingSampleList> void SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> ::PrintSelf( std::ostream& os, itk::Indent indent ) const @@ -72,13 +72,13 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> template<class TInputSampleList, - class TTrainingSampleList> +class TTrainingSampleList> void SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> ::BuildProblem() { - //Do some error checking + //Do some error checking InputSampleListPointer inputSampleList = this->GetInputSampleList(); TrainingSampleListPointer trainingSampleList = this->GetTrainingSampleList(); @@ -88,7 +88,7 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> int trainingSampleListSize = trainingSampleList->Size(); // Check if size of the two inputs are same - if( inputSampleListSize != trainingSampleListSize ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input pointset size is not the same as the training pointset size.",ITK_LOCATION); + if ( inputSampleListSize != trainingSampleListSize ) throw itk::ExceptionObject(__FILE__, __LINE__,"Input pointset size is not the same as the training pointset size.",ITK_LOCATION); // Declaration of the iterators on the input and training images @@ -111,10 +111,10 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> otbMsgDebugMacro( << " Training nb points " << trainingSampleListSize ); - // otbMsgDebugMacro( << " Before while " ); +// otbMsgDebugMacro( << " Before while " ); - while(inIt!=inEnd && trIt!=trEnd) - { + while (inIt!=inEnd && trIt!=trEnd) + { // If label != 0 @@ -133,17 +133,17 @@ SVMSampleListModelEstimator<TInputSampleList, TTrainingSampleList> typename TInputSampleList::MeasurementVectorType::ConstIterator pIt = value.Begin(); typename TInputSampleList::MeasurementVectorType::ConstIterator pEnd = value.End(); - while(pIt!=pEnd) - { + while (pIt!=pEnd) + { v.push_back(*pIt); ++pIt; - } + } this->m_Measures.push_back(v); ++inIt; ++trIt; - } + } // otbMsgDebugMacro( << " Before prepare data " ); this->PrepareData(); diff --git a/Code/Learning/otbSpectralAngleKernelFunctor.cxx b/Code/Learning/otbSpectralAngleKernelFunctor.cxx index 5d6fef4a1cf275ddd2a2b521d931726d1c3a0c1d..01eccdf66ee9e0eb119489aee15473a58f64bcc9 100644 --- a/Code/Learning/otbSpectralAngleKernelFunctor.cxx +++ b/Code/Learning/otbSpectralAngleKernelFunctor.cxx @@ -22,7 +22,8 @@ #include "otbSpectralAngleKernelFunctor.h" -namespace otb { +namespace otb +{ SpectralAngleKernelFunctor ::SpectralAngleKernelFunctor () @@ -43,7 +44,7 @@ SpectralAngleKernelFunctor double SpectralAngleKernelFunctor ::operator()( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const + const svm_parameter & param ) const { double mq = m_Coef + SAM( x, y ); diff --git a/Code/Learning/otbSpectralAngleKernelFunctor.h b/Code/Learning/otbSpectralAngleKernelFunctor.h index 1c6ef22c7d4fb62117ad81fa75897389e3cebcee..e997d1060a6e57081e1ad681bffef660ad394e47 100644 --- a/Code/Learning/otbSpectralAngleKernelFunctor.h +++ b/Code/Learning/otbSpectralAngleKernelFunctor.h @@ -25,32 +25,32 @@ namespace otb { - /** \class SpectralAngleKernelFunctor - * \brief Spectral Angle Kernel - * - * Performs an inverse multiquadric kernel evaluation that suits - * spectral data. - * - * It is of kind: - * - * \f$ frac{1}{\sqrt{ c_0 + \cos\textrm{SAM(x,y)} }} \f$ where \f$ \textrm{SAM(x,y)} \f$ is - * Spectral Angle Measure: - * \f$ \textrm{SAM}(x,y) = \acos\left( \frac{x \cdot y}{\|x\| \|y\|} \right) \f$. - * - * The only parameter \f$ c_0 \f$ is to be fixed by the \code SetValue \endcode - * interface with keyword Coef (def 2.0). - * - */ +/** \class SpectralAngleKernelFunctor + * \brief Spectral Angle Kernel + * + * Performs an inverse multiquadric kernel evaluation that suits + * spectral data. + * + * It is of kind: + * + * \f$ frac{1}{\sqrt{ c_0 + \cos\textrm{SAM(x,y)} }} \f$ where \f$ \textrm{SAM(x,y)} \f$ is + * Spectral Angle Measure: + * \f$ \textrm{SAM}(x,y) = \acos\left( \frac{x \cdot y}{\|x\| \|y\|} \right) \f$. + * + * The only parameter \f$ c_0 \f$ is to be fixed by the \code SetValue \endcode + * interface with keyword Coef (def 2.0). + * + */ class SpectralAngleKernelFunctor - : public GenericKernelFunctorBase + : public GenericKernelFunctorBase { public: double operator() ( const svm_node * x, const svm_node * y, - const svm_parameter & param ) const; + const svm_parameter & param ) const; SpectralAngleKernelFunctor (); virtual ~SpectralAngleKernelFunctor () { } diff --git a/Code/Markov/otbMRFEnergy.h b/Code/Markov/otbMRFEnergy.h index 1b2140f889067455bbe4c9a01df9e922b24190ce..6ecc15680252bacc23fdaac9b99ae3410eca70a6 100644 --- a/Code/Markov/otbMRFEnergy.h +++ b/Code/Markov/otbMRFEnergy.h @@ -24,207 +24,212 @@ namespace otb { - /** - * \class MRFEnergy - * \brief This is the base class for energy function used in the MRF framework - * - * Derived class must reimplement the GetSingleValue() method. - * - * This class is meant to be used in the MRF framework with the otb::MarkovRandomFieldFilter - * - * \ingroup Markov - */ +/** + * \class MRFEnergy + * \brief This is the base class for energy function used in the MRF framework + * + * Derived class must reimplement the GetSingleValue() method. + * + * This class is meant to be used in the MRF framework with the otb::MarkovRandomFieldFilter + * + * \ingroup Markov + */ template< class TInput1, class TInput2 > class ITK_EXPORT MRFEnergy : public itk::Object - { - public: - typedef MRFEnergy Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public: + typedef MRFEnergy Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef TInput1 InputImageType; - typedef TInput2 LabelledImageType; - typedef typename InputImageType::PixelType InputImagePixelType; - typedef typename LabelledImageType::PixelType LabelledImagePixelType; + typedef TInput1 InputImageType; + typedef TInput2 LabelledImageType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename LabelledImageType::PixelType LabelledImagePixelType; - typedef itk::ConstNeighborhoodIterator< LabelledImageType > LabelledNeighborhoodIterator; - typedef itk::ConstNeighborhoodIterator< InputImageType > InputNeighborhoodIterator; + typedef itk::ConstNeighborhoodIterator< LabelledImageType > LabelledNeighborhoodIterator; + typedef itk::ConstNeighborhoodIterator< InputImageType > InputNeighborhoodIterator; - typedef itk::Array< double > ParametersType; + typedef itk::Array< double > ParametersType; - itkNewMacro(Self); + itkNewMacro(Self); - itkTypeMacro(MRFEnergy,itk::Object); + itkTypeMacro(MRFEnergy,itk::Object); - itkSetMacro(NumberOfParameters, unsigned int); - itkGetConstMacro(NumberOfParameters, unsigned int); + itkSetMacro(NumberOfParameters, unsigned int); + itkGetConstMacro(NumberOfParameters, unsigned int); - // Get the parameters - const ParametersType& GetParameters( void ) const - { - return this->m_Parameters; - } + // Get the parameters + const ParametersType& GetParameters( void ) const + { + return this->m_Parameters; + } - void SetParameters( const ParametersType & parameters ) - { - if( parameters.Size() != m_NumberOfParameters ) + void SetParameters( const ParametersType & parameters ) + { + if ( parameters.Size() != m_NumberOfParameters ) { itkExceptionMacro(<<"Invalid number of parameters"); } - m_Parameters = parameters; - this->Modified(); - } + m_Parameters = parameters; + this->Modified(); + } - virtual double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes."); - } + virtual double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) + { + itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes."); + } - double GetValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - return GetSingleValue(value1, value2); - } + double GetValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) + { + return GetSingleValue(value1, value2); + } - double GetValue(const LabelledNeighborhoodIterator & it, const LabelledImagePixelType & value2) - { - double result = 0.0; - unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); - InputImagePixelType value1; //TODO put also the other neighborhood ? - bool isInside=false; - unsigned int insideNeighbors = 0; - for(unsigned long pos = 0; pos< it.Size(); ++pos) + double GetValue(const LabelledNeighborhoodIterator & it, const LabelledImagePixelType & value2) + { + double result = 0.0; + unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); + InputImagePixelType value1; //TODO put also the other neighborhood ? + bool isInside=false; + unsigned int insideNeighbors = 0; + for (unsigned long pos = 0; pos< it.Size(); ++pos) { if (pos != centerIndex)//TODO put outside loop for faster access ? - { - value1 = it.GetPixel(pos, isInside); - if (isInside){ - result += GetSingleValue(value1, value2); - insideNeighbors++; - } - } - } - return result/insideNeighbors; + { + value1 = it.GetPixel(pos, isInside); + if (isInside) + { + result += GetSingleValue(value1, value2); + insideNeighbors++; + } } + } + return result/insideNeighbors; + } - double GetValue(const InputNeighborhoodIterator & it, const LabelledImagePixelType & value2) - { - double result = 0.0; - unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); - InputImagePixelType value1; //TODO put also the other neighborhood ? - bool isInside=false; - unsigned int insideNeighbors = 0; - for(unsigned long pos = 0; pos< it.Size(); ++pos) + double GetValue(const InputNeighborhoodIterator & it, const LabelledImagePixelType & value2) + { + double result = 0.0; + unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); + InputImagePixelType value1; //TODO put also the other neighborhood ? + bool isInside=false; + unsigned int insideNeighbors = 0; + for (unsigned long pos = 0; pos< it.Size(); ++pos) { if (pos != centerIndex)//TODO put outside loop for faster access ? - { - value1 = it.GetPixel(pos, isInside); - if (isInside) { - result += GetSingleValue(value1, value2); - insideNeighbors++; + value1 = it.GetPixel(pos, isInside); + if (isInside) + { + result += GetSingleValue(value1, value2); + insideNeighbors++; + } } - } } - return result/insideNeighbors; - } + return result/insideNeighbors; + } - protected: - // The constructor and destructor. - MRFEnergy() {m_NumberOfParameters = 1;}; - virtual ~MRFEnergy() {}; - unsigned int m_NumberOfParameters; - ParametersType m_Parameters; +protected: + // The constructor and destructor. + MRFEnergy() + { + m_NumberOfParameters = 1; }; + virtual ~MRFEnergy() {}; + unsigned int m_NumberOfParameters; + ParametersType m_Parameters; +}; template< class TInput2> class ITK_EXPORT MRFEnergy<TInput2,TInput2> : public itk::Object - { - public: - typedef MRFEnergy Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public: + typedef MRFEnergy Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef TInput2 LabelledImageType; - typedef typename LabelledImageType::PixelType LabelledImagePixelType; + typedef TInput2 LabelledImageType; + typedef typename LabelledImageType::PixelType LabelledImagePixelType; - typedef itk::ConstNeighborhoodIterator< LabelledImageType > LabelledNeighborhoodIterator; - typedef itk::Array< double > ParametersType; + typedef itk::ConstNeighborhoodIterator< LabelledImageType > LabelledNeighborhoodIterator; + typedef itk::Array< double > ParametersType; - itkNewMacro(Self); + itkNewMacro(Self); - itkTypeMacro(MRFEnergy,itk::Object); + itkTypeMacro(MRFEnergy,itk::Object); - itkSetMacro(NumberOfParameters, unsigned int); - itkGetConstMacro(NumberOfParameters, unsigned int); + itkSetMacro(NumberOfParameters, unsigned int); + itkGetConstMacro(NumberOfParameters, unsigned int); - // Get the parameters - const ParametersType& GetParameters( void ) const - { - return this->m_Parameters; - } + // Get the parameters + const ParametersType& GetParameters( void ) const + { + return this->m_Parameters; + } - void SetParameters( const ParametersType & parameters ) - { - if( parameters.Size() != m_NumberOfParameters ) + void SetParameters( const ParametersType & parameters ) + { + if ( parameters.Size() != m_NumberOfParameters ) { itkExceptionMacro(<<"Invalid number of parameters"); } - m_Parameters = parameters; - this->Modified(); - } + m_Parameters = parameters; + this->Modified(); + } - virtual double GetSingleValue(const LabelledImagePixelType & value1, const LabelledImagePixelType & value2) - { - itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes."); - } + virtual double GetSingleValue(const LabelledImagePixelType & value1, const LabelledImagePixelType & value2) + { + itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes."); + } - double GetValue(const LabelledImagePixelType & value1, const LabelledImagePixelType & value2) - { - return GetSingleValue(value1, value2); - } + double GetValue(const LabelledImagePixelType & value1, const LabelledImagePixelType & value2) + { + return GetSingleValue(value1, value2); + } - double GetValue(const LabelledNeighborhoodIterator & it, const LabelledImagePixelType & value2) - { - double result = 0.0; - unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); - LabelledImagePixelType value1; //TODO put also the other neighborhood ? - bool isInside=false; - unsigned int insideNeighbors = 0; - for(unsigned long pos = 0; pos< it.Size(); ++pos) + double GetValue(const LabelledNeighborhoodIterator & it, const LabelledImagePixelType & value2) + { + double result = 0.0; + unsigned int centerIndex = it.GetCenterNeighborhoodIndex(); + LabelledImagePixelType value1; //TODO put also the other neighborhood ? + bool isInside=false; + unsigned int insideNeighbors = 0; + for (unsigned long pos = 0; pos< it.Size(); ++pos) { if (pos != centerIndex)//TODO put outside loop for faster access ? - { - value1 = it.GetPixel(pos, isInside); - if (isInside){ - result += GetSingleValue(value1, value2); - insideNeighbors++; - } - } - } - return result/insideNeighbors; + { + value1 = it.GetPixel(pos, isInside); + if (isInside) + { + result += GetSingleValue(value1, value2); + insideNeighbors++; + } } + } + return result/insideNeighbors; + } - protected: - // The constructor and destructor. - MRFEnergy() - { - m_NumberOfParameters = 1; - m_Parameters=0; - }; - virtual ~MRFEnergy() {}; - unsigned int m_NumberOfParameters; - ParametersType m_Parameters; +protected: + // The constructor and destructor. + MRFEnergy() + { + m_NumberOfParameters = 1; + m_Parameters=0; }; + virtual ~MRFEnergy() {}; + unsigned int m_NumberOfParameters; + ParametersType m_Parameters; +}; } #endif diff --git a/Code/Markov/otbMRFEnergyEdgeFidelity.h b/Code/Markov/otbMRFEnergyEdgeFidelity.h index 810924c5a217b7b0eb584de0c8c06f75840991e7..9702dccd081da21578f2c3aded1572c10013bbaa 100644 --- a/Code/Markov/otbMRFEnergyEdgeFidelity.h +++ b/Code/Markov/otbMRFEnergyEdgeFidelity.h @@ -44,35 +44,35 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFEnergyEdgeFidelity : public MRFEnergy< TInput1, TInput2> - { - public: - typedef MRFEnergyEdgeFidelity Self; - typedef MRFEnergy< TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public: + typedef MRFEnergyEdgeFidelity Self; + typedef MRFEnergy< TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::ConstNeighborhoodIterator< TInput1 > NeighborhoodIterator; - typedef typename TInput1::PixelType InputImagePixelType; - typedef typename TInput2::PixelType LabelledImagePixelType; + typedef itk::ConstNeighborhoodIterator< TInput1 > NeighborhoodIterator; + typedef typename TInput1::PixelType InputImagePixelType; + typedef typename TInput2::PixelType LabelledImagePixelType; - itkNewMacro(Self); + itkNewMacro(Self); - itkTypeMacro(MRFEnergyEdgeFidelity, MRFEnergy); + itkTypeMacro(MRFEnergyEdgeFidelity, MRFEnergy); - double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - double val1 = static_cast<double>(value1); - double val2 = static_cast<double>(value2); + double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) + { + double val1 = static_cast<double>(value1); + double val2 = static_cast<double>(value2); - return M_SQUARE((val1 - val2))/(1+M_SQUARE(val1 - val2)); - } + return M_SQUARE((val1 - val2))/(1+M_SQUARE(val1 - val2)); + } - protected: - // The constructor and destructor. - MRFEnergyEdgeFidelity() {}; - virtual ~MRFEnergyEdgeFidelity() {}; - }; +protected: + // The constructor and destructor. + MRFEnergyEdgeFidelity() {}; + virtual ~MRFEnergyEdgeFidelity() {}; +}; } #endif diff --git a/Code/Markov/otbMRFEnergyGaussian.h b/Code/Markov/otbMRFEnergyGaussian.h index 77ca049bce0ea8313190fb1b161c61c625fa2c2f..6cf5734d6404fcac65ce007dc08df06694632f56 100644 --- a/Code/Markov/otbMRFEnergyGaussian.h +++ b/Code/Markov/otbMRFEnergyGaussian.h @@ -47,39 +47,40 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFEnergyGaussian:public MRFEnergy< TInput1, TInput2> - { - public: - typedef MRFEnergyGaussian Self; - typedef MRFEnergy< TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef TInput1 InputImageType; - typedef TInput2 LabelledImageType; - typedef typename InputImageType::PixelType InputImagePixelType; - typedef typename LabelledImageType::PixelType LabelledImagePixelType; +{ +public: + typedef MRFEnergyGaussian Self; + typedef MRFEnergy< TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::Array< double > ParametersType; + typedef TInput1 InputImageType; + typedef TInput2 LabelledImageType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename LabelledImageType::PixelType LabelledImagePixelType; - itkTypeMacro(MRFEnergyGaussian, MRFEnergy); + typedef itk::Array< double > ParametersType; - itkNewMacro(Self); + itkTypeMacro(MRFEnergyGaussian, MRFEnergy); - double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - return M_SQUARE((static_cast<double>(value1)) - - (static_cast<double>(value2)) ); - } + itkNewMacro(Self); - protected: - // The constructor and destructor. - MRFEnergyGaussian() { - this->m_NumberOfParameters = 0; - this->m_Parameters.SetSize(this->m_NumberOfParameters); - }; - virtual ~MRFEnergyGaussian() {}; + double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) + { + return M_SQUARE((static_cast<double>(value1)) + - (static_cast<double>(value2)) ); + } +protected: + // The constructor and destructor. + MRFEnergyGaussian() + { + this->m_NumberOfParameters = 0; + this->m_Parameters.SetSize(this->m_NumberOfParameters); }; + virtual ~MRFEnergyGaussian() {}; + +}; } #endif diff --git a/Code/Markov/otbMRFEnergyGaussianClassification.h b/Code/Markov/otbMRFEnergyGaussianClassification.h index 2b39fbda53702120300667a953f120c8fc33912f..0be7871e6143e8fab6c3cbbe5ebfa6d1fa054185 100644 --- a/Code/Markov/otbMRFEnergyGaussianClassification.h +++ b/Code/Markov/otbMRFEnergyGaussianClassification.h @@ -10,8 +10,8 @@ See OTBCopyright.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. =========================================================================*/ @@ -36,62 +36,62 @@ namespace otb * - \f$ x_s \f$ the label on site s * - \f$ y_s \f$ the value on the reference image * - \f$ \mu_{x_s} \f$ and \f$ \sigma^2_{x_s} \f$ the mean and variance of label \f$ x_s \f$ - * + * * This class is meant to be used in the MRF framework with the otb::MarkovRandomFieldFilter * * \ingroup Markov */ - -template< class TInput1, class TInput2> + +template< class TInput1, class TInput2> class ITK_EXPORT MRFEnergyGaussianClassification:public MRFEnergy< TInput1, TInput2> +{ +public: + typedef MRFEnergyGaussianClassification Self; + typedef MRFEnergy< TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef TInput1 InputImageType; + typedef TInput2 LabelledImageType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename LabelledImageType::PixelType LabelledImagePixelType; + typedef itk::Array < double > ParametersType; + + itkNewMacro(Self); + + itkTypeMacro(MRFEnergyGaussianClassification, MRFEnergy); + + void SetNumberOfParameters(const unsigned int nParameters) + { + Superclass::SetNumberOfParameters(nParameters); + this->m_Parameters.SetSize(nParameters); + this->Modified(); + } + + + double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) { - public: - typedef MRFEnergyGaussianClassification Self; - typedef MRFEnergy< TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef TInput1 InputImageType; - typedef TInput2 LabelledImageType; - typedef typename InputImageType::PixelType InputImagePixelType; - typedef typename LabelledImageType::PixelType LabelledImagePixelType; - typedef itk::Array < double > ParametersType; - - itkNewMacro(Self); - - itkTypeMacro(MRFEnergyGaussianClassification, MRFEnergy); - - void SetNumberOfParameters(const unsigned int nParameters) - { - Superclass::SetNumberOfParameters(nParameters); - this->m_Parameters.SetSize(nParameters); - this->Modified(); - } - - - double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - if ((unsigned int)value2 >= this->GetNumberOfParameters()/2) + if ((unsigned int)value2 >= this->GetNumberOfParameters()/2) { - itkExceptionMacro(<<"Number of parameters does not correspond to number of classes" ); + itkExceptionMacro(<<"Number of parameters does not correspond to number of classes" ); } - double val1 = static_cast<double>(value1); - - double result = M_SQUARE(val1-this->m_Parameters[2*static_cast<int>(value2)]) - / (2*M_SQUARE(this->m_Parameters[2*static_cast<int>(value2)+1])) - + vcl_log(vcl_sqrt(2*M_PI)*this->m_Parameters[2*static_cast<int>(value2)+1]); - - return static_cast<double>( result ); - } - - - - protected: - // The constructor and destructor. - MRFEnergyGaussianClassification() {}; - virtual ~MRFEnergyGaussianClassification() {}; - - }; + double val1 = static_cast<double>(value1); + + double result = M_SQUARE(val1-this->m_Parameters[2*static_cast<int>(value2)]) + / (2*M_SQUARE(this->m_Parameters[2*static_cast<int>(value2)+1])) + + vcl_log(vcl_sqrt(2*M_PI)*this->m_Parameters[2*static_cast<int>(value2)+1]); + + return static_cast<double>( result ); + } + + + +protected: + // The constructor and destructor. + MRFEnergyGaussianClassification() {}; + virtual ~MRFEnergyGaussianClassification() {}; + +}; } #endif diff --git a/Code/Markov/otbMRFEnergyPotts.h b/Code/Markov/otbMRFEnergyPotts.h index 221f3ee4b404a562c7949c527fef3f3a2d0dadcf..33dc11de5369bf102379d6f14e3caa33bb517441 100644 --- a/Code/Markov/otbMRFEnergyPotts.h +++ b/Code/Markov/otbMRFEnergyPotts.h @@ -43,46 +43,47 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFEnergyPotts:public MRFEnergy< TInput1, TInput2> - { - public: - typedef MRFEnergyPotts Self; - typedef MRFEnergy< TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef TInput1 InputImageType; - typedef TInput2 LabelledImageType; - typedef typename InputImageType::PixelType InputImagePixelType; - typedef typename LabelledImageType::PixelType LabelledImagePixelType; - - typedef itk::Array< double > ParametersType; - - itkTypeMacro(MRFEnergyPotts, MRFEnergy); - - itkNewMacro(Self); - - double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) - { - if (value1 != value2) - { - return this->m_Parameters[0]; - } - else - { - return -this->m_Parameters[0]; - } - } - - protected: - // The constructor and destructor. - MRFEnergyPotts() { - this->m_NumberOfParameters = 1; - this->m_Parameters.SetSize(this->m_NumberOfParameters); - this->m_Parameters[0]=1.0; - }; - virtual ~MRFEnergyPotts() {}; +{ +public: + typedef MRFEnergyPotts Self; + typedef MRFEnergy< TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef TInput1 InputImageType; + typedef TInput2 LabelledImageType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename LabelledImageType::PixelType LabelledImagePixelType; + + typedef itk::Array< double > ParametersType; + + itkTypeMacro(MRFEnergyPotts, MRFEnergy); + itkNewMacro(Self); + + double GetSingleValue(const InputImagePixelType & value1, const LabelledImagePixelType & value2) + { + if (value1 != value2) + { + return this->m_Parameters[0]; + } + else + { + return -this->m_Parameters[0]; + } + } + +protected: + // The constructor and destructor. + MRFEnergyPotts() + { + this->m_NumberOfParameters = 1; + this->m_Parameters.SetSize(this->m_NumberOfParameters); + this->m_Parameters[0]=1.0; }; + virtual ~MRFEnergyPotts() {}; + +}; } #endif diff --git a/Code/Markov/otbMRFOptimizer.h b/Code/Markov/otbMRFOptimizer.h index cbbba52a5d5181f338e1995dd10b330b3cec2989..1b75bfc5dd892147c9577504ff8de5279ec3c13e 100644 --- a/Code/Markov/otbMRFOptimizer.h +++ b/Code/Markov/otbMRFOptimizer.h @@ -36,46 +36,46 @@ namespace otb */ class ITK_EXPORT MRFOptimizer : public itk::Object - { - public: - typedef MRFOptimizer Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::Array< double > ParametersType; +{ +public: + typedef MRFOptimizer Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef itk::Array< double > ParametersType; - itkTypeMacro(MRFOptimizer, itk::Object); + itkTypeMacro(MRFOptimizer, itk::Object); - itkGetConstMacro(NumberOfParameters, unsigned int); + itkGetConstMacro(NumberOfParameters, unsigned int); - // Get the parameters - const ParametersType& GetParameters( void ) const - { - return this->m_Parameters; - } - - virtual void SetParameters( const ParametersType & parameters ) - { - if( parameters.GetSize() != m_NumberOfParameters ) + // Get the parameters + const ParametersType& GetParameters( void ) const { - itkExceptionMacro(<<"Invalid number of parameters ("<<parameters.GetSize()<<" , "<<m_NumberOfParameters<<")"); + return this->m_Parameters; } - m_Parameters = parameters; - this->Modified(); - } - virtual bool Compute(double deltaEnergy) = 0; - - protected: - MRFOptimizer() + virtual void SetParameters( const ParametersType & parameters ) + { + if ( parameters.GetSize() != m_NumberOfParameters ) { - m_Parameters=1; + itkExceptionMacro(<<"Invalid number of parameters ("<<parameters.GetSize()<<" , "<<m_NumberOfParameters<<")"); } - virtual ~MRFOptimizer() {} - unsigned int m_NumberOfParameters; - ParametersType m_Parameters; + m_Parameters = parameters; + this->Modified(); + } + + virtual bool Compute(double deltaEnergy) = 0; + +protected: + MRFOptimizer() + { + m_Parameters=1; + } + virtual ~MRFOptimizer() {} + unsigned int m_NumberOfParameters; + ParametersType m_Parameters; - }; +}; } #endif diff --git a/Code/Markov/otbMRFOptimizerICM.h b/Code/Markov/otbMRFOptimizerICM.h index 15e94c09cd9b88d4f708d350cefd95a21561d384..edad099c69139747403b10515dede2f293af7c6c 100644 --- a/Code/Markov/otbMRFOptimizerICM.h +++ b/Code/Markov/otbMRFOptimizerICM.h @@ -36,7 +36,7 @@ namespace otb */ class ITK_EXPORT MRFOptimizerICM : public MRFOptimizer { - public: +public: typedef MRFOptimizerICM Self; typedef MRFOptimizer Superclass; @@ -49,19 +49,19 @@ class ITK_EXPORT MRFOptimizerICM : public MRFOptimizer inline bool Compute(double deltaEnergy) - { - if (deltaEnergy < 0) - { - return true; - } - else { - return false; - } + if (deltaEnergy < 0) + { + return true; + } + else + { + return false; } + } - protected: +protected: MRFOptimizerICM() {} virtual ~MRFOptimizerICM() {} diff --git a/Code/Markov/otbMRFOptimizerMetropolis.h b/Code/Markov/otbMRFOptimizerMetropolis.h index b0cbed84100608a9cd744f7887071b977c22eac7..1b91b3d73bcc1e0122d3a5d1f0f7c29a6cb0666c 100644 --- a/Code/Markov/otbMRFOptimizerMetropolis.h +++ b/Code/Markov/otbMRFOptimizerMetropolis.h @@ -25,85 +25,92 @@ namespace otb { - /** - * \class MRFOptimizerMetropolis - * \brief This is the optimizer class implementing the Metropolis algorithm - * - * This is one optimizer to be used in the MRF framework. This optimizer - * follows the metropolis algorithm to accept of reject the value proposed by the sampler. - * - * The MRFOptimizerMetropolis has one parameter corresponding to the temperature T used - * to accept or reject proposed values. The proposed value is accepted with a probability: - * - * \f[ e^{\frac{-\Delta E}{T}} \f] - * - * - * This class is meant to be used in the MRF framework with the otb::MarkovRandomFieldFilter - * - * \ingroup Markov - */ +/** + * \class MRFOptimizerMetropolis + * \brief This is the optimizer class implementing the Metropolis algorithm + * + * This is one optimizer to be used in the MRF framework. This optimizer + * follows the metropolis algorithm to accept of reject the value proposed by the sampler. + * + * The MRFOptimizerMetropolis has one parameter corresponding to the temperature T used + * to accept or reject proposed values. The proposed value is accepted with a probability: + * + * \f[ e^{\frac{-\Delta E}{T}} \f] + * + * + * This class is meant to be used in the MRF framework with the otb::MarkovRandomFieldFilter + * + * \ingroup Markov + */ class ITK_EXPORT MRFOptimizerMetropolis : public MRFOptimizer - { - public: +{ +public: - typedef MRFOptimizerMetropolis Self; - typedef MRFOptimizer Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef Superclass::ParametersType ParametersType; + typedef MRFOptimizerMetropolis Self; + typedef MRFOptimizer Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef Superclass::ParametersType ParametersType; - typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; - itkNewMacro(Self); + itkNewMacro(Self); - itkTypeMacro(MRFOptimizerMetropolis,MRFOptimizer); + itkTypeMacro(MRFOptimizerMetropolis,MRFOptimizer); - /** Set parameter to a one array filled with paramVal.*/ - void SetSingleParameter( double parameterVal ) - { - this->m_Parameters.SetSize(1); - this->m_Parameters.Fill(parameterVal); - this->Modified(); - } + /** Set parameter to a one array filled with paramVal.*/ + void SetSingleParameter( double parameterVal ) + { + this->m_Parameters.SetSize(1); + this->m_Parameters.Fill(parameterVal); + this->Modified(); + } - inline bool Compute(double deltaEnergy) - { - if (deltaEnergy < 0) + inline bool Compute(double deltaEnergy) + { + if (deltaEnergy < 0) { return true; } - if (deltaEnergy == 0) + if (deltaEnergy == 0) { return false; } - else - { - double proba = vcl_exp(-(deltaEnergy)/this->m_Parameters[0]); - if ( (m_Generator->GetIntegerVariate() % 10000) < proba*10000) + else + { + double proba = vcl_exp(-(deltaEnergy)/this->m_Parameters[0]); + if ( (m_Generator->GetIntegerVariate() % 10000) < proba*10000) { return true; } - } - return false; - } - - /** Methods to cancel random effects.*/ - void InitializeSeed(int seed){ m_Generator->SetSeed(seed); } - void InitializeSeed(){ m_Generator->SetSeed(); } - - protected: - MRFOptimizerMetropolis() { - this->m_NumberOfParameters = 1; - this->m_Parameters.SetSize(1); - this->m_Parameters[0]=1.0; - m_Generator = RandomGeneratorType::New(); - m_Generator->SetSeed(); } - virtual ~MRFOptimizerMetropolis() {} - RandomGeneratorType::Pointer m_Generator; - }; + return false; + } + + /** Methods to cancel random effects.*/ + void InitializeSeed(int seed) + { + m_Generator->SetSeed(seed); + } + void InitializeSeed() + { + m_Generator->SetSeed(); + } + +protected: + MRFOptimizerMetropolis() + { + this->m_NumberOfParameters = 1; + this->m_Parameters.SetSize(1); + this->m_Parameters[0]=1.0; + m_Generator = RandomGeneratorType::New(); + m_Generator->SetSeed(); + } + virtual ~MRFOptimizerMetropolis() {} + RandomGeneratorType::Pointer m_Generator; +}; } diff --git a/Code/Markov/otbMRFSampler.h b/Code/Markov/otbMRFSampler.h index 6ae321e697a54b7ac8e0449f4420b58545603a34..be46d94106ec67588422f7ae740b371d303a761a 100644 --- a/Code/Markov/otbMRFSampler.h +++ b/Code/Markov/otbMRFSampler.h @@ -37,77 +37,77 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFSampler : public itk::Object - { - public: - - typedef MRFSampler Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public: - typedef itk::ConstNeighborhoodIterator< TInput1 > InputImageNeighborhoodIterator; - typedef typename TInput1::PixelType InputImagePixelType; + typedef MRFSampler Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::NeighborhoodIterator< TInput2 > LabelledImageNeighborhoodIterator; - typedef typename TInput2::PixelType LabelledImagePixelType; + typedef itk::ConstNeighborhoodIterator< TInput1 > InputImageNeighborhoodIterator; + typedef typename TInput1::PixelType InputImagePixelType; - typedef MRFEnergy<TInput1, TInput2> EnergyFidelityType; - typedef MRFEnergy<TInput2, TInput2> EnergyRegularizationType; + typedef itk::NeighborhoodIterator< TInput2 > LabelledImageNeighborhoodIterator; + typedef typename TInput2::PixelType LabelledImagePixelType; - typedef typename EnergyFidelityType::Pointer EnergyFidelityPointer; - typedef typename EnergyRegularizationType::Pointer EnergyRegularizationPointer; + typedef MRFEnergy<TInput1, TInput2> EnergyFidelityType; + typedef MRFEnergy<TInput2, TInput2> EnergyRegularizationType; - itkTypeMacro(MRFSampler,Object); + typedef typename EnergyFidelityType::Pointer EnergyFidelityPointer; + typedef typename EnergyRegularizationType::Pointer EnergyRegularizationPointer; - itkSetMacro(NumberOfClasses, unsigned int); - itkGetMacro(NumberOfClasses, unsigned int); + itkTypeMacro(MRFSampler,Object); - itkSetMacro(Lambda, double); - itkGetMacro(Lambda, double); + itkSetMacro(NumberOfClasses, unsigned int); + itkGetMacro(NumberOfClasses, unsigned int); - itkGetMacro(DeltaEnergy, double); - itkGetMacro(Value, LabelledImagePixelType); + itkSetMacro(Lambda, double); + itkGetMacro(Lambda, double); - // Accessor for validation tests pour les tests - itkGetConstMacro(EnergyBefore, double); - itkGetConstMacro(EnergyAfter, double); + itkGetMacro(DeltaEnergy, double); + itkGetMacro(Value, LabelledImagePixelType); - itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType); - itkSetObjectMacro( EnergyFidelity, EnergyFidelityType); + // Accessor for validation tests pour les tests + itkGetConstMacro(EnergyBefore, double); + itkGetConstMacro(EnergyAfter, double); - virtual int Compute( const InputImageNeighborhoodIterator & itData, - const LabelledImageNeighborhoodIterator & itRegul) = 0; + itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType); + itkSetObjectMacro( EnergyFidelity, EnergyFidelityType); - protected: - unsigned int m_NumberOfClasses; - double m_EnergyBefore; - double m_EnergyAfter; - double m_DeltaEnergy; - double m_EnergyCurrent; - double m_Lambda; + virtual int Compute( const InputImageNeighborhoodIterator & itData, + const LabelledImageNeighborhoodIterator & itRegul) = 0; - LabelledImagePixelType m_Value; - EnergyRegularizationPointer m_EnergyRegularization; - EnergyFidelityPointer m_EnergyFidelity; - LabelledImagePixelType m_ValueCurrent; +protected: + unsigned int m_NumberOfClasses; + double m_EnergyBefore; + double m_EnergyAfter; + double m_DeltaEnergy; + double m_EnergyCurrent; + double m_Lambda; + LabelledImagePixelType m_Value; + EnergyRegularizationPointer m_EnergyRegularization; + EnergyFidelityPointer m_EnergyFidelity; + LabelledImagePixelType m_ValueCurrent; - protected: - // The constructor and destructor. - MRFSampler() - { - m_EnergyRegularization = EnergyRegularizationType::New(); - m_EnergyFidelity = EnergyFidelityType::New(), - m_NumberOfClasses =1; - m_EnergyBefore = 1.; - m_EnergyAfter = 1.; - m_DeltaEnergy = 1.; - m_EnergyCurrent = 1.; - m_Lambda = 1.; - }; - virtual ~MRFSampler() {}; +protected: + // The constructor and destructor. + MRFSampler() + { + m_EnergyRegularization = EnergyRegularizationType::New(); + m_EnergyFidelity = EnergyFidelityType::New(), + m_NumberOfClasses =1; + m_EnergyBefore = 1.; + m_EnergyAfter = 1.; + m_DeltaEnergy = 1.; + m_EnergyCurrent = 1.; + m_Lambda = 1.; }; + virtual ~MRFSampler() {}; + +}; } diff --git a/Code/Markov/otbMRFSamplerMAP.h b/Code/Markov/otbMRFSamplerMAP.h index e7b9a02ccdecb632fb32e62a8050120eae89f9b9..fca62e589643c0b0c7a9ca572f617c54f389a085 100644 --- a/Code/Markov/otbMRFSamplerMAP.h +++ b/Code/Markov/otbMRFSamplerMAP.h @@ -39,67 +39,67 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFSamplerMAP : public MRFSampler< TInput1, TInput2> { - public: - - typedef MRFSamplerMAP Self; - typedef MRFSampler< TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; - typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; - typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; - typedef typename Superclass::InputImagePixelType InputImagePixelType; - typedef typename Superclass::EnergyFidelityType EnergyFidelityType; - typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; - typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; - typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; - - itkNewMacro(Self); - - itkTypeMacro(MRFSamplerMAP,MRFSampler); - - inline int Compute( const InputImageNeighborhoodIterator & itData, - const LabelledImageNeighborhoodIterator & itRegul) +public: + + typedef MRFSamplerMAP Self; + typedef MRFSampler< TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; + typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; + typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; + typedef typename Superclass::InputImagePixelType InputImagePixelType; + typedef typename Superclass::EnergyFidelityType EnergyFidelityType; + typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; + typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; + typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; + + itkNewMacro(Self); + + itkTypeMacro(MRFSamplerMAP,MRFSampler); + + inline int Compute( const InputImageNeighborhoodIterator & itData, + const LabelledImageNeighborhoodIterator & itRegul) + { + if (this->m_NumberOfClasses == 0) { - if (this->m_NumberOfClasses == 0) - { - itkExceptionMacro(<<"NumberOfClasse has to be greater than 0."); - } + itkExceptionMacro(<<"NumberOfClasse has to be greater than 0."); + } - this->m_EnergyBefore=this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); - this->m_EnergyBefore += this->m_Lambda - * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); + this->m_EnergyBefore=this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); + this->m_EnergyBefore += this->m_Lambda + * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); - //Try all possible value (how to be generic ?) - this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one - this->m_Value = itRegul.GetCenterPixel(); + //Try all possible value (how to be generic ?) + this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one + this->m_Value = itRegul.GetCenterPixel(); - LabelledImagePixelType valueCurrent = 0; - while( valueCurrent<static_cast<LabelledImagePixelType>(this->GetNumberOfClasses()) && valueCurrent != itk::NumericTraits<LabelledImagePixelType>::max() ) + LabelledImagePixelType valueCurrent = 0; + while ( valueCurrent<static_cast<LabelledImagePixelType>(this->GetNumberOfClasses()) && valueCurrent != itk::NumericTraits<LabelledImagePixelType>::max() ) + { + this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, valueCurrent); + this->m_EnergyCurrent += this->m_Lambda + * this->m_EnergyRegularization->GetValue(itRegul, valueCurrent); + if (this->m_EnergyCurrent < this->m_EnergyAfter) { - this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, valueCurrent); - this->m_EnergyCurrent += this->m_Lambda - * this->m_EnergyRegularization->GetValue(itRegul, valueCurrent); - if (this->m_EnergyCurrent < this->m_EnergyAfter) - { - this->m_EnergyAfter = this->m_EnergyCurrent; - this->m_Value = valueCurrent; - } - valueCurrent++; + this->m_EnergyAfter = this->m_EnergyCurrent; + this->m_Value = valueCurrent; } + valueCurrent++; + } - this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; + this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; - return 0; - } + return 0; + } - protected: - // The constructor and destructor. - MRFSamplerMAP() {} - virtual ~MRFSamplerMAP() {} +protected: + // The constructor and destructor. + MRFSamplerMAP() {} + virtual ~MRFSamplerMAP() {} }; diff --git a/Code/Markov/otbMRFSamplerRandom.h b/Code/Markov/otbMRFSamplerRandom.h index 2f9b334f2db96dde9d3f8d738a0599b6092520d7..c080a913727dc03d255d2e114d390624baa27053 100644 --- a/Code/Markov/otbMRFSamplerRandom.h +++ b/Code/Markov/otbMRFSamplerRandom.h @@ -39,59 +39,65 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFSamplerRandom: public MRFSampler< TInput1, TInput2> +{ +public: + typedef MRFSamplerRandom Self; + typedef otb::MRFSampler<TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; + typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; + typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; + typedef typename Superclass::InputImagePixelType InputImagePixelType; + typedef typename Superclass::EnergyFidelityType EnergyFidelityType; + typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; + typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; + typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; + + typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + + itkNewMacro(Self); + + itkTypeMacro(MRFSamplerRandom,MRFSampler); + + inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul) { - public: - typedef MRFSamplerRandom Self; - typedef otb::MRFSampler<TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; - typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; - typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; - typedef typename Superclass::InputImagePixelType InputImagePixelType; - typedef typename Superclass::EnergyFidelityType EnergyFidelityType; - typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; - typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; - typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; - - typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; - - itkNewMacro(Self); - - itkTypeMacro(MRFSamplerRandom,MRFSampler); - - inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul) - { - this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); - this->m_EnergyBefore += this->m_Lambda - * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); - - this->m_Value = static_cast<LabelledImagePixelType>(m_Generator->GetIntegerVariate() % this->m_NumberOfClasses); - this->m_EnergyAfter = this->m_EnergyFidelity->GetValue(itData, this->m_Value); - this->m_EnergyAfter += this->m_Lambda * this->m_EnergyRegularization->GetValue(itRegul, this->m_Value); - this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; - - return 0; - } - - /** Methods to cancel random effects.*/ - void InitializeSeed(int seed){ m_Generator->SetSeed(seed); } - void InitializeSeed(){ m_Generator->SetSeed(); } - - protected: - // The constructor and destructor. - MRFSamplerRandom() - { - m_Generator = RandomGeneratorType::New(); - m_Generator->SetSeed(); - } - virtual ~MRFSamplerRandom() {} - - - private: - RandomGeneratorType::Pointer m_Generator; - }; + this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); + this->m_EnergyBefore += this->m_Lambda + * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); + + this->m_Value = static_cast<LabelledImagePixelType>(m_Generator->GetIntegerVariate() % this->m_NumberOfClasses); + this->m_EnergyAfter = this->m_EnergyFidelity->GetValue(itData, this->m_Value); + this->m_EnergyAfter += this->m_Lambda * this->m_EnergyRegularization->GetValue(itRegul, this->m_Value); + this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; + + return 0; + } + + /** Methods to cancel random effects.*/ + void InitializeSeed(int seed) + { + m_Generator->SetSeed(seed); + } + void InitializeSeed() + { + m_Generator->SetSeed(); + } + +protected: + // The constructor and destructor. + MRFSamplerRandom() + { + m_Generator = RandomGeneratorType::New(); + m_Generator->SetSeed(); + } + virtual ~MRFSamplerRandom() {} + + +private: + RandomGeneratorType::Pointer m_Generator; +}; } #endif diff --git a/Code/Markov/otbMRFSamplerRandomMAP.h b/Code/Markov/otbMRFSamplerRandomMAP.h index 5518301044188942829ad42b1dfa1308564ca683..1be1680d817b50866c6ef7f2c3f144051a4921fd 100644 --- a/Code/Markov/otbMRFSamplerRandomMAP.h +++ b/Code/Markov/otbMRFSamplerRandomMAP.h @@ -46,127 +46,133 @@ namespace otb template< class TInput1, class TInput2> class ITK_EXPORT MRFSamplerRandomMAP: public MRFSampler< TInput1, TInput2> { - public: +public: - typedef MRFSamplerRandomMAP Self; - typedef otb::MRFSampler<TInput1, TInput2> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + typedef MRFSamplerRandomMAP Self; + typedef otb::MRFSampler<TInput1, TInput2> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; - typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; - typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; - typedef typename Superclass::InputImagePixelType InputImagePixelType; - typedef typename Superclass::EnergyFidelityType EnergyFidelityType; - typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; - typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; - typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; - typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + typedef typename Superclass::InputImageNeighborhoodIterator InputImageNeighborhoodIterator; + typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator; + typedef typename Superclass::LabelledImagePixelType LabelledImagePixelType; + typedef typename Superclass::InputImagePixelType InputImagePixelType; + typedef typename Superclass::EnergyFidelityType EnergyFidelityType; + typedef typename Superclass::EnergyRegularizationType EnergyRegularizationType; + typedef typename Superclass::EnergyFidelityPointer EnergyFidelityPointer; + typedef typename Superclass::EnergyRegularizationPointer EnergyRegularizationPointer; + typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; - itkNewMacro(Self); + itkNewMacro(Self); - itkTypeMacro(MRFSamplerRandomMAP,MRFSampler); + itkTypeMacro(MRFSamplerRandomMAP,MRFSampler); - void SetNumberOfClasses(const unsigned int nClasses) + void SetNumberOfClasses(const unsigned int nClasses) + { + if (nClasses != this->m_NumberOfClasses || energiesInvalid == true) { - if (nClasses != this->m_NumberOfClasses || energiesInvalid == true) - { - this->m_NumberOfClasses = nClasses; - if (energy != NULL) - free(energy); - if (repartitionFunction != NULL) - free(repartitionFunction); - energy = (double *) calloc(this->m_NumberOfClasses, sizeof(double)); - repartitionFunction = (double *) calloc(this->m_NumberOfClasses, sizeof(double)); - this->Modified(); - } + this->m_NumberOfClasses = nClasses; + if (energy != NULL) + free(energy); + if (repartitionFunction != NULL) + free(repartitionFunction); + energy = (double *) calloc(this->m_NumberOfClasses, sizeof(double)); + repartitionFunction = (double *) calloc(this->m_NumberOfClasses, sizeof(double)); + this->Modified(); } + } - inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul) + inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul) + { + if (this->m_NumberOfClasses == 0) { - if (this->m_NumberOfClasses == 0) - { - itkExceptionMacro(<<"NumberOfClasse has to be greater than 0."); - } - - this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); - this->m_EnergyBefore += this->m_Lambda - * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); - - //Try all possible value (how to be generic ?) - this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one - this->m_Value = itRegul.GetCenterPixel(); - - //Compute probability for each possibility - double totalProba=0.0; - unsigned int valueCurrent = 0; - for (valueCurrent = 0; valueCurrent < this->m_NumberOfClasses; ++valueCurrent) - { - this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, static_cast<LabelledImagePixelType>(valueCurrent)); - this->m_EnergyCurrent += this->m_Lambda - * this->m_EnergyRegularization->GetValue(itRegul, static_cast<LabelledImagePixelType>(valueCurrent)); - - energy[valueCurrent] = this->m_EnergyCurrent; - repartitionFunction[valueCurrent] = vcl_exp(-this->m_EnergyCurrent)+totalProba; - totalProba = repartitionFunction[valueCurrent]; - - } - - //Pick a value according to probability - - //double select = (m_Generator->GetIntegerVariate()/(double(RAND_MAX)+1) * totalProba); - double select = (m_Generator->GetIntegerVariate()/(double(itk::NumericTraits<RandomGeneratorType::IntegerType>::max())+1) * totalProba); - valueCurrent = 0; - while( valueCurrent<this->GetNumberOfClasses() && repartitionFunction[valueCurrent] <= select) - { - valueCurrent++; - } - - if ( valueCurrent==this->GetNumberOfClasses() ) - { - valueCurrent = this->GetNumberOfClasses()-1; - } - - - if ( this->m_Value != static_cast<LabelledImagePixelType>(valueCurrent)) - { - this->m_Value = static_cast<LabelledImagePixelType>(valueCurrent); - this->m_EnergyAfter = energy[static_cast<unsigned int>(valueCurrent)]; - } - - this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; - - return 0; + itkExceptionMacro(<<"NumberOfClasse has to be greater than 0."); } - /** Methods to cancel random effects.*/ - void InitializeSeed(int seed){ m_Generator->SetSeed(seed); } - void InitializeSeed(){ m_Generator->SetSeed(); } + this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel()); + this->m_EnergyBefore += this->m_Lambda + * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel()); + + //Try all possible value (how to be generic ?) + this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one + this->m_Value = itRegul.GetCenterPixel(); - protected: - // The constructor and destructor. - MRFSamplerRandomMAP() + //Compute probability for each possibility + double totalProba=0.0; + unsigned int valueCurrent = 0; + for (valueCurrent = 0; valueCurrent < this->m_NumberOfClasses; ++valueCurrent) { - energy=NULL; - repartitionFunction=NULL; - energiesInvalid = true; - m_Generator = RandomGeneratorType::New(); - m_Generator->SetSeed(); + this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, static_cast<LabelledImagePixelType>(valueCurrent)); + this->m_EnergyCurrent += this->m_Lambda + * this->m_EnergyRegularization->GetValue(itRegul, static_cast<LabelledImagePixelType>(valueCurrent)); + + energy[valueCurrent] = this->m_EnergyCurrent; + repartitionFunction[valueCurrent] = vcl_exp(-this->m_EnergyCurrent)+totalProba; + totalProba = repartitionFunction[valueCurrent]; + } - virtual ~MRFSamplerRandomMAP() + + //Pick a value according to probability + + //double select = (m_Generator->GetIntegerVariate()/(double(RAND_MAX)+1) * totalProba); + double select = (m_Generator->GetIntegerVariate()/(double(itk::NumericTraits<RandomGeneratorType::IntegerType>::max())+1) * totalProba); + valueCurrent = 0; + while ( valueCurrent<this->GetNumberOfClasses() && repartitionFunction[valueCurrent] <= select) { - if (energy != NULL) - free(energy); - if (repartitionFunction != NULL) - free(repartitionFunction); + valueCurrent++; + } + + if ( valueCurrent==this->GetNumberOfClasses() ) + { + valueCurrent = this->GetNumberOfClasses()-1; + } + + + if ( this->m_Value != static_cast<LabelledImagePixelType>(valueCurrent)) + { + this->m_Value = static_cast<LabelledImagePixelType>(valueCurrent); + this->m_EnergyAfter = energy[static_cast<unsigned int>(valueCurrent)]; } - private: - double * repartitionFunction; - double * energy; - bool energiesInvalid; - RandomGeneratorType::Pointer m_Generator; + this->m_DeltaEnergy= this->m_EnergyAfter - this->m_EnergyBefore; + + return 0; + } + + /** Methods to cancel random effects.*/ + void InitializeSeed(int seed) + { + m_Generator->SetSeed(seed); + } + void InitializeSeed() + { + m_Generator->SetSeed(); + } + +protected: + // The constructor and destructor. + MRFSamplerRandomMAP() + { + energy=NULL; + repartitionFunction=NULL; + energiesInvalid = true; + m_Generator = RandomGeneratorType::New(); + m_Generator->SetSeed(); + } + virtual ~MRFSamplerRandomMAP() + { + if (energy != NULL) + free(energy); + if (repartitionFunction != NULL) + free(repartitionFunction); + } + +private: + double * repartitionFunction; + double * energy; + bool energiesInvalid; + RandomGeneratorType::Pointer m_Generator; }; } diff --git a/Code/Markov/otbMarkovRandomFieldFilter.h b/Code/Markov/otbMarkovRandomFieldFilter.h index b5aeaa6c67e9a70e51387add331e4ada9439a8f8..38b88184656d47379b107d430906afa0472d4967 100644 --- a/Code/Markov/otbMarkovRandomFieldFilter.h +++ b/Code/Markov/otbMarkovRandomFieldFilter.h @@ -41,363 +41,370 @@ namespace otb { - /** - * \class MarkovRandomFieldFilter - * \brief This is the class to use the Markov Random Field framework in OTB. - * - * This filter apply a Markov Random Field to an input image. Several - * components need to be specify: - * - * - Fidelity energy (class derived from otb::MRFEnergy): the energy to make - * sure that the output image is close enough to the reference. - * - Regularization energy (class derived from otb::MRFEnergy): the energy to - * make sure that neighborhood pixels have similar values. - * - Sampler (class derived from otb::MRFSampler): the strategy to propose - * variations for each pixel. - * - Optimizer (class derived from otb::MRFOptimizer): the strategy to accept - * or reject the proposed modification. - * - * An example of usage for this filter is: - * - * \code - * markovFilter->SetNumberOfClasses(4); - * markovFilter->SetMaximumNumberOfIterations(30); - * markovFilter->SetErrorTolerance(0.0); - * markovFilter->SetLambda(1.0); - * markovFilter->SetNeighborhoodRadius(1); - * - * markovFilter->SetEnergyRegularization(energyRegularization); - * markovFilter->SetEnergyFidelity(energyFidelity); - * markovFilter->SetOptimizer(optimizer); - * markovFilter->SetSampler(sampler); - * \endcode - * - * - * \ingroup Markov - * - * \example Markov/MarkovClassification1Example.cxx - * \example Markov/MarkovClassification2Example.cxx - * \example Markov/MarkovRegularizationExample.cxx - * \example Markov/MarkovRestaurationExample.cxx - * - */ +/** + * \class MarkovRandomFieldFilter + * \brief This is the class to use the Markov Random Field framework in OTB. + * + * This filter apply a Markov Random Field to an input image. Several + * components need to be specify: + * + * - Fidelity energy (class derived from otb::MRFEnergy): the energy to make + * sure that the output image is close enough to the reference. + * - Regularization energy (class derived from otb::MRFEnergy): the energy to + * make sure that neighborhood pixels have similar values. + * - Sampler (class derived from otb::MRFSampler): the strategy to propose + * variations for each pixel. + * - Optimizer (class derived from otb::MRFOptimizer): the strategy to accept + * or reject the proposed modification. + * + * An example of usage for this filter is: + * + * \code + * markovFilter->SetNumberOfClasses(4); + * markovFilter->SetMaximumNumberOfIterations(30); + * markovFilter->SetErrorTolerance(0.0); + * markovFilter->SetLambda(1.0); + * markovFilter->SetNeighborhoodRadius(1); + * + * markovFilter->SetEnergyRegularization(energyRegularization); + * markovFilter->SetEnergyFidelity(energyFidelity); + * markovFilter->SetOptimizer(optimizer); + * markovFilter->SetSampler(sampler); + * \endcode + * + * + * \ingroup Markov + * + * \example Markov/MarkovClassification1Example.cxx + * \example Markov/MarkovClassification2Example.cxx + * \example Markov/MarkovRegularizationExample.cxx + * \example Markov/MarkovRestaurationExample.cxx + * + */ template <class TInputImage, class TClassifiedImage> class ITK_EXPORT MarkovRandomFieldFilter : -public itk::ImageToImageFilter<TInputImage,TClassifiedImage> - { - public: - /** Standard class typedefs. */ - typedef MarkovRandomFieldFilter Self; - typedef itk::ImageToImageFilter<TInputImage,TClassifiedImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::OutputImagePointer OutputImagePointer; + public itk::ImageToImageFilter<TInputImage,TClassifiedImage> +{ +public: + /** Standard class typedefs. */ + typedef MarkovRandomFieldFilter Self; + typedef itk::ImageToImageFilter<TInputImage,TClassifiedImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef typename Superclass::OutputImagePointer OutputImagePointer; - /** Run-time type information (and related methods). */ - itkTypeMacro(MarkovRandomFieldFilter,itk::ImageToImageFilter); + /** Run-time type information (and related methods). */ + itkTypeMacro(MarkovRandomFieldFilter,itk::ImageToImageFilter); - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Type definition for the input image. */ - typedef TInputImage InputImageType; - typedef typename TInputImage::Pointer InputImagePointer; - typedef typename TInputImage::ConstPointer InputImageConstPointer; + /** Type definition for the input image. */ + typedef TInputImage InputImageType; + typedef typename TInputImage::Pointer InputImagePointer; + typedef typename TInputImage::ConstPointer InputImageConstPointer; - /** Type definition for the input image pixel type. */ - typedef typename TInputImage::PixelType InputImagePixelType; + /** Type definition for the input image pixel type. */ + typedef typename TInputImage::PixelType InputImagePixelType; - /** Type definition for the input image region type. */ - typedef typename TInputImage::RegionType InputImageRegionType; + /** Type definition for the input image region type. */ + typedef typename TInputImage::RegionType InputImageRegionType; - /** Type definition for the input image region iterator */ - typedef itk::ImageRegionIterator<TInputImage> InputImageRegionIterator; - typedef itk::ImageRegionConstIterator<TInputImage> InputImageRegionConstIterator; + /** Type definition for the input image region iterator */ + typedef itk::ImageRegionIterator<TInputImage> InputImageRegionIterator; + typedef itk::ImageRegionConstIterator<TInputImage> InputImageRegionConstIterator; - /** Image dimension */ - itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + /** Image dimension */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); - /** Type definitions for the training image. */ - typedef TClassifiedImage TrainingImageType; - typedef typename TClassifiedImage::Pointer TrainingImagePointer; + /** Type definitions for the training image. */ + typedef TClassifiedImage TrainingImageType; + typedef typename TClassifiedImage::Pointer TrainingImagePointer; - /** Type definitions for the training image pixel type. */ - typedef typename TClassifiedImage::PixelType TrainingImagePixelType; + /** Type definitions for the training image pixel type. */ + typedef typename TClassifiedImage::PixelType TrainingImagePixelType; - /** Type definitions for the labelled image. - * It is derived from the training image. */ - typedef TClassifiedImage LabelledImageType; - typedef typename TClassifiedImage::Pointer LabelledImagePointer; + /** Type definitions for the labelled image. + * It is derived from the training image. */ + typedef TClassifiedImage LabelledImageType; + typedef typename TClassifiedImage::Pointer LabelledImagePointer; - /** Type definitions for the classified image pixel type. - * It has to be the same type as the training image. */ - typedef typename TClassifiedImage::PixelType LabelledImagePixelType; + /** Type definitions for the classified image pixel type. + * It has to be the same type as the training image. */ + typedef typename TClassifiedImage::PixelType LabelledImagePixelType; - /** Type definitions for the classified image pixel type. - * It has to be the same type as the training image. */ - typedef typename TClassifiedImage::RegionType LabelledImageRegionType; + /** Type definitions for the classified image pixel type. + * It has to be the same type as the training image. */ + typedef typename TClassifiedImage::RegionType LabelledImageRegionType; - /** Type definition for the classified image index type. */ - typedef typename TClassifiedImage::IndexType LabelledImageIndexType; - typedef typename LabelledImageIndexType::IndexValueType IndexValueType; + /** Type definition for the classified image index type. */ + typedef typename TClassifiedImage::IndexType LabelledImageIndexType; + typedef typename LabelledImageIndexType::IndexValueType IndexValueType; - /** Type definition for the classified image offset type. */ - typedef typename TClassifiedImage::OffsetType LabelledImageOffsetType; + /** Type definition for the classified image offset type. */ + typedef typename TClassifiedImage::OffsetType LabelledImageOffsetType; - /** Type definition for the input image region iterator */ - typedef itk::ImageRegionIterator<TClassifiedImage> - LabelledImageRegionIterator; + /** Type definition for the input image region iterator */ + typedef itk::ImageRegionIterator<TClassifiedImage> + LabelledImageRegionIterator; - typedef itk::ImageRegionConstIterator<TClassifiedImage> - LabelledImageRegionConstIterator; + typedef itk::ImageRegionConstIterator<TClassifiedImage> + LabelledImageRegionConstIterator; - /** Labelled Image dimension */ - itkStaticConstMacro(ClassifiedImageDimension, unsigned int, - TClassifiedImage::ImageDimension); + /** Labelled Image dimension */ + itkStaticConstMacro(ClassifiedImageDimension, unsigned int, + TClassifiedImage::ImageDimension); - /** Type definitions for classifier to be used for the MRF lavbelling. */ - typedef itk::ImageClassifierBase<TInputImage,TClassifiedImage> ClassifierType; + /** Type definitions for classifier to be used for the MRF lavbelling. */ + typedef itk::ImageClassifierBase<TInputImage,TClassifiedImage> ClassifierType; - /** Size and value typedef support. */ - typedef typename TInputImage::SizeType SizeType; + /** Size and value typedef support. */ + typedef typename TInputImage::SizeType SizeType; - /** Radius typedef support. */ - typedef typename TInputImage::SizeType NeighborhoodRadiusType; + /** Radius typedef support. */ + typedef typename TInputImage::SizeType NeighborhoodRadiusType; - /** Input image neighborhood iterator and kernel size typedef */ - typedef itk::ConstNeighborhoodIterator< TInputImage > - InputImageNeighborhoodIterator; + /** Input image neighborhood iterator and kernel size typedef */ + typedef itk::ConstNeighborhoodIterator< TInputImage > + InputImageNeighborhoodIterator; - typedef typename InputImageNeighborhoodIterator::RadiusType - InputImageNeighborhoodRadiusType; + typedef typename InputImageNeighborhoodIterator::RadiusType + InputImageNeighborhoodRadiusType; - typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TInputImage > - InputImageFacesCalculator; + typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TInputImage > + InputImageFacesCalculator; - typedef typename InputImageFacesCalculator::FaceListType - InputImageFaceListType; + typedef typename InputImageFacesCalculator::FaceListType + InputImageFaceListType; - typedef typename InputImageFaceListType::iterator - InputImageFaceListIterator; + typedef typename InputImageFaceListType::iterator + InputImageFaceListIterator; - /** Labelled image neighborhood interator typedef */ - typedef itk::NeighborhoodIterator< TClassifiedImage > - LabelledImageNeighborhoodIterator; + /** Labelled image neighborhood interator typedef */ + typedef itk::NeighborhoodIterator< TClassifiedImage > + LabelledImageNeighborhoodIterator; - typedef typename LabelledImageNeighborhoodIterator::RadiusType - LabelledImageNeighborhoodRadiusType; + typedef typename LabelledImageNeighborhoodIterator::RadiusType + LabelledImageNeighborhoodRadiusType; - typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TClassifiedImage > - LabelledImageFacesCalculator; + typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< TClassifiedImage > + LabelledImageFacesCalculator; - typedef typename LabelledImageFacesCalculator::FaceListType - LabelledImageFaceListType; + typedef typename LabelledImageFacesCalculator::FaceListType + LabelledImageFaceListType; - typedef typename LabelledImageFaceListType::iterator - LabelledImageFaceListIterator; + typedef typename LabelledImageFaceListType::iterator + LabelledImageFaceListIterator; - /** Typedef for random values. */ - typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; + /** Typedef for random values. */ + typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; - /** Set the pointer to the classifer being used. */ - void SetClassifier( typename ClassifierType::Pointer ptrToClassifier ); + /** Set the pointer to the classifer being used. */ + void SetClassifier( typename ClassifierType::Pointer ptrToClassifier ); - /** Set pipeline elements */ - typedef MRFEnergy< TClassifiedImage, TClassifiedImage> EnergyRegularizationType; - typedef MRFEnergy< TInputImage, TClassifiedImage> EnergyFidelityType; + /** Set pipeline elements */ + typedef MRFEnergy< TClassifiedImage, TClassifiedImage> EnergyRegularizationType; + typedef MRFEnergy< TInputImage, TClassifiedImage> EnergyFidelityType; - typedef typename EnergyRegularizationType::Pointer EnergyRegularizationPointer; - typedef typename EnergyFidelityType::Pointer EnergyFidelityPointer; + typedef typename EnergyRegularizationType::Pointer EnergyRegularizationPointer; + typedef typename EnergyFidelityType::Pointer EnergyFidelityPointer; - typedef MRFSampler< TInputImage, TClassifiedImage> SamplerType; - typedef typename SamplerType::Pointer SamplerPointer; + typedef MRFSampler< TInputImage, TClassifiedImage> SamplerType; + typedef typename SamplerType::Pointer SamplerPointer; - typedef MRFOptimizer OptimizerType; - typedef typename OptimizerType::Pointer OptimizerPointer; + typedef MRFOptimizer OptimizerType; + typedef typename OptimizerType::Pointer OptimizerPointer; - /** - ************ ACCESSORS ************ - */ - itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType); - itkGetObjectMacro( EnergyRegularization, EnergyRegularizationType); + /** + ************ ACCESSORS ************ + */ + itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType); + itkGetObjectMacro( EnergyRegularization, EnergyRegularizationType); - itkSetObjectMacro( EnergyFidelity, EnergyFidelityType); - itkGetObjectMacro( EnergyFidelity, EnergyFidelityType); + itkSetObjectMacro( EnergyFidelity, EnergyFidelityType); + itkGetObjectMacro( EnergyFidelity, EnergyFidelityType); - itkSetObjectMacro( Sampler, SamplerType); - itkGetObjectMacro( Sampler, SamplerType); + itkSetObjectMacro( Sampler, SamplerType); + itkGetObjectMacro( Sampler, SamplerType); - itkSetObjectMacro( Optimizer, OptimizerType); - itkGetObjectMacro( Optimizer, OptimizerType); + itkSetObjectMacro( Optimizer, OptimizerType); + itkGetObjectMacro( Optimizer, OptimizerType); - /** Set/Get the number of classes. */ - itkSetMacro(NumberOfClasses, unsigned int); - itkGetMacro(NumberOfClasses, unsigned int); + /** Set/Get the number of classes. */ + itkSetMacro(NumberOfClasses, unsigned int); + itkGetMacro(NumberOfClasses, unsigned int); - /** Set/Get the number of iteration of the Iterated Conditional Mode - * (ICM) algorithm. A default value is set at 50 iterations. */ - itkSetMacro(MaximumNumberOfIterations, unsigned int); - itkGetMacro(MaximumNumberOfIterations, unsigned int); + /** Set/Get the number of iteration of the Iterated Conditional Mode + * (ICM) algorithm. A default value is set at 50 iterations. */ + itkSetMacro(MaximumNumberOfIterations, unsigned int); + itkGetMacro(MaximumNumberOfIterations, unsigned int); - /** Set/Get the error tollerance level which is used as a threshold - * to quit the iterations */ - itkSetMacro(ErrorTolerance, double); - itkGetMacro(ErrorTolerance, double); + /** Set/Get the error tollerance level which is used as a threshold + * to quit the iterations */ + itkSetMacro(ErrorTolerance, double); + itkGetMacro(ErrorTolerance, double); - /** Set/Get the degree of smoothing desired - * */ - itkSetMacro(SmoothingFactor, double); - itkGetMacro(SmoothingFactor, double); + /** Set/Get the degree of smoothing desired + * */ + itkSetMacro(SmoothingFactor, double); + itkGetMacro(SmoothingFactor, double); - /** Set/Get the regularization coefficient - * */ - itkSetMacro(Lambda, double); - itkGetMacro(Lambda, double); + /** Set/Get the regularization coefficient + * */ + itkSetMacro(Lambda, double); + itkGetMacro(Lambda, double); - /** Set the neighborhood radius */ - void SetNeighborhoodRadius(const NeighborhoodRadiusType &); + /** Set the neighborhood radius */ + void SetNeighborhoodRadius(const NeighborhoodRadiusType &); - /** Sets the radius for the neighborhood, calculates size from the - * radius, and allocates storage. */ + /** Sets the radius for the neighborhood, calculates size from the + * radius, and allocates storage. */ - void SetNeighborhoodRadius( const unsigned long ); - void SetNeighborhoodRadius( const unsigned long *radiusArray ); + void SetNeighborhoodRadius( const unsigned long ); + void SetNeighborhoodRadius( const unsigned long *radiusArray ); - /** Get the neighborhood radius */ - const NeighborhoodRadiusType GetNeighborhoodRadius() const - { - NeighborhoodRadiusType m_NeighborhoodRadius; + /** Get the neighborhood radius */ + const NeighborhoodRadiusType GetNeighborhoodRadius() const + { + NeighborhoodRadiusType m_NeighborhoodRadius; - for(int i=0; i<InputImageDimension; ++i) - m_NeighborhoodRadius[i] = m_InputImageNeighborhoodRadius[i]; + for (int i=0; i<InputImageDimension; ++i) + m_NeighborhoodRadius[i] = m_InputImageNeighborhoodRadius[i]; - return m_NeighborhoodRadius; - } + return m_NeighborhoodRadius; + } - /** Set training image for the starting point. This is not compulsory: - * if the starting image is not specified, a random image will be used - * instead. - */ - virtual void SetTrainingInput( const TrainingImageType * trainingImage); - const TrainingImageType* GetTrainingInput(void); + /** Set training image for the starting point. This is not compulsory: + * if the starting image is not specified, a random image will be used + * instead. + */ + virtual void SetTrainingInput( const TrainingImageType * trainingImage); + const TrainingImageType* GetTrainingInput(void); - //Enum to get the stopping condition of the MRF filter - typedef enum{ - MaximumNumberOfIterations=1, - ErrorTolerance - } StopConditionType; + //Enum to get the stopping condition of the MRF filter + typedef enum + { + MaximumNumberOfIterations=1, + ErrorTolerance + } StopConditionType; - /** Get condition that stops the MRF filter (Number of Iterations - * / Error tolerance ) */ - itkGetConstReferenceMacro( StopCondition, StopConditionType ); + /** Get condition that stops the MRF filter (Number of Iterations + * / Error tolerance ) */ + itkGetConstReferenceMacro( StopCondition, StopConditionType ); - /** Get macro for number of iterations */ - itkGetConstReferenceMacro( NumberOfIterations, unsigned int ); + /** Get macro for number of iterations */ + itkGetConstReferenceMacro( NumberOfIterations, unsigned int ); #ifdef ITK_USE_CONCEPT_CHECKING - /** Begin concept checking */ - itkConceptMacro(UnsignedIntConvertibleToClassifiedCheck, - (itk::Concept::Convertible<unsigned int, LabelledImagePixelType>)); - itkConceptMacro(ClassifiedConvertibleToUnsignedIntCheck, - (itk::Concept::Convertible<LabelledImagePixelType, unsigned int> )); - itkConceptMacro(ClassifiedConvertibleToIntCheck, - (itk::Concept::Convertible<LabelledImagePixelType, int> )); - itkConceptMacro(IntConvertibleToClassifiedCheck, - (itk::Concept::Convertible<int, LabelledImagePixelType>)); - itkConceptMacro(SameDimensionCheck, - (itk::Concept::SameDimension<InputImageDimension, ClassifiedImageDimension>)); - /** End concept checking */ + /** Begin concept checking */ + itkConceptMacro(UnsignedIntConvertibleToClassifiedCheck, + (itk::Concept::Convertible<unsigned int, LabelledImagePixelType>)); + itkConceptMacro(ClassifiedConvertibleToUnsignedIntCheck, + (itk::Concept::Convertible<LabelledImagePixelType, unsigned int> )); + itkConceptMacro(ClassifiedConvertibleToIntCheck, + (itk::Concept::Convertible<LabelledImagePixelType, int> )); + itkConceptMacro(IntConvertibleToClassifiedCheck, + (itk::Concept::Convertible<int, LabelledImagePixelType>)); + itkConceptMacro(SameDimensionCheck, + (itk::Concept::SameDimension<InputImageDimension, ClassifiedImageDimension>)); + /** End concept checking */ #endif - /** Methods to cancel random effects.*/ - void InitializeSeed(int seed){ m_Generator->SetSeed(seed); } - void InitializeSeed(){ m_Generator->SetSeed(); } + /** Methods to cancel random effects.*/ + void InitializeSeed(int seed) + { + m_Generator->SetSeed(seed); + } + void InitializeSeed() + { + m_Generator->SetSeed(); + } - protected: - MarkovRandomFieldFilter(); - ~MarkovRandomFieldFilter(); - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + MarkovRandomFieldFilter(); + ~MarkovRandomFieldFilter(); + void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** Allocate memory for labelled images. This is automatically called - * in GenerateData(). - */ - void Allocate(); + /** Allocate memory for labelled images. This is automatically called + * in GenerateData(). + */ + void Allocate(); - /** Connect the pipeline and propagate the required parameters. This - * is automatically called in GenerateData(). - */ - void Initialize() throw (itk::ExceptionObject); + /** Connect the pipeline and propagate the required parameters. This + * is automatically called in GenerateData(). + */ + void Initialize() throw (itk::ExceptionObject); - virtual void ApplyMarkovRandomFieldFilter(); + virtual void ApplyMarkovRandomFieldFilter(); - virtual void GenerateData(); - virtual void GenerateInputRequestedRegion(); - virtual void EnlargeOutputRequestedRegion( itk::DataObject * ); - virtual void GenerateOutputInformation(); + virtual void GenerateData(); + virtual void GenerateInputRequestedRegion(); + virtual void EnlargeOutputRequestedRegion( itk::DataObject * ); + virtual void GenerateOutputInformation(); - MarkovRandomFieldFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + MarkovRandomFieldFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - typedef typename TInputImage::SizeType InputImageSizeType; + typedef typename TInputImage::SizeType InputImageSizeType; - InputImageNeighborhoodRadiusType m_InputImageNeighborhoodRadius; - LabelledImageNeighborhoodRadiusType m_LabelledImageNeighborhoodRadius; + InputImageNeighborhoodRadiusType m_InputImageNeighborhoodRadius; + LabelledImageNeighborhoodRadiusType m_LabelledImageNeighborhoodRadius; - unsigned int m_NumberOfClasses; - unsigned int m_MaximumNumberOfIterations; - unsigned int m_KernelSize; + unsigned int m_NumberOfClasses; + unsigned int m_MaximumNumberOfIterations; + unsigned int m_KernelSize; - int m_ErrorCounter; - double m_ImageDeltaEnergy; + int m_ErrorCounter; + double m_ImageDeltaEnergy; - int m_NeighborhoodRadius; - int m_TotalNumberOfValidPixelsInOutputImage; - int m_TotalNumberOfPixelsInInputImage; - double m_ErrorTolerance; - double m_SmoothingFactor; + int m_NeighborhoodRadius; + int m_TotalNumberOfValidPixelsInOutputImage; + int m_TotalNumberOfPixelsInInputImage; + double m_ErrorTolerance; + double m_SmoothingFactor; - unsigned int m_NumberOfIterations; + unsigned int m_NumberOfIterations; - double m_Lambda; - bool m_ExternalClassificationSet; - StopConditionType m_StopCondition; + double m_Lambda; + bool m_ExternalClassificationSet; + StopConditionType m_StopCondition; - TrainingImagePointer m_TrainingImage; + TrainingImagePointer m_TrainingImage; - std::vector<double> m_MRFNeighborhoodWeight; - std::vector<double> m_NeighborInfluence; - std::vector<double> m_DummyVector; + std::vector<double> m_MRFNeighborhoodWeight; + std::vector<double> m_NeighborInfluence; + std::vector<double> m_DummyVector; - RandomGeneratorType::Pointer m_Generator; + RandomGeneratorType::Pointer m_Generator; - /** Pointer to different elements */ + /** Pointer to different elements */ - EnergyRegularizationPointer m_EnergyRegularization; - EnergyFidelityPointer m_EnergyFidelity; - OptimizerPointer m_Optimizer; - SamplerPointer m_Sampler; + EnergyRegularizationPointer m_EnergyRegularization; + EnergyFidelityPointer m_EnergyFidelity; + OptimizerPointer m_Optimizer; + SamplerPointer m_Sampler; - virtual void MinimizeOnce(); + virtual void MinimizeOnce(); - private: +private: - }; // class MarkovRandomFieldFilter +}; // class MarkovRandomFieldFilter } // namespace otb diff --git a/Code/Markov/otbMarkovRandomFieldFilter.txx b/Code/Markov/otbMarkovRandomFieldFilter.txx index 64c21b68952d22b9b27dd11ff9bb21a38754a02a..3439a580b952786d5098f2ed8fd92a68a8a4caea 100644 --- a/Code/Markov/otbMarkovRandomFieldFilter.txx +++ b/Code/Markov/otbMarkovRandomFieldFilter.txx @@ -56,12 +56,12 @@ MarkovRandomFieldFilter<TInputImage,TClassifiedImage> m_Generator->SetSeed(); this->SetNumberOfRequiredInputs(1); - if( (int)InputImageDimension != (int)ClassifiedImageDimension ) - { - itk::OStringStream msg; - msg << "Input image dimension: " << InputImageDimension << " != output image dimension: " << ClassifiedImageDimension; - throw itk::ExceptionObject(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); - } + if ( (int)InputImageDimension != (int)ClassifiedImageDimension ) + { + itk::OStringStream msg; + msg << "Input image dimension: " << InputImageDimension << " != output image dimension: " << ClassifiedImageDimension; + throw itk::ExceptionObject(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION); + } m_InputImageNeighborhoodRadius.Fill(m_NeighborhoodRadius); // m_MRFNeighborhoodWeight.resize(0); // m_NeighborInfluence.resize(0); @@ -98,11 +98,11 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> ::GetTrainingInput(void) { if (this->GetNumberOfInputs() < 2) - { - return 0; - } + { + return 0; + } return static_cast<const TrainingImageType * > - (this->itk::ProcessObject::GetInput(1) ); + (this->itk::ProcessObject::GetInput(1) ); } @@ -118,22 +118,22 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> os << indent <<" Number of classes: " << m_NumberOfClasses << std::endl; os << indent <<" Maximum number of iterations: " << - m_MaximumNumberOfIterations << std::endl; + m_MaximumNumberOfIterations << std::endl; os << indent <<" Error tolerance for convergence: " << - m_ErrorTolerance << std::endl; + m_ErrorTolerance << std::endl; os << indent <<" Size of the MRF neighborhood radius:" << - m_InputImageNeighborhoodRadius << std::endl; + m_InputImageNeighborhoodRadius << std::endl; os << indent << "StopCondition: " - << m_StopCondition << std::endl; + << m_StopCondition << std::endl; os << indent <<" Number of iterations: " << - m_NumberOfIterations << std::endl; + m_NumberOfIterations << std::endl; os << indent <<" Lambda: " << - m_Lambda << std::endl; + m_Lambda << std::endl; }// end PrintSelf @@ -221,10 +221,10 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> { //Set up the neighbor hood NeighborhoodRadiusType radius; - for(unsigned int i=0;i < InputImageDimension; ++i) - { - radius[i] = radiusValue; - } + for (unsigned int i=0;i < InputImageDimension; ++i) + { + radius[i] = radiusValue; + } this->SetNeighborhoodRadius( radius ); }// end SetNeighborhoodRadius @@ -239,10 +239,10 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> ::SetNeighborhoodRadius( const unsigned long *radiusArray) { NeighborhoodRadiusType radius; - for(unsigned int i=0;i < InputImageDimension; ++i) - { - radius[i] = radiusArray[i]; - } + for (unsigned int i=0;i < InputImageDimension; ++i) + { + radius[i] = radiusArray[i]; + } //Set up the neighbor hood this->SetNeighborhoodRadius( radius ); @@ -259,11 +259,11 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> ::SetNeighborhoodRadius( const NeighborhoodRadiusType &radius) { //Set up the neighbor hood - for(unsigned int i=0;i < InputImageDimension; ++i) - { - m_InputImageNeighborhoodRadius[ i ] = radius[ i ]; - m_LabelledImageNeighborhoodRadius[ i ] =radius[ i ]; - } + for (unsigned int i=0;i < InputImageDimension; ++i) + { + m_InputImageNeighborhoodRadius[ i ] = radius[ i ]; + m_LabelledImageNeighborhoodRadius[ i ] =radius[ i ]; + } }// end SetNeighborhoodRadius //------------------------------------------------------- @@ -278,10 +278,10 @@ void MarkovRandomFieldFilter<TInputImage, TClassifiedImage> ::Allocate() { - if( m_NumberOfClasses <= 0 ) - { - throw itk::ExceptionObject(__FILE__, __LINE__,"NumberOfClasses <= 0.",ITK_LOCATION); - } + if ( m_NumberOfClasses <= 0 ) + { + throw itk::ExceptionObject(__FILE__, __LINE__,"NumberOfClasses <= 0.",ITK_LOCATION); + } //Set the output labelled and allocate the memory @@ -294,38 +294,38 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> //Copy input data in the output buffer memory or //initialize to random values if not set LabelledImageRegionIterator - outImageIt( outputPtr, outputPtr->GetRequestedRegion() ); + outImageIt( outputPtr, outputPtr->GetRequestedRegion() ); if (m_ExternalClassificationSet) - { - typename TrainingImageType::ConstPointer trainingImage = this->GetTrainingInput(); - LabelledImageRegionConstIterator - trainingImageIt( trainingImage, outputPtr->GetRequestedRegion() ); - - while ( !outImageIt.IsAtEnd() ) { - LabelledImagePixelType labelvalue = static_cast<LabelledImagePixelType> (trainingImageIt.Get()); + typename TrainingImageType::ConstPointer trainingImage = this->GetTrainingInput(); + LabelledImageRegionConstIterator + trainingImageIt( trainingImage, outputPtr->GetRequestedRegion() ); - outImageIt.Set( labelvalue ); - ++trainingImageIt; - ++outImageIt; - }// end while - } - else //set to random value + while ( !outImageIt.IsAtEnd() ) { -// srand((unsigned)time(0)); + LabelledImagePixelType labelvalue = static_cast<LabelledImagePixelType> (trainingImageIt.Get()); - while ( !outImageIt.IsAtEnd() ) + outImageIt.Set( labelvalue ); + ++trainingImageIt; + ++outImageIt; + }// end while + } + else //set to random value { - LabelledImagePixelType randomvalue = static_cast<LabelledImagePixelType>( - m_Generator->GetIntegerVariate() % static_cast<int>(m_NumberOfClasses) - ); - outImageIt.Set( randomvalue ); - ++outImageIt; - }// end while +// srand((unsigned)time(0)); + while ( !outImageIt.IsAtEnd() ) + { + LabelledImagePixelType randomvalue = static_cast<LabelledImagePixelType>( + m_Generator->GetIntegerVariate() % static_cast<int>(m_NumberOfClasses) + ); + outImageIt.Set( randomvalue ); + ++outImageIt; + }// end while - } + + } }// Allocate @@ -342,7 +342,7 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> m_ImageDeltaEnergy=0.0; InputImageSizeType inputImageSize = - this->GetInput()->GetBufferedRegion().GetSize(); + this->GetInput()->GetBufferedRegion().GetSize(); //--------------------------------------------------------------------- //Get the number of valid pixels in the output MRF image @@ -351,42 +351,42 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> m_TotalNumberOfPixelsInInputImage = 1; m_TotalNumberOfValidPixelsInOutputImage = 1; - for( unsigned int i=0; i < InputImageDimension; i++ ) - { - m_TotalNumberOfPixelsInInputImage *= static_cast<int>(inputImageSize[i]); + for ( unsigned int i=0; i < InputImageDimension; i++ ) + { + m_TotalNumberOfPixelsInInputImage *= static_cast<int>(inputImageSize[i]); - m_TotalNumberOfValidPixelsInOutputImage *= - ( static_cast<int>(inputImageSize[i]) - - 2*m_InputImageNeighborhoodRadius[i] ); - } + m_TotalNumberOfValidPixelsInOutputImage *= + ( static_cast<int>(inputImageSize[i]) + - 2*m_InputImageNeighborhoodRadius[i] ); + } srand((unsigned)time(0)); if ( !m_EnergyRegularization ) - { - itkExceptionMacro(<<"EnergyRegularization is not present" ); - } + { + itkExceptionMacro(<<"EnergyRegularization is not present" ); + } if ( !m_EnergyFidelity ) - { - itkExceptionMacro(<<"EnergyFidelity is not present" ); - } + { + itkExceptionMacro(<<"EnergyFidelity is not present" ); + } if ( !m_Optimizer ) - { - itkExceptionMacro(<<"Optimizer is not present" ); - } + { + itkExceptionMacro(<<"Optimizer is not present" ); + } - if( !m_Sampler ) - { - itkExceptionMacro(<<"Sampler is not present"); - } + if ( !m_Sampler ) + { + itkExceptionMacro(<<"Sampler is not present"); + } - m_Sampler->SetLambda(m_Lambda); - m_Sampler->SetEnergyRegularization(m_EnergyRegularization); - m_Sampler->SetEnergyFidelity(m_EnergyFidelity); - m_Sampler->SetNumberOfClasses(m_NumberOfClasses); + m_Sampler->SetLambda(m_Lambda); + m_Sampler->SetEnergyRegularization(m_EnergyRegularization); + m_Sampler->SetEnergyFidelity(m_EnergyFidelity); + m_Sampler->SetNumberOfClasses(m_NumberOfClasses); } @@ -402,29 +402,29 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> //Note: error should be defined according to the number of valid pixel in the output int maxNumPixelError = (int) ( vnl_math_rnd (m_ErrorTolerance * - m_TotalNumberOfPixelsInInputImage) ); + m_TotalNumberOfPixelsInInputImage) ); m_NumberOfIterations = 0; m_ErrorCounter = m_TotalNumberOfValidPixelsInOutputImage; - while(( m_NumberOfIterations < m_MaximumNumberOfIterations ) && - ( m_ErrorCounter >= maxNumPixelError ) ) - { - otbMsgDebugMacro(<< "Iteration No." << m_NumberOfIterations); + while (( m_NumberOfIterations < m_MaximumNumberOfIterations ) && + ( m_ErrorCounter >= maxNumPixelError ) ) + { + otbMsgDebugMacro(<< "Iteration No." << m_NumberOfIterations); // std::cerr << "Iteration No." << m_NumberOfIterations << std::endl; - this->MinimizeOnce(); + this->MinimizeOnce(); - otbMsgDebugMacro(<< "m_ErrorCounter/m_TotalNumberOfPixelsInInputImage: " - << m_ErrorCounter/((double)(m_TotalNumberOfPixelsInInputImage))); + otbMsgDebugMacro(<< "m_ErrorCounter/m_TotalNumberOfPixelsInInputImage: " + << m_ErrorCounter/((double)(m_TotalNumberOfPixelsInInputImage))); // std::cerr << "m_ErrorCounter/m_TotalNumberOfPixelsInInputImage: " // << m_ErrorCounter/((double)(m_TotalNumberOfPixelsInInputImage)) // << std::endl; // std::cerr << "m_ImageDeltaEnergy: " << m_ImageDeltaEnergy << std::endl; - ++m_NumberOfIterations; + ++m_NumberOfIterations; - } + } otbMsgDebugMacro(<< "m_NumberOfIterations: " << m_NumberOfIterations); otbMsgDebugMacro(<< "m_MaximumNumberOfIterations: " << m_MaximumNumberOfIterations); @@ -436,14 +436,14 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> // std::cerr << "maxNumPixelError: " << maxNumPixelError << std::endl; //Determine stop condition - if( m_NumberOfIterations >= m_MaximumNumberOfIterations ) - { - m_StopCondition = MaximumNumberOfIterations; - } - else if( m_ErrorCounter <= maxNumPixelError ) - { - m_StopCondition = ErrorTolerance; - } + if ( m_NumberOfIterations >= m_MaximumNumberOfIterations ) + { + m_StopCondition = MaximumNumberOfIterations; + } + else if ( m_ErrorCounter <= maxNumPixelError ) + { + m_StopCondition = ErrorTolerance; + } }// ApplyMarkovRandomFieldFilter @@ -457,23 +457,25 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage> ::MinimizeOnce() { LabelledImageNeighborhoodIterator - labelledIterator(m_LabelledImageNeighborhoodRadius, this->GetOutput(), - this->GetOutput()->GetLargestPossibleRegion() ); + labelledIterator(m_LabelledImageNeighborhoodRadius, this->GetOutput(), + this->GetOutput()->GetLargestPossibleRegion() ); InputImageNeighborhoodIterator - dataIterator(m_InputImageNeighborhoodRadius, this->GetInput(), - this->GetInput()->GetLargestPossibleRegion() ); + dataIterator(m_InputImageNeighborhoodRadius, this->GetInput(), + this->GetInput()->GetLargestPossibleRegion() ); m_ErrorCounter = 0; for (labelledIterator.GoToBegin(), dataIterator.GoToBegin(); !labelledIterator.IsAtEnd(); - ++labelledIterator, ++dataIterator){ + ++labelledIterator, ++dataIterator) + { LabelledImagePixelType value; bool changeValueBool; m_Sampler->Compute(dataIterator,labelledIterator); value=m_Sampler->GetValue(); changeValueBool= m_Optimizer->Compute(m_Sampler->GetDeltaEnergy()); - if (changeValueBool){ + if (changeValueBool) + { labelledIterator.SetCenterPixel(value); ++m_ErrorCounter; m_ImageDeltaEnergy += m_Sampler->GetDeltaEnergy(); diff --git a/Code/MultiScale/otbConvexOrConcaveClassificationFilter.h b/Code/MultiScale/otbConvexOrConcaveClassificationFilter.h index 6c7c7cc740f993577270d62803e83d1b773aa5fc..3212bb5db909accebf4e347895e81cf9081e504b 100644 --- a/Code/MultiScale/otbConvexOrConcaveClassificationFilter.h +++ b/Code/MultiScale/otbConvexOrConcaveClassificationFilter.h @@ -22,53 +22,53 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class ConvexOrConcaveDecisionRule - * \brief This functor labels the given pixel between three classes Convex, Concave and Flat. - * - * \par - * This algorithm is based on the following publication: - * \par - * Martino Pesaresi and Jon Alti Benediktsson, Member, IEEE: - * A new approach for the morphological segmentation of high resolution - * satellite imagery. IEEE Transactions on geoscience and remote sensing, vol. 39, - * NO. 2, February 2001, p. 309-320. - * \par - * - * This functor implements the following decision rule to classify a pixel between the three classes - * Convex, Concave and Flat. Let \f$f\f$ denote the input image and \f$\psi_{N}(f)\f$ the geodesic leveling - * of \f$f\f$ with a structuring element of size \f$N\f$. One can derive the following decision rule to - * classify \f$f\f$ into Convex (label \f$\stackrel{\smile}{k}\f$), Concave (label \f$\stackrel{\frown}{k}\f$) - * and Flat (label \f$\bar{k}\f$): - * - * \f[ - * \phi_{N}^{\sigma}=\left\{\begin{array}{lcl} - * \stackrel{\smile}{k} &:& f-\psi_{N}(f)>\sigma\\ - * \stackrel{\frown}{k} &:& \psi_{N}(f)-f>\sigma\\ - * \bar{k}&:&\mid f - \psi_{N}(f) \mid \leq \sigma - * \end{array}\right. - * \f] - * - */ - template<class TInput,class TOutput> - class ConvexOrConcaveDecisionRule - { +{ +/** \class ConvexOrConcaveDecisionRule + * \brief This functor labels the given pixel between three classes Convex, Concave and Flat. + * + * \par + * This algorithm is based on the following publication: + * \par + * Martino Pesaresi and Jon Alti Benediktsson, Member, IEEE: + * A new approach for the morphological segmentation of high resolution + * satellite imagery. IEEE Transactions on geoscience and remote sensing, vol. 39, + * NO. 2, February 2001, p. 309-320. + * \par + * + * This functor implements the following decision rule to classify a pixel between the three classes + * Convex, Concave and Flat. Let \f$f\f$ denote the input image and \f$\psi_{N}(f)\f$ the geodesic leveling + * of \f$f\f$ with a structuring element of size \f$N\f$. One can derive the following decision rule to + * classify \f$f\f$ into Convex (label \f$\stackrel{\smile}{k}\f$), Concave (label \f$\stackrel{\frown}{k}\f$) + * and Flat (label \f$\bar{k}\f$): + * + * \f[ + * \phi_{N}^{\sigma}=\left\{\begin{array}{lcl} + * \stackrel{\smile}{k} &:& f-\psi_{N}(f)>\sigma\\ + * \stackrel{\frown}{k} &:& \psi_{N}(f)-f>\sigma\\ + * \bar{k}&:&\mid f - \psi_{N}(f) \mid \leq \sigma + * \end{array}\right. + * \f] + * + */ +template<class TInput,class TOutput> +class ConvexOrConcaveDecisionRule +{ - public: +public: /** * Constructor */ ConvexOrConcaveDecisionRule() - { - m_ConvexLabel = 1; - m_ConcaveLabel = 2; - m_FlatLabel = 0; - m_Sigma = 0.0; - } + { + m_ConvexLabel = 1; + m_ConcaveLabel = 2; + m_FlatLabel = 0; + m_Sigma = 0.0; + } /** * Destructor */ - ~ConvexOrConcaveDecisionRule(){}; + ~ConvexOrConcaveDecisionRule() {}; /** * Label the pixel to convex, concave or flat * \return The label of the pixel @@ -76,84 +76,84 @@ namespace Functor * \param xlevel The leveling value */ inline TOutput operator()(const TInput& x, const TInput& xlevel) - { - TOutput resp = m_FlatLabel; + { + TOutput resp = m_FlatLabel; - if(static_cast<double>(x-xlevel)>m_Sigma) - { - resp = m_ConvexLabel; - } - else if (static_cast<double>(xlevel-x)>m_Sigma) - { - resp = m_ConcaveLabel; - } - return resp; + if (static_cast<double>(x-xlevel)>m_Sigma) + { + resp = m_ConvexLabel; } + else if (static_cast<double>(xlevel-x)>m_Sigma) + { + resp = m_ConcaveLabel; + } + return resp; + } /** * Set the convex label * \param label the convex label */ void SetConvexLabel(const TOutput& label) - { - m_ConvexLabel=label; - } + { + m_ConvexLabel=label; + } /** * Get the convex label * \return the convex label */ TOutput GetConvexLabel(void) - { - return m_ConvexLabel; - } + { + return m_ConvexLabel; + } /** * Set the concave label * \param label the concave label */ void SetConcaveLabel(const TOutput& label) - { - m_ConcaveLabel=label; - } + { + m_ConcaveLabel=label; + } /** * Get the concave label * \return the concave label */ TOutput GetConcaveLabel(void) - { - return m_ConcaveLabel; - } + { + return m_ConcaveLabel; + } /** * Set the flat label * \param label the flat label */ void SetFlatLabel(const TOutput& label) - { - m_FlatLabel=label; - } + { + m_FlatLabel=label; + } /** * Get the flat label * \return the flat label */ TOutput GetFlatLabel(void) - { - return m_FlatLabel; - } + { + return m_FlatLabel; + } /** * Set the tolerance value * \param sigma the tolerance value */ void SetSigma(const double & sigma) - { - m_Sigma = sigma; - } + { + m_Sigma = sigma; + } /** * Get the tolerance value * \return the tolerance value */ double GetSigma(void) - { - return m_Sigma; - } - private: + { + return m_Sigma; + } +private: /** Label of the convex class */ TOutput m_ConvexLabel; /** Label of the concave class */ @@ -163,8 +163,8 @@ namespace Functor /** Sigma (tolerance) parameter */ double m_Sigma; - }; - } //end namespace Functor +}; +} //end namespace Functor /** \class ConvexOrConcaveClassificationFilter * \brief This filter apply the Convex, Concave and flat classification functor to the whole image. @@ -176,16 +176,16 @@ namespace Functor */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ConvexOrConcaveClassificationFilter - : public itk::BinaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage, - Functor::ConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> > + : public itk::BinaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage, + Functor::ConvexOrConcaveDecisionRule<typename TInputImage::PixelType, + typename TOutputImage::PixelType> > { - public: +public: /** Standard typedefs */ typedef ConvexOrConcaveClassificationFilter Self; typedef itk::BinaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage, - Functor::ConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> > Superclass; + Functor::ConvexOrConcaveDecisionRule<typename TInputImage::PixelType, + typename TOutputImage::PixelType> > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -200,25 +200,25 @@ class ITK_EXPORT ConvexOrConcaveClassificationFilter typedef TOutputImage OutputImageType; typedef typename OutputImageType::PixelType LabelType; typedef Functor::ConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> DecisionFunctorType; + typename TOutputImage::PixelType> DecisionFunctorType; /** * Set the input image * \param image the input image * */ void SetInput(const TInputImage * image) - { - this->SetInput1(image); - } + { + this->SetInput1(image); + } /** * Set the input leveling image * \param leveling the input leveling image * */ void SetInputLeveling(const TInputImage * leveling) - { - this->SetInput2(leveling); - } + { + this->SetInput2(leveling); + } /** Set/Get the convex label */ itkSetMacro(ConvexLabel,LabelType); itkGetMacro(ConvexLabel,LabelType); @@ -234,33 +234,33 @@ class ITK_EXPORT ConvexOrConcaveClassificationFilter /** Set the functor parameters before calling the ThreadedGenerateData() */ virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctor().SetConvexLabel(m_ConvexLabel); - this->GetFunctor().SetConcaveLabel(m_ConcaveLabel); - this->GetFunctor().SetFlatLabel(m_FlatLabel); - this->GetFunctor().SetSigma(m_Sigma); - } + { + this->GetFunctor().SetConvexLabel(m_ConvexLabel); + this->GetFunctor().SetConcaveLabel(m_ConcaveLabel); + this->GetFunctor().SetFlatLabel(m_FlatLabel); + this->GetFunctor().SetSigma(m_Sigma); + } protected: /** Constructor */ ConvexOrConcaveClassificationFilter() - { - m_ConvexLabel = 1; - m_ConcaveLabel = 2; - m_FlatLabel = 0; - m_Sigma = 0.0; - }; + { + m_ConvexLabel = 1; + m_ConcaveLabel = 2; + m_FlatLabel = 0; + m_Sigma = 0.0; + }; /** Destructor */ virtual ~ConvexOrConcaveClassificationFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"ConvexLabel: "<<m_ConvexLabel<<std::endl; - os<<indent<<"ConcaveLabel: "<<m_ConcaveLabel<<std::endl; - os<<indent<<"FlatLabel: "<<m_FlatLabel<<std::endl; - os<<indent<<"Sigma: "<<m_Sigma<<std::endl; - } + { + Superclass::PrintSelf(os,indent); + os<<indent<<"ConvexLabel: "<<m_ConvexLabel<<std::endl; + os<<indent<<"ConcaveLabel: "<<m_ConcaveLabel<<std::endl; + os<<indent<<"FlatLabel: "<<m_FlatLabel<<std::endl; + os<<indent<<"Sigma: "<<m_Sigma<<std::endl; + } private: ConvexOrConcaveClassificationFilter(const Self&); //purposely not implemented diff --git a/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.h b/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.h index 166ac64393ecbb9ed6ee6bf1702e9a90b16667c3..6865523576ebb0d979f8fa28a54f342d1b5b9784 100644 --- a/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.h +++ b/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.h @@ -79,9 +79,9 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TStructuringElement> class ITK_EXPORT GeodesicMorphologyDecompositionImageFilter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> + : public itk::ImageToImageFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef GeodesicMorphologyDecompositionImageFilter Self; typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; @@ -143,7 +143,7 @@ protected: GeodesicMorphologyDecompositionImageFilter(); /** Destructor */ virtual ~GeodesicMorphologyDecompositionImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.txx b/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.txx index 5ac1163a83183ba04c7b6386ae46a314fb6fb118..8224cab53252b14e63205888fb0b1e56a5b41e25 100644 --- a/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.txx +++ b/Code/MultiScale/otbGeodesicMorphologyDecompositionImageFilter.txx @@ -99,11 +99,11 @@ GeodesicMorphologyDecompositionImageFilter<TInputImage,TOutputImage,TStructuring ::GetConvexMap() { if (this->GetNumberOfOutputs() < 2) - { - return 0; - } + { + return 0; + } return static_cast<OutputImageType * > - (this->itk::ProcessObject::GetOutput(1)); + (this->itk::ProcessObject::GetOutput(1)); } /** @@ -115,11 +115,11 @@ GeodesicMorphologyDecompositionImageFilter<TInputImage,TOutputImage,TStructuring ::GetConcaveMap() { if (this->GetNumberOfOutputs() < 3) - { - return 0; - } + { + return 0; + } return static_cast<OutputImageType * > - (this->itk::ProcessObject::GetOutput(2)); + (this->itk::ProcessObject::GetOutput(2)); } /** diff --git a/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.h b/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.h index 8f32c7c53a69e3c1b9d8d49258f944dcbeddadef..6f9f67989cb95779bf52c1398df25a77e415de1a 100644 --- a/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.h +++ b/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.h @@ -62,7 +62,7 @@ namespace otb */ template <class TImage, class TStructuringElement> class ITK_EXPORT GeodesicMorphologyIterativeDecompositionImageFilter - : public ImageToImageListFilter<TImage,TImage> + : public ImageToImageListFilter<TImage,TImage> { public: /** Standard typedefs */ @@ -125,7 +125,7 @@ protected: /** Constructor */ GeodesicMorphologyIterativeDecompositionImageFilter(); /** Destructor */ - ~GeodesicMorphologyIterativeDecompositionImageFilter(){}; + ~GeodesicMorphologyIterativeDecompositionImageFilter() {}; /** Generate output information */ virtual void GenerateOutputInformation(); /** Generate input requested region */ @@ -135,7 +135,7 @@ protected: /** Printself method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** The step for the scale analysis */ unsigned int m_Step; /** The initial value for the scale */ diff --git a/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.txx b/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.txx index 9d44f5d3253a3cac2ffcc900df05d5c036f7189f..c903abbf5170b2afbb62d1495fe4fe362b29936c 100644 --- a/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.txx +++ b/Code/MultiScale/otbGeodesicMorphologyIterativeDecompositionImageFilter.txx @@ -27,199 +27,199 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TImage, class TStructuringElement> - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GeodesicMorphologyIterativeDecompositionImageFilter() - { - this->SetNumberOfRequiredInputs(1); - this->SetNumberOfOutputs(3); - m_NumberOfIterations = 2; - m_InitialValue = 1; - m_Step = 1; - OutputImageListPointerType convList = OutputImageListType::New(); - this->SetNthOutput(0,convList.GetPointer()); - OutputImageListPointerType concList = OutputImageListType::New(); - this->SetNthOutput(1,concList.GetPointer()); - OutputImageListPointerType outputList = OutputImageListType::New(); - this->SetNthOutput(2,outputList.GetPointer()); - } - - template <class TImage, class TStructuringElement> - typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::OutputImageListType* - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GetOutput(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); - } - - template <class TImage, class TStructuringElement> - typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::OutputImageListType* - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GetConvexOutput(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); - } - - template <class TImage, class TStructuringElement> - typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::OutputImageListType* - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GetConcaveOutput(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); - } +/** + * Constructor + */ +template <class TImage, class TStructuringElement> +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GeodesicMorphologyIterativeDecompositionImageFilter() +{ + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfOutputs(3); + m_NumberOfIterations = 2; + m_InitialValue = 1; + m_Step = 1; + OutputImageListPointerType convList = OutputImageListType::New(); + this->SetNthOutput(0,convList.GetPointer()); + OutputImageListPointerType concList = OutputImageListType::New(); + this->SetNthOutput(1,concList.GetPointer()); + OutputImageListPointerType outputList = OutputImageListType::New(); + this->SetNthOutput(2,outputList.GetPointer()); +} + +template <class TImage, class TStructuringElement> +typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::OutputImageListType* +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GetOutput(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); +} + +template <class TImage, class TStructuringElement> +typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::OutputImageListType* +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GetConvexOutput(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); +} + +template <class TImage, class TStructuringElement> +typename GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::OutputImageListType* +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GetConcaveOutput(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); +} - template <class TImage, class TStructuringElement> - void - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GenerateOutputInformation(void) +template <class TImage, class TStructuringElement> +void +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GenerateOutputInformation(void) +{ + // Retrieving input/output pointers + InputImagePointerType inputPtr = this->GetInput(); + OutputImageListPointerType outputPtr = this->GetOutput(); + OutputImageListPointerType convOutputPtr = this->GetConvexOutput(); + OutputImageListPointerType concOutputPtr = this->GetConcaveOutput(); + if (outputPtr) { - // Retrieving input/output pointers - InputImagePointerType inputPtr = this->GetInput(); - OutputImageListPointerType outputPtr = this->GetOutput(); - OutputImageListPointerType convOutputPtr = this->GetConvexOutput(); - OutputImageListPointerType concOutputPtr = this->GetConcaveOutput(); - if(outputPtr) - { - if(outputPtr->Size()!=m_NumberOfIterations) + if (outputPtr->Size()!=m_NumberOfIterations) { // in this case, clear the list outputPtr->Clear(); - for(unsigned int i = 0;i<m_NumberOfIterations;++i) - { - //Create the output image - outputPtr->PushBack(OutputImageType::New()); - } + for (unsigned int i = 0;i<m_NumberOfIterations;++i) + { + //Create the output image + outputPtr->PushBack(OutputImageType::New()); + } } - // For each output image - typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); - while(outputListIt!=outputPtr->End()) + // For each output image + typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); + while (outputListIt!=outputPtr->End()) { //Set the image information outputListIt.Get()->CopyInformation(this->GetInput()); outputListIt.Get()->SetRequestedRegion(this->GetInput()->GetLargestPossibleRegion()); ++outputListIt; } - } - if(convOutputPtr) - { - if(convOutputPtr->Size()!=m_NumberOfIterations) + } + if (convOutputPtr) + { + if (convOutputPtr->Size()!=m_NumberOfIterations) { // in this case, clear the list convOutputPtr->Clear(); - for(unsigned int i = 0;i<m_NumberOfIterations;++i) - { - //Create the output image - convOutputPtr->PushBack(OutputImageType::New()); - } + for (unsigned int i = 0;i<m_NumberOfIterations;++i) + { + //Create the output image + convOutputPtr->PushBack(OutputImageType::New()); + } } - // For each output image - typename OutputImageListType::Iterator outputListIt = convOutputPtr->Begin(); - while(outputListIt!=convOutputPtr->End()) + // For each output image + typename OutputImageListType::Iterator outputListIt = convOutputPtr->Begin(); + while (outputListIt!=convOutputPtr->End()) { //Set the image information outputListIt.Get()->CopyInformation(this->GetInput()); outputListIt.Get()->SetRequestedRegion(this->GetInput()->GetLargestPossibleRegion()); ++outputListIt; } - } - if(concOutputPtr) - { - if(concOutputPtr->Size()!=m_NumberOfIterations) + } + if (concOutputPtr) + { + if (concOutputPtr->Size()!=m_NumberOfIterations) { // in this case, clear the list concOutputPtr->Clear(); - for(unsigned int i = 0;i<m_NumberOfIterations;++i) - { - //Create the output image - concOutputPtr->PushBack(OutputImageType::New()); - } + for (unsigned int i = 0;i<m_NumberOfIterations;++i) + { + //Create the output image + concOutputPtr->PushBack(OutputImageType::New()); + } } - // For each output image - typename OutputImageListType::Iterator outputListIt = concOutputPtr->Begin(); - while(outputListIt!=concOutputPtr->End()) + // For each output image + typename OutputImageListType::Iterator outputListIt = concOutputPtr->Begin(); + while (outputListIt!=concOutputPtr->End()) { //Set the image information outputListIt.Get()->CopyInformation(this->GetInput()); outputListIt.Get()->SetRequestedRegion(this->GetInput()->GetLargestPossibleRegion()); ++outputListIt; } - } } +} - template <class TImage, class TStructuringElement> - void - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GenerateInputRequestedRegion(void) - { - // Retrieving input/output pointers - InputImagePointerType inputPtr = this->GetInput(); - OutputImageListPointerType outputPtr = this->GetOutput(); - - // For each output image - typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); - inputPtr->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); - } - - /** - * Main computation method - */ - template <class TImage, class TStructuringElement> - void - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::GenerateData(void) - { - //Input image pointer - InputImagePointerType current = this->GetInput(); - OutputImageListPointerType outputPtr = this->GetOutput(); - OutputImageListPointerType convOutputPtr = this->GetConvexOutput(); - OutputImageListPointerType concOutputPtr = this->GetConcaveOutput(); +template <class TImage, class TStructuringElement> +void +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GenerateInputRequestedRegion(void) +{ + // Retrieving input/output pointers + InputImagePointerType inputPtr = this->GetInput(); + OutputImageListPointerType outputPtr = this->GetOutput(); - unsigned int i = 0; + // For each output image + typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); + inputPtr->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); +} + +/** + * Main computation method + */ +template <class TImage, class TStructuringElement> +void +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::GenerateData(void) +{ + //Input image pointer + InputImagePointerType current = this->GetInput(); + OutputImageListPointerType outputPtr = this->GetOutput(); + OutputImageListPointerType convOutputPtr = this->GetConvexOutput(); + OutputImageListPointerType concOutputPtr = this->GetConcaveOutput(); - DecompositionFilterPointerType filter; + unsigned int i = 0; - while(i<m_NumberOfIterations) - { - filter = DecompositionFilterType::New(); - typename StructuringElementType::RadiusType radius; - radius.Fill(m_InitialValue+i*m_Step); - filter->SetRadius(radius); - filter->SetInput(current); - filter->GetOutput()->UpdateOutputInformation(); - filter->GetOutput()->SetRequestedRegion(outputPtr->GetNthElement(i)->GetRequestedRegion()); - filter->GetOutput()->PropagateRequestedRegion(); - filter->GetOutput()->UpdateOutputData(); - - outputPtr->SetNthElement(i,filter->GetOutput()); - concOutputPtr->SetNthElement(i,filter->GetConvexMap()); - convOutputPtr->SetNthElement(i,filter->GetConcaveMap()); - - current=filter->GetOutput(); - - ++i; - } + DecompositionFilterPointerType filter; - } - /** - * PrintSelf method - */ - template <class TImage, class TStructuringElement> - void - GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + while (i<m_NumberOfIterations) { - Superclass::PrintSelf(os, indent); - os<<indent<<"NumberOfIterations: "<<m_NumberOfIterations<<std::endl; - os<<indent<<"IntialValue: "<<m_InitialValue<<std::endl; - os<<indent<<"Step: "<<m_Step<<std::endl; + filter = DecompositionFilterType::New(); + typename StructuringElementType::RadiusType radius; + radius.Fill(m_InitialValue+i*m_Step); + filter->SetRadius(radius); + filter->SetInput(current); + filter->GetOutput()->UpdateOutputInformation(); + filter->GetOutput()->SetRequestedRegion(outputPtr->GetNthElement(i)->GetRequestedRegion()); + filter->GetOutput()->PropagateRequestedRegion(); + filter->GetOutput()->UpdateOutputData(); + + outputPtr->SetNthElement(i,filter->GetOutput()); + concOutputPtr->SetNthElement(i,filter->GetConvexMap()); + convOutputPtr->SetNthElement(i,filter->GetConcaveMap()); + + current=filter->GetOutput(); + + ++i; } + +} +/** + * PrintSelf method + */ +template <class TImage, class TStructuringElement> +void +GeodesicMorphologyIterativeDecompositionImageFilter<TImage, TStructuringElement> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os<<indent<<"NumberOfIterations: "<<m_NumberOfIterations<<std::endl; + os<<indent<<"IntialValue: "<<m_InitialValue<<std::endl; + os<<indent<<"Step: "<<m_Step<<std::endl; +} } // End namespace otb #endif diff --git a/Code/MultiScale/otbGeodesicMorphologyLevelingFilter.h b/Code/MultiScale/otbGeodesicMorphologyLevelingFilter.h index 84ffa303d04a0b3dbcc1e67a96691661bca1bec9..660c232b63c1e933c29bc44a0f4d3fa8eccea74d 100644 --- a/Code/MultiScale/otbGeodesicMorphologyLevelingFilter.h +++ b/Code/MultiScale/otbGeodesicMorphologyLevelingFilter.h @@ -24,42 +24,42 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class LevelingFunctor - * \brief This functor performs the pixel-wise leveling operation needed in the - * geodesic morphology decomposition filter. For more details, please refer to - * the documentation of this filter. - * \sa GeodesicMorphologyDecompositionImageFilter - */ - template <class TInput, class TInputMap, class TOutput> - class LevelingFunctor - { - public: +{ +/** \class LevelingFunctor + * \brief This functor performs the pixel-wise leveling operation needed in the + * geodesic morphology decomposition filter. For more details, please refer to + * the documentation of this filter. + * \sa GeodesicMorphologyDecompositionImageFilter + */ +template <class TInput, class TInputMap, class TOutput> +class LevelingFunctor +{ +public: /// Constructor - LevelingFunctor(){}; + LevelingFunctor() {}; /// Destructor - ~LevelingFunctor(){}; + ~LevelingFunctor() {}; inline TOutput operator()(const TInput& pixel, const TInputMap& convexPixel, const TInputMap& concavePixel) + { + TOutput result; + + if (convexPixel>concavePixel) + { + result = static_cast<TOutput>(pixel-convexPixel); + } + else if (convexPixel<concavePixel) { - TOutput result; - - if(convexPixel>concavePixel) - { - result = static_cast<TOutput>(pixel-convexPixel); - } - else if(convexPixel<concavePixel) - { - result = static_cast<TOutput>(concavePixel+pixel); - } - else - { - result = static_cast<TOutput>(pixel); - } - return result; + result = static_cast<TOutput>(concavePixel+pixel); } - }; - }// end namespace Functor + else + { + result = static_cast<TOutput>(pixel); + } + return result; + } +}; +}// end namespace Functor /** \class GeodesicMorphologyLevelingFilter * \brief This filter performs the leveling operation defined in the documentation of @@ -70,20 +70,20 @@ namespace Functor */ template <class TInputImage, class TInputMaps, class TOutputImage> class ITK_EXPORT GeodesicMorphologyLevelingFilter - : public itk::TernaryFunctorImageFilter<TInputImage,TInputImage, - TInputImage,TOutputImage, - Functor::LevelingFunctor<typename TInputImage::PixelType, - typename TInputMaps::PixelType, - typename TOutputImage::PixelType> > + : public itk::TernaryFunctorImageFilter<TInputImage,TInputImage, + TInputImage,TOutputImage, + Functor::LevelingFunctor<typename TInputImage::PixelType, + typename TInputMaps::PixelType, + typename TOutputImage::PixelType> > { - public: +public: /** Standard typedefs */ typedef GeodesicMorphologyLevelingFilter Self; typedef itk::TernaryFunctorImageFilter<TInputImage,TInputImage, - TInputImage,TOutputImage, - Functor::LevelingFunctor<typename TInputImage::PixelType, - typename TInputMaps::PixelType, - typename TOutputImage::PixelType> >Superclass; + TInputImage,TOutputImage, + Functor::LevelingFunctor<typename TInputImage::PixelType, + typename TInputMaps::PixelType, + typename TOutputImage::PixelType> >Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -97,34 +97,34 @@ class ITK_EXPORT GeodesicMorphologyLevelingFilter * Set the convex membership image. */ void SetInputConvexMap(const TInputMaps * convexMap) - { - this->SetInput2(convexMap); - } + { + this->SetInput2(convexMap); + } /** * Set the concave membership image. */ void SetInputConcaveMap(const TInputMaps * concaveMap) - { - this->SetInput3(concaveMap); - } + { + this->SetInput3(concaveMap); + } /** * Set the original input image */ void SetInput(const TInputImage * input) - { - this->SetInput1(input); - } + { + this->SetInput1(input); + } protected: /** Constructor */ - GeodesicMorphologyLevelingFilter(){}; + GeodesicMorphologyLevelingFilter() {}; /** Destructor */ virtual ~GeodesicMorphologyLevelingFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } + { + Superclass::PrintSelf(os,indent); + } private: GeodesicMorphologyLevelingFilter(const Self&); //purposely not implemented diff --git a/Code/MultiScale/otbImageToProfileFilter.h b/Code/MultiScale/otbImageToProfileFilter.h index 93c93b2aa8c4c8160743322d977b8e7310fbb557..0381be66544ca95649dc14a66526a27bbc35b0a6 100644 --- a/Code/MultiScale/otbImageToProfileFilter.h +++ b/Code/MultiScale/otbImageToProfileFilter.h @@ -40,79 +40,79 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TFilter, class TParameter = unsigned int> class ITK_EXPORT ImageToProfileFilter - : public ImageToImageListFilter<TInputImage,TOutputImage> + : public ImageToImageListFilter<TInputImage,TOutputImage> { - public: - /** Standard typedefs */ - typedef ImageToProfileFilter Self; - typedef ImageToImageListFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Type macro */ - itkNewMacro(Self); - - /** Creation through object factory macro */ - itkTypeMacro(ImageToProfileFilter, ImageToImageListFilter); - - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - typedef TParameter ParameterType; - typedef TFilter FilterType; - typedef typename FilterType::Pointer FilterPointerType; - typedef typename Superclass::OutputImageListType OutputImageListType; - typedef typename Superclass::OutputImageListPointerType OutputImageListPointerType; - typedef typename Superclass::InputImagePointer InputImagePointerType; - - /** Get/Set the initial value */ - itkSetMacro(InitialValue,ParameterType); - itkGetMacro(InitialValue,ParameterType); - /** Get/Set the profile size */ - itkSetMacro(ProfileSize,unsigned int); - itkGetMacro(ProfileSize,unsigned int); - /** Get/Set the profile step */ - itkSetMacro(Step,ParameterType); - itkGetMacro(Step,ParameterType); - /** Get/Set the output index */ - itkSetMacro(OutputIndex,unsigned int); - itkGetMacro(OutputIndex,unsigned int); +public: + /** Standard typedefs */ + typedef ImageToProfileFilter Self; + typedef ImageToImageListFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Type macro */ + itkNewMacro(Self); + + /** Creation through object factory macro */ + itkTypeMacro(ImageToProfileFilter, ImageToImageListFilter); + + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef TParameter ParameterType; + typedef TFilter FilterType; + typedef typename FilterType::Pointer FilterPointerType; + typedef typename Superclass::OutputImageListType OutputImageListType; + typedef typename Superclass::OutputImageListPointerType OutputImageListPointerType; + typedef typename Superclass::InputImagePointer InputImagePointerType; + + /** Get/Set the initial value */ + itkSetMacro(InitialValue,ParameterType); + itkGetMacro(InitialValue,ParameterType); + /** Get/Set the profile size */ + itkSetMacro(ProfileSize,unsigned int); + itkGetMacro(ProfileSize,unsigned int); + /** Get/Set the profile step */ + itkSetMacro(Step,ParameterType); + itkGetMacro(Step,ParameterType); + /** Get/Set the output index */ + itkSetMacro(OutputIndex,unsigned int); + itkGetMacro(OutputIndex,unsigned int); protected: - /** - * Set the profile parameter - * \param param The parameter to set - */ - virtual void SetProfileParameter(ParameterType param){}; - /** Get the pointer to the filter */ - itkGetObjectMacro(Filter,FilterType); - /** GenerateData method */ - virtual void GenerateData(void); - /** GenerateOutputInformation method */ - virtual void GenerateOutputInformation(void); - /** Generate input requested region */ - virtual void GenerateInputRequestedRegion(void); - /** Constructor */ - ImageToProfileFilter(); - /** Destructor */ - virtual ~ImageToProfileFilter() {}; - /**PrintSelf method */ - virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Set the profile parameter + * \param param The parameter to set + */ + virtual void SetProfileParameter(ParameterType param) {}; + /** Get the pointer to the filter */ + itkGetObjectMacro(Filter,FilterType); + /** GenerateData method */ + virtual void GenerateData(void); + /** GenerateOutputInformation method */ + virtual void GenerateOutputInformation(void); + /** Generate input requested region */ + virtual void GenerateInputRequestedRegion(void); + /** Constructor */ + ImageToProfileFilter(); + /** Destructor */ + virtual ~ImageToProfileFilter() {}; + /**PrintSelf method */ + virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: ImageToProfileFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - /** The filter used to compute the profile */ - FilterPointerType m_Filter; - /** The profile parameters */ - unsigned int m_ProfileSize; - /** Initial value */ - ParameterType m_InitialValue; - /** Step */ - ParameterType m_Step; - /** The index of the output of the filter used for the profile */ - unsigned int m_OutputIndex; + /** The filter used to compute the profile */ + FilterPointerType m_Filter; + /** The profile parameters */ + unsigned int m_ProfileSize; + /** Initial value */ + ParameterType m_InitialValue; + /** Step */ + ParameterType m_Step; + /** The index of the output of the filter used for the profile */ + unsigned int m_OutputIndex; }; }// End namespace otb diff --git a/Code/MultiScale/otbImageToProfileFilter.txx b/Code/MultiScale/otbImageToProfileFilter.txx index 73b588f99b98f5d6acf847b9f32783de80fbc2f4..b4d5d49b991fcc7b3b1824e2b1190953feaf47a5 100644 --- a/Code/MultiScale/otbImageToProfileFilter.txx +++ b/Code/MultiScale/otbImageToProfileFilter.txx @@ -46,30 +46,30 @@ ImageToProfileFilter<TInputImage,TOutputImage,TFilter,TParameter> // Retrieving input/output pointers InputImagePointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); - if(outputPtr) - { - if(outputPtr->Size()!=m_ProfileSize) + if (outputPtr) { - // in this case, clear the list - outputPtr->Clear(); - for(unsigned int i = 0;i<m_ProfileSize;++i) + if (outputPtr->Size()!=m_ProfileSize) + { + // in this case, clear the list + outputPtr->Clear(); + for (unsigned int i = 0;i<m_ProfileSize;++i) { //Create the output image outputPtr->PushBack(OutputImageType::New()); } - } - // For each output image - typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); - m_Filter->SetInput(inputPtr); - m_Filter->UpdateOutputInformation(); - while(outputListIt!=outputPtr->End()) - { - //Set the image information - outputListIt.Get()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); - outputListIt.Get()->SetLargestPossibleRegion(m_Filter->GetOutput(m_OutputIndex)->GetLargestPossibleRegion()); - ++outputListIt; - } } + // For each output image + typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); + m_Filter->SetInput(inputPtr); + m_Filter->UpdateOutputInformation(); + while (outputListIt!=outputPtr->End()) + { + //Set the image information + outputListIt.Get()->CopyInformation(m_Filter->GetOutput(m_OutputIndex)); + outputListIt.Get()->SetLargestPossibleRegion(m_Filter->GetOutput(m_OutputIndex)->GetLargestPossibleRegion()); + ++outputListIt; + } + } } /** * Generate input requested region @@ -89,12 +89,12 @@ ImageToProfileFilter<TInputImage,TOutputImage,TFilter,TParameter> m_Filter->SetInput(inputPtr); // Use the filter to generate input requested region - while(outputListIt!=outputPtr->End()) - { - m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); - m_Filter->PropagateRequestedRegion(outputListIt.Get()); - ++outputListIt; - } + while (outputListIt!=outputPtr->End()) + { + m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); + m_Filter->PropagateRequestedRegion(outputListIt.Get()); + ++outputListIt; + } } /** * GenerateData method @@ -104,20 +104,20 @@ void ImageToProfileFilter<TInputImage,TOutputImage,TFilter,TParameter> ::GenerateData(void) { - // Retrieving input/output pointers +// Retrieving input/output pointers InputImagePointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); m_Filter->SetInput(inputPtr); - for(unsigned int i = 0;i<m_ProfileSize;++i) - { - ParameterType profileParameter = m_InitialValue + static_cast<ParameterType>(i)*m_Step; - this->SetProfileParameter(profileParameter); - m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputPtr->GetNthElement(i)->GetRequestedRegion()); - m_Filter->Update(); - outputPtr->SetNthElement(i,static_cast<OutputImageType *>(m_Filter->GetOutput(m_OutputIndex))); - outputPtr->GetNthElement(i)->DisconnectPipeline(); - } + for (unsigned int i = 0;i<m_ProfileSize;++i) + { + ParameterType profileParameter = m_InitialValue + static_cast<ParameterType>(i)*m_Step; + this->SetProfileParameter(profileParameter); + m_Filter->GetOutput(m_OutputIndex)->SetRequestedRegion(outputPtr->GetNthElement(i)->GetRequestedRegion()); + m_Filter->Update(); + outputPtr->SetNthElement(i,static_cast<OutputImageType *>(m_Filter->GetOutput(m_OutputIndex))); + outputPtr->GetNthElement(i)->DisconnectPipeline(); + } } /** diff --git a/Code/MultiScale/otbMorphologicalClosingProfileFilter.h b/Code/MultiScale/otbMorphologicalClosingProfileFilter.h index 14615cd6d635ad1894419528494fc1c81648ddd8..c8bca394671b80a328e7f0bf42817c684d1e2f16 100644 --- a/Code/MultiScale/otbMorphologicalClosingProfileFilter.h +++ b/Code/MultiScale/otbMorphologicalClosingProfileFilter.h @@ -45,18 +45,18 @@ namespace otb */ template <class TInputImage,class TOutputImage, class TStructuringElement> class ITK_EXPORT MorphologicalClosingProfileFilter - : public ImageToProfileFilter<TInputImage,TOutputImage, - itk::ClosingByReconstructionImageFilter - <TInputImage, TOutputImage, TStructuringElement>, - unsigned int> + : public ImageToProfileFilter<TInputImage,TOutputImage, + itk::ClosingByReconstructionImageFilter + <TInputImage, TOutputImage, TStructuringElement>, + unsigned int> { - public: +public: /** Standard typedefs */ typedef MorphologicalClosingProfileFilter Self; typedef ImageToProfileFilter<TInputImage,TOutputImage, - itk::ClosingByReconstructionImageFilter - <TInputImage, TOutputImage, TStructuringElement>, - unsigned int> Superclass; + itk::ClosingByReconstructionImageFilter + <TInputImage, TOutputImage, TStructuringElement>, + unsigned int> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -72,21 +72,21 @@ class ITK_EXPORT MorphologicalClosingProfileFilter protected: /** Set the profile parameter */ virtual void SetProfileParameter(ParameterType param) - { - StructuringElementType se; - se.SetRadius(param); - se.CreateStructuringElement(); - this->GetFilter()->SetKernel(se); - }; + { + StructuringElementType se; + se.SetRadius(param); + se.CreateStructuringElement(); + this->GetFilter()->SetKernel(se); + }; /** Constructor */ - MorphologicalClosingProfileFilter(){}; + MorphologicalClosingProfileFilter() {}; /** Destructor */ - virtual ~MorphologicalClosingProfileFilter(){}; - /**PrintSelf method */ + virtual ~MorphologicalClosingProfileFilter() {}; + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: MorphologicalClosingProfileFilter(const Self&); //purposely not implemented diff --git a/Code/MultiScale/otbMorphologicalOpeningProfileFilter.h b/Code/MultiScale/otbMorphologicalOpeningProfileFilter.h index 4907bbe739a2c739b1d9249c493a24846c38b270..ff8d6f78f5efa20549f28bbe5e2466ff03223d42 100644 --- a/Code/MultiScale/otbMorphologicalOpeningProfileFilter.h +++ b/Code/MultiScale/otbMorphologicalOpeningProfileFilter.h @@ -45,18 +45,18 @@ namespace otb */ template <class TInputImage,class TOutputImage, class TStructuringElement> class ITK_EXPORT MorphologicalOpeningProfileFilter - : public ImageToProfileFilter<TInputImage,TOutputImage, - itk::OpeningByReconstructionImageFilter - <TInputImage, TOutputImage, TStructuringElement>, - unsigned int> + : public ImageToProfileFilter<TInputImage,TOutputImage, + itk::OpeningByReconstructionImageFilter + <TInputImage, TOutputImage, TStructuringElement>, + unsigned int> { - public: +public: /** Standard typedefs */ typedef MorphologicalOpeningProfileFilter Self; typedef ImageToProfileFilter<TInputImage,TOutputImage, - itk::OpeningByReconstructionImageFilter - <TInputImage, TOutputImage, TStructuringElement>, - unsigned int> Superclass; + itk::OpeningByReconstructionImageFilter + <TInputImage, TOutputImage, TStructuringElement>, + unsigned int> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -72,21 +72,21 @@ class ITK_EXPORT MorphologicalOpeningProfileFilter protected: /** Set the profile parameter */ virtual void SetProfileParameter(ParameterType param) - { - StructuringElementType se; - se.SetRadius(param); - se.CreateStructuringElement(); - this->GetFilter()->SetKernel(se); - }; + { + StructuringElementType se; + se.SetRadius(param); + se.CreateStructuringElement(); + this->GetFilter()->SetKernel(se); + }; /** Constructor */ - MorphologicalOpeningProfileFilter(){}; + MorphologicalOpeningProfileFilter() {}; /** Destructor */ - virtual ~MorphologicalOpeningProfileFilter(){}; - /**PrintSelf method */ + virtual ~MorphologicalOpeningProfileFilter() {}; + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: MorphologicalOpeningProfileFilter(const Self&); //purposely not implemented diff --git a/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.h b/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.h index 2705b0496167a16a47e0c8080e52e64174ee9af3..2c35e040b821352344a559ee507d761dc65bcb88 100644 --- a/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.h +++ b/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.h @@ -48,7 +48,7 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TMorphoFilter> class ITK_EXPORT MorphologicalPyramidAnalysisFilter - : public ImageToImageListFilter<TInputImage,TOutputImage> + : public ImageToImageListFilter<TInputImage,TOutputImage> { public: /** Standard typedefs */ @@ -115,13 +115,13 @@ protected: MorphologicalPyramidAnalysisFilter(); /** Destructor */ ~MorphologicalPyramidAnalysisFilter(); - virtual void GenerateOutputInformation(){}; // does nothing + virtual void GenerateOutputInformation() {}; // does nothing /** Main computation method */ virtual void GenerateData(); /** Printself method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** Number of levels of the algorithm */ int m_NumberOfLevels; /** Subsampling scale used */ diff --git a/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.txx b/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.txx index 6a8c8ce71d5ef2ce61f80c61846bb63f24fc1d99..b9d564800c78ecc43da22c27df7b38abf19e8513 100644 --- a/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.txx +++ b/Code/MultiScale/otbMorphologicalPyramidAnalysisFilter.txx @@ -31,251 +31,251 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage, TMorphoFilter> - ::MorphologicalPyramidAnalysisFilter() - { - this->SetNumberOfRequiredOutputs(2); - m_DecimationRatio = 2.0; - m_NumberOfLevels = 4; - OutputImageListPointerType supFilter = OutputImageListType::New(); - this->SetNthOutput(0,supFilter.GetPointer()); - OutputImageListPointerType infFilter = OutputImageListType::New(); - this->SetNthOutput(1,infFilter.GetPointer()); - OutputImageListPointerType outputList = OutputImageListType::New(); - this->SetNthOutput(2,outputList.GetPointer()); - OutputImageListPointerType supDeci = OutputImageListType::New(); - this->SetNthOutput(3,supDeci.GetPointer()); - OutputImageListPointerType infDeci = OutputImageListType::New(); - this->SetNthOutput(4,infDeci.GetPointer()); - } - /** - * Destructor - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::~MorphologicalPyramidAnalysisFilter(){} - /** - * Get The Analyse image at each level of the pyramid. - * \return The analysed image at each level of the pyramid. - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::OutputImageListType* - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GetOutput(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); - } - /** - * Get The SupFilter details - * \return The brighter details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::OutputImageListType* - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GetSupFilter(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); - } - /** - * Get The InfFilter details - * \return The darker details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::OutputImageListType* - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GetInfFilter(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); - } - /** - * Get The SupDeci details - * \return The brighter details extracted from the resampling operation. - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::OutputImageListType* - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GetSupDeci(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(3)); - } - /** - * Get The InfDeci details - * \return The brighter details extracted from the resampling operation. - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::OutputImageListType* - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GetInfDeci(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(4)); - } - /** - * Main computation method - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - void - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::GenerateData(void) - { - // Input image pointer - OutputImageListType * OutputImageList = this->GetOutput(); +/** + * Constructor + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage, TMorphoFilter> +::MorphologicalPyramidAnalysisFilter() +{ + this->SetNumberOfRequiredOutputs(2); + m_DecimationRatio = 2.0; + m_NumberOfLevels = 4; + OutputImageListPointerType supFilter = OutputImageListType::New(); + this->SetNthOutput(0,supFilter.GetPointer()); + OutputImageListPointerType infFilter = OutputImageListType::New(); + this->SetNthOutput(1,infFilter.GetPointer()); + OutputImageListPointerType outputList = OutputImageListType::New(); + this->SetNthOutput(2,outputList.GetPointer()); + OutputImageListPointerType supDeci = OutputImageListType::New(); + this->SetNthOutput(3,supDeci.GetPointer()); + OutputImageListPointerType infDeci = OutputImageListType::New(); + this->SetNthOutput(4,infDeci.GetPointer()); +} +/** + * Destructor + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::~MorphologicalPyramidAnalysisFilter() {} +/** + * Get The Analyse image at each level of the pyramid. + * \return The analysed image at each level of the pyramid. + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::OutputImageListType* +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GetOutput(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); +} +/** + * Get The SupFilter details + * \return The brighter details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::OutputImageListType* +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GetSupFilter(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); +} +/** + * Get The InfFilter details + * \return The darker details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::OutputImageListType* +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GetInfFilter(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); +} +/** + * Get The SupDeci details + * \return The brighter details extracted from the resampling operation. + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::OutputImageListType* +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GetSupDeci(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(3)); +} +/** + * Get The InfDeci details + * \return The brighter details extracted from the resampling operation. + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +typename MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::OutputImageListType* +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GetInfDeci(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(4)); +} +/** + * Main computation method + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +void +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::GenerateData(void) +{ + // Input image pointer + OutputImageListType * OutputImageList = this->GetOutput(); - // Output images pointers - OutputImageListType * supFilter = this->GetSupFilter(); - OutputImageListType * infFilter = this->GetInfFilter(); - OutputImageListType * supDeci = this->GetSupDeci(); - OutputImageListType * infDeci = this->GetInfDeci(); + // Output images pointers + OutputImageListType * supFilter = this->GetSupFilter(); + OutputImageListType * infFilter = this->GetInfFilter(); + OutputImageListType * supDeci = this->GetSupDeci(); + OutputImageListType * infDeci = this->GetInfDeci(); - // typedefs of the filters - typedef itk::SubtractImageFilter<InputImageType,InputImageType,OutputImageType> SubtractFilterType; - typedef itk::MaximumImageFilter<InputImageType,InputImageType,InputImageType> MaxFilterType; - typedef itk::ImageDuplicator<InputImageType> DuplicatorType; - typedef otb::MorphologicalPyramid::Resampler<InputImageType,OutputImageType> ResamplerType; + // typedefs of the filters + typedef itk::SubtractImageFilter<InputImageType,InputImageType,OutputImageType> SubtractFilterType; + typedef itk::MaximumImageFilter<InputImageType,InputImageType,InputImageType> MaxFilterType; + typedef itk::ImageDuplicator<InputImageType> DuplicatorType; + typedef otb::MorphologicalPyramid::Resampler<InputImageType,OutputImageType> ResamplerType; - // Input Image duplication to the currentImage Pointer - typename DuplicatorType::Pointer duplicator = DuplicatorType::New(); - duplicator->SetInputImage(this->GetInput()); - duplicator->Update(); - typename InputImageType::Pointer currentImage =duplicator->GetOutput(); - typename InputImageType::Pointer upsampled; + // Input Image duplication to the currentImage Pointer + typename DuplicatorType::Pointer duplicator = DuplicatorType::New(); + duplicator->SetInputImage(this->GetInput()); + duplicator->Update(); + typename InputImageType::Pointer currentImage =duplicator->GetOutput(); + typename InputImageType::Pointer upsampled; - // Structuring element size computation - const int structElementDimension=static_cast<int>(vcl_ceil(this->GetDecimationRatio()/2.)); + // Structuring element size computation + const int structElementDimension=static_cast<int>(vcl_ceil(this->GetDecimationRatio()/2.)); - // Structuring element creation - KernelType structuringElement; - structuringElement.SetRadius(structElementDimension); - structuringElement.CreateStructuringElement(); + // Structuring element creation + KernelType structuringElement; + structuringElement.SetRadius(structElementDimension); + structuringElement.CreateStructuringElement(); - // Filters declarations - typename MorphoFilterType::Pointer morphoFilter; - typename MaxFilterType::Pointer max; - typename SubtractFilterType::Pointer subtract1,subtract2,subtract3,subtract4; - typename ResamplerType::Pointer resampler1, resampler2; + // Filters declarations + typename MorphoFilterType::Pointer morphoFilter; + typename MaxFilterType::Pointer max; + typename SubtractFilterType::Pointer subtract1,subtract2,subtract3,subtract4; + typename ResamplerType::Pointer resampler1, resampler2; - // Size declaration - typename InputImageType::SizeType size; + // Size declaration + typename InputImageType::SizeType size; - // local variables declarations and initialisations - int i = 0; - int sizeTmp; - //--------------------------------------------------------// - // Main loop // - //--------------------------------------------------------// - // While the number of iterations is not reached - otbMsgDevMacro(<<"Entering main loop"); - while(i<this->GetNumberOfLevels()) - { + // local variables declarations and initialisations + int i = 0; + int sizeTmp; + //--------------------------------------------------------// + // Main loop // + //--------------------------------------------------------// + // While the number of iterations is not reached + otbMsgDevMacro(<<"Entering main loop"); + while (i<this->GetNumberOfLevels()) + { - // morphological filtering - morphoFilter = MorphoFilterType::New(); - morphoFilter->SetKernel(structuringElement); - morphoFilter->SetInput(currentImage); - morphoFilter->Update(); + // morphological filtering + morphoFilter = MorphoFilterType::New(); + morphoFilter->SetKernel(structuringElement); + morphoFilter->SetInput(currentImage); + morphoFilter->Update(); - // Maximum between current and filtered image - max=MaxFilterType::New(); - max->SetInput1(morphoFilter->GetOutput()); - max->SetInput2(currentImage); - max->Update(); + // Maximum between current and filtered image + max=MaxFilterType::New(); + max->SetInput1(morphoFilter->GetOutput()); + max->SetInput2(currentImage); + max->Update(); - // SupFilter detail image computation - subtract1 = SubtractFilterType::New(); - subtract1->SetInput1(max->GetOutput()); - subtract1->SetInput2(morphoFilter->GetOutput()); - subtract1->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract1 OK "<<subtract1->GetOutput()->GetLargestPossibleRegion().GetSize()); - supFilter->PushBack(subtract1->GetOutput()); - otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to SupFilter"); + // SupFilter detail image computation + subtract1 = SubtractFilterType::New(); + subtract1->SetInput1(max->GetOutput()); + subtract1->SetInput2(morphoFilter->GetOutput()); + subtract1->Update(); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract1 OK "<<subtract1->GetOutput()->GetLargestPossibleRegion().GetSize()); + supFilter->PushBack(subtract1->GetOutput()); + otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to SupFilter"); - // InfFilter detail image computation - subtract2 = SubtractFilterType::New(); - subtract2->SetInput1(max->GetOutput()); - subtract2->SetInput2(currentImage); - subtract2->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract2 OK "<<subtract2->GetOutput()->GetLargestPossibleRegion().GetSize()); - infFilter->PushBack(subtract2->GetOutput()); - otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to InfFilter"); + // InfFilter detail image computation + subtract2 = SubtractFilterType::New(); + subtract2->SetInput1(max->GetOutput()); + subtract2->SetInput2(currentImage); + subtract2->Update(); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract2 OK "<<subtract2->GetOutput()->GetLargestPossibleRegion().GetSize()); + infFilter->PushBack(subtract2->GetOutput()); + otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to InfFilter"); - // New Size - size = morphoFilter->GetOutput()->GetLargestPossibleRegion().GetSize(); - for (int j =0; j<InputImageType::ImageDimension;j++) + // New Size + size = morphoFilter->GetOutput()->GetLargestPossibleRegion().GetSize(); + for (int j =0; j<InputImageType::ImageDimension;j++) { sizeTmp=size[j]; // As we knwow that our values will always be positive ones, we can simulate round by ceil(value+0.5) size[j]=static_cast<unsigned int>(vcl_ceil((static_cast<double>(sizeTmp)/this->GetDecimationRatio())+0.5)); } - otbMsgDevMacro(<<"New size: "<<size); + otbMsgDevMacro(<<"New size: "<<size); - // Image subsampling - // Current image becomes the newly subsampled image - resampler1 = ResamplerType::New(); - resampler1->SetInput(morphoFilter->GetOutput()); - resampler1->SetSize(size); - resampler1->Update(); - currentImage=resampler1->GetOutput(); + // Image subsampling + // Current image becomes the newly subsampled image + resampler1 = ResamplerType::New(); + resampler1->SetInput(morphoFilter->GetOutput()); + resampler1->SetSize(size); + resampler1->Update(); + currentImage=resampler1->GetOutput(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: DownSampling OK "<<currentImage->GetLargestPossibleRegion().GetSize()); - // New current image is appeneded to the output list - OutputImageList->PushBack(currentImage); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: DownSampling OK "<<currentImage->GetLargestPossibleRegion().GetSize()); + // New current image is appeneded to the output list + OutputImageList->PushBack(currentImage); - // Image upsampling - resampler2 = ResamplerType::New(); - resampler2->SetInput(resampler1->GetOutput()); - resampler2->SetSize(morphoFilter->GetOutput()->GetLargestPossibleRegion().GetSize()); - resampler2->Update(); + // Image upsampling + resampler2 = ResamplerType::New(); + resampler2->SetInput(resampler1->GetOutput()); + resampler2->SetSize(morphoFilter->GetOutput()->GetLargestPossibleRegion().GetSize()); + resampler2->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: UpSampling OK "<<resampler2->GetOutput()->GetLargestPossibleRegion().GetSize()); - // Computation of the details lost in the subsampling operation - max=MaxFilterType::New(); - max->SetInput1(morphoFilter->GetOutput()); - max->SetInput2(resampler2->GetOutput()); - max->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: Max OK "<<max->GetOutput()->GetLargestPossibleRegion().GetSize()); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: UpSampling OK "<<resampler2->GetOutput()->GetLargestPossibleRegion().GetSize()); + // Computation of the details lost in the subsampling operation + max=MaxFilterType::New(); + max->SetInput1(morphoFilter->GetOutput()); + max->SetInput2(resampler2->GetOutput()); + max->Update(); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: Max OK "<<max->GetOutput()->GetLargestPossibleRegion().GetSize()); - // InfDeci detail image computation - subtract4 = SubtractFilterType::New(); - subtract4->SetInput1(max->GetOutput()); - subtract4->SetInput2(morphoFilter->GetOutput()); - subtract4->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract4 OK "<<subtract4->GetOutput()->GetLargestPossibleRegion().GetSize()); - infDeci->PushBack(subtract4->GetOutput()); - otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to InfDeci"); + // InfDeci detail image computation + subtract4 = SubtractFilterType::New(); + subtract4->SetInput1(max->GetOutput()); + subtract4->SetInput2(morphoFilter->GetOutput()); + subtract4->Update(); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract4 OK "<<subtract4->GetOutput()->GetLargestPossibleRegion().GetSize()); + infDeci->PushBack(subtract4->GetOutput()); + otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to InfDeci"); - // SupDeci detail image computation - subtract3 = SubtractFilterType::New(); - subtract3->SetInput1(max->GetOutput()); - subtract3->SetInput2(resampler2->GetOutput()); - subtract3->Update(); - otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract3 OK "<<subtract3->GetOutput()->GetLargestPossibleRegion().GetSize()); - supDeci->PushBack(subtract3->GetOutput()); - otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to SupDeci"); + // SupDeci detail image computation + subtract3 = SubtractFilterType::New(); + subtract3->SetInput1(max->GetOutput()); + subtract3->SetInput2(resampler2->GetOutput()); + subtract3->Update(); + otbMsgDevMacro(<<"MorphologicalPyramidAnalysisFilter: subtract3 OK "<<subtract3->GetOutput()->GetLargestPossibleRegion().GetSize()); + supDeci->PushBack(subtract3->GetOutput()); + otbMsgDevMacro("MorphologicalPyramidAnalysisFilter: step "<<i<<" - Image appended to SupDeci"); - // Iteration ounter incrementation - i++; - } - otbMsgDevMacro(<<"Exiting main loop"); - } - /** - * PrintSelf method - */ - template <class TInputImage, class TOutputImage, class TMorphoFilter> - void - MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); - os << indent << "DecimationRatio: " << m_DecimationRatio << std::endl; - os << indent << "NumberOfLevels: " << m_NumberOfLevels << std::endl; + // Iteration ounter incrementation + i++; } + otbMsgDevMacro(<<"Exiting main loop"); +} +/** + * PrintSelf method + */ +template <class TInputImage, class TOutputImage, class TMorphoFilter> +void +MorphologicalPyramidAnalysisFilter<TInputImage,TOutputImage,TMorphoFilter> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "DecimationRatio: " << m_DecimationRatio << std::endl; + os << indent << "NumberOfLevels: " << m_NumberOfLevels << std::endl; +} } // End namespace otb #endif diff --git a/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.h b/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.h index e9a8ca9c3cb7690a9d512f4ea1062bb91a77cf71..f2e660d0073832a6a462b6e5aa07f84ac53e7aa9 100644 --- a/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.h +++ b/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.h @@ -22,142 +22,142 @@ namespace otb { - namespace MorphologicalPyramid - { - /** - * \class MRToMSConverter - * \brief This class convert a multi resolution decomposition from the morphological pyramid to a multi-scale one. - * - * This class convert a multi resolution decomposition from the morphological pyramid to a multi-scale one. - * - * The operation consists in iterativly upsampling and adding decimation details to a given detail image. - * - * \sa MorphologicalPyramidAnalyseFilter - * \sa MorphologicalPyramidSynthesisFilter - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT MRToMSConverter - : public ImageListToImageListFilter<TInputImage,TOutputImage> - { - public : - /** Standard typedefs */ - typedef MRToMSConverter Self; - typedef ImageListToImageListFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory macro */ - itkNewMacro(Self); - /** Type macro */ - itkTypeMacro(MRToMSConverter,ImageListToImageListFilter); - /** Input parameters typedefs */ - typedef TInputImage InputImageType; - typedef typename Superclass::InputImagePointer InputImagePointer; - typedef typename Superclass::InputImageListType InputImageListType; - typedef typename Superclass::InputImageListPointerType InputImageListPointerType; - typedef typename InputImageListType::Iterator InputImageListIteratorType; - /** Output parameters typedefs */ - typedef TOutputImage OutputImageType; - typedef typename Superclass::OutputImagePointer OutputImagePointerType; - typedef typename Superclass::OutputImageListType OutputImageListType; - typedef typename Superclass::OutputImageListPointerType OutputImageListPointerType; +namespace MorphologicalPyramid +{ +/** + * \class MRToMSConverter + * \brief This class convert a multi resolution decomposition from the morphological pyramid to a multi-scale one. + * + * This class convert a multi resolution decomposition from the morphological pyramid to a multi-scale one. + * + * The operation consists in iterativly upsampling and adding decimation details to a given detail image. + * + * \sa MorphologicalPyramidAnalyseFilter + * \sa MorphologicalPyramidSynthesisFilter + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT MRToMSConverter + : public ImageListToImageListFilter<TInputImage,TOutputImage> +{ +public : + /** Standard typedefs */ + typedef MRToMSConverter Self; + typedef ImageListToImageListFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory macro */ + itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(MRToMSConverter,ImageListToImageListFilter); + /** Input parameters typedefs */ + typedef TInputImage InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputImageListType InputImageListType; + typedef typename Superclass::InputImageListPointerType InputImageListPointerType; + typedef typename InputImageListType::Iterator InputImageListIteratorType; + /** Output parameters typedefs */ + typedef TOutputImage OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointerType; + typedef typename Superclass::OutputImageListType OutputImageListType; + typedef typename Superclass::OutputImageListPointerType OutputImageListPointerType; - /** - * Set The input list. - * \param imageList The analysed image at each level of the pyramid. - */ - void SetInput(InputImageListType * imageList); - /** - * Set The SupFilter details - * \param imageList The brighter details extracted from the filtering operation. - */ - void SetSupFilter(InputImageListType * imageList); - /** - * Set The InfFilter details - * \param imageList The darker details extracted from the filtering operation. - */ - void SetInfFilter(InputImageListType * imageList); - /** - * Set The SupDeci details - * \param imageList The brighter details extracted from the filtering operation. - */ - void SetSupDeci(InputImageListType * imageList); - /** - * Set The InfDeci details - * \param imageList The darker details extracted from the filtering operation. - */ - void SetInfDeci(InputImageListType * imageList); - /** - * Get the input list. - * \return The list of the analysed image at each pyramid level. - */ - InputImageListType* GetInput(void); - /** - * Get The SupFilter details - * \return The brighter details extracted from the filtering operation. - */ - InputImageListType* GetSupFilter(void); - /** - * Get The InfFilter details - * \return The darker details extracted from the filtering operation. - */ - InputImageListType* GetInfFilter(void); - /** - * Get The SupDeci details - * \return The brighter details extracted from the resampling operation. - */ - InputImageListType* GetSupDeci(void); - /** - * Get The InfDeci details - * \return The brighter details extracted from the resampling operation. - */ - InputImageListType* GetInfDeci(void); - /** - * Get The inputList at full resolution. - * \return The analysed image at each pyramid level - * resampled at full resolution. - */ - OutputImageListType* GetOutput(void); - /** - * Get The SupFilter details at full resolution. - * \return The brighter details extracted from the filtering operation - * resampled at full resolution. - */ - OutputImageListType * GetSupFilterFullResolution(void); - /** - * Get The InfFilter details at full resolution. - * \return The darker details extracted from the filtering operation - * resampled at full resolution. - */ - OutputImageListType * GetInfFilterFullResolution(void); - /** - * Get The SupDeci details at full resolution. - * \return The brighter details extracted from the resampling operation - * resampled at full resolution. - */ - OutputImageListType * GetSupDeciFullResolution(void); - /** - * Get The InfDeci details at full resolution. - * \return The darker details extracted from the resampling operation - * resampled at full resolution. - */ - OutputImageListType * GetInfDeciFullResolution(void); + /** + * Set The input list. + * \param imageList The analysed image at each level of the pyramid. + */ + void SetInput(InputImageListType * imageList); + /** + * Set The SupFilter details + * \param imageList The brighter details extracted from the filtering operation. + */ + void SetSupFilter(InputImageListType * imageList); + /** + * Set The InfFilter details + * \param imageList The darker details extracted from the filtering operation. + */ + void SetInfFilter(InputImageListType * imageList); + /** + * Set The SupDeci details + * \param imageList The brighter details extracted from the filtering operation. + */ + void SetSupDeci(InputImageListType * imageList); + /** + * Set The InfDeci details + * \param imageList The darker details extracted from the filtering operation. + */ + void SetInfDeci(InputImageListType * imageList); + /** + * Get the input list. + * \return The list of the analysed image at each pyramid level. + */ + InputImageListType* GetInput(void); + /** + * Get The SupFilter details + * \return The brighter details extracted from the filtering operation. + */ + InputImageListType* GetSupFilter(void); + /** + * Get The InfFilter details + * \return The darker details extracted from the filtering operation. + */ + InputImageListType* GetInfFilter(void); + /** + * Get The SupDeci details + * \return The brighter details extracted from the resampling operation. + */ + InputImageListType* GetSupDeci(void); + /** + * Get The InfDeci details + * \return The brighter details extracted from the resampling operation. + */ + InputImageListType* GetInfDeci(void); + /** + * Get The inputList at full resolution. + * \return The analysed image at each pyramid level + * resampled at full resolution. + */ + OutputImageListType* GetOutput(void); + /** + * Get The SupFilter details at full resolution. + * \return The brighter details extracted from the filtering operation + * resampled at full resolution. + */ + OutputImageListType * GetSupFilterFullResolution(void); + /** + * Get The InfFilter details at full resolution. + * \return The darker details extracted from the filtering operation + * resampled at full resolution. + */ + OutputImageListType * GetInfFilterFullResolution(void); + /** + * Get The SupDeci details at full resolution. + * \return The brighter details extracted from the resampling operation + * resampled at full resolution. + */ + OutputImageListType * GetSupDeciFullResolution(void); + /** + * Get The InfDeci details at full resolution. + * \return The darker details extracted from the resampling operation + * resampled at full resolution. + */ + OutputImageListType * GetInfDeciFullResolution(void); - protected: - /** Constructor */ - MRToMSConverter(); - /** Destructor */ - ~MRToMSConverter() {}; +protected: + /** Constructor */ + MRToMSConverter(); + /** Destructor */ + ~MRToMSConverter() {}; - /** Main computation method */ - void GenerateData(); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** Main computation method */ + void GenerateData(); + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : - MRToMSConverter(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - }; - } // End namespace MorphologicalPyramid +private : + MRToMSConverter(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented +}; +} // End namespace MorphologicalPyramid }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.txx b/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.txx index faedced8f7c76deb682b301027e502823b45d0ae..a496ba0d604ec6c5311a06fcaf86a61d3dca9da9 100644 --- a/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.txx +++ b/Code/MultiScale/otbMorphologicalPyramidMRToMSConverter.txx @@ -24,247 +24,247 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace MorphologicalPyramid - { - /** - * Constructor - */ - template <class TInputImage,class TOutputImage> - MRToMSConverter<TInputImage, TOutputImage> - ::MRToMSConverter() - { - this->SetNumberOfRequiredInputs(2); - this->SetNumberOfRequiredOutputs(2); - OutputImageListPointerType supFilter = OutputImageListType::New(); - this->SetNthOutput(0,supFilter.GetPointer()); - OutputImageListPointerType infFilter = OutputImageListType::New(); - this->SetNthOutput(1,infFilter.GetPointer()); - OutputImageListPointerType outputList = OutputImageListType::New(); - this->SetNthOutput(2,outputList.GetPointer()); - OutputImageListPointerType supDeci = OutputImageListType::New(); - this->SetNthOutput(3,supDeci.GetPointer()); - OutputImageListPointerType infDeci = OutputImageListType::New(); - this->SetNthOutput(4,infDeci.GetPointer()); - } - /** - * Get The inputList at full resolution. - * \return The analysed image at each pyramid level - * resampled at full resolution. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::OutputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetOutput(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); - } - /** - * Get The SupFilter details at full resolution. - * \return The brighter details extracted from the filtering operation. - * resampled at full resolution. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::OutputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetSupFilterFullResolution(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); - } - /** - * Get The InfFilter details at full resolution. - * \return The darker details extracted from the filtering operation. - * resampled at full resolution. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::OutputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetInfFilterFullResolution(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); - } - /** - * Get The SupDeci details at full resolution. - * \return The brighter details extracted from the resampling operation. - * resampled at full resolution. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::OutputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetSupDeciFullResolution(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(3)); - } - /** - * Get The InfDeci details at full resolution. - * \return The brighter details extracted from the resampling operation. - * resampled at full resolution. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::OutputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetInfDeciFullResolution(void) - { - return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(4)); - } - /** - * Set The input list. - * \param imageList The analysed image at each level of the pyramid. - */ - template <class TInputImage, class TOutputImage> - void - MRToMSConverter<TInputImage,TOutputImage> - ::SetInput(InputImageListType * imageList) - { - this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); - } - /** - * Set The SupFilter details - * \param imageList The brighter details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage> - void - MRToMSConverter<TInputImage,TOutputImage> - ::SetSupFilter(InputImageListType * imageList) - { - this->SetNthInput(0,const_cast<InputImageListType *>(imageList)); - } - /** - * Set The InfFilter details - * \param imageList The darker details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage> - void - MRToMSConverter<TInputImage,TOutputImage> - ::SetInfFilter(InputImageListType * imageList) - { - this->SetNthInput(1,const_cast<InputImageListType *>(imageList)); - } - /** - * Set The SupDeci details - * \param imageList The brighter details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage> - void - MRToMSConverter<TInputImage,TOutputImage> - ::SetSupDeci(InputImageListType * imageList) - { - this->SetNthInput(3,const_cast<InputImageListType *>(imageList)); - } - /** - * Set The InfDeci details - * \param imageList The darker details extracted from the filtering operation. - */ - template <class TInputImage, class TOutputImage> - void - MRToMSConverter<TInputImage,TOutputImage> - ::SetInfDeci(InputImageListType * imageList) - { - this->SetNthInput(4,const_cast<InputImageListType *>(imageList)); - } - /** - * Get the input list. - * \return The list of the analysed image at each pyramid level. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::InputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetInput(void) - { - return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(2)); - } - /** - * Get The SupFilter details. - * \return The brighter details extracted from the filtering operation - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::InputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetSupFilter(void) - { - return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(0)); - } - /** - * Get The InfFilter details. - * \return The darker details extracted from the filtering operation - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::InputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetInfFilter(void) - { - return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(1)); - } - /** - * Get The SupDeci details. - * \return The brighter details extracted from the resampling operation - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::InputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetSupDeci(void) - { - return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(3)); - } - /** - * Get The InfDeci details. - * \return The darker details extracted from the resampling operation. - */ - template <class TInputImage, class TOutputImage> - typename MRToMSConverter<TInputImage,TOutputImage> - ::InputImageListType* - MRToMSConverter<TInputImage,TOutputImage> - ::GetInfDeci(void) - { - return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(4)); - } - /** - * Main computation method - */ - template <class TInputImage,class TOutputImage> - void - MRToMSConverter<TInputImage, TOutputImage> - ::GenerateData() - { - // Input images lists pointers - InputImageListPointerType supFilter = this->GetSupFilter(); - InputImageListPointerType infFilter = this->GetInfFilter(); - InputImageListPointerType supDeci = this->GetSupDeci(); - InputImageListPointerType infDeci = this->GetInfDeci(); - InputImageListPointerType inputList = this->GetInput(); +namespace MorphologicalPyramid +{ +/** + * Constructor + */ +template <class TInputImage,class TOutputImage> +MRToMSConverter<TInputImage, TOutputImage> +::MRToMSConverter() +{ + this->SetNumberOfRequiredInputs(2); + this->SetNumberOfRequiredOutputs(2); + OutputImageListPointerType supFilter = OutputImageListType::New(); + this->SetNthOutput(0,supFilter.GetPointer()); + OutputImageListPointerType infFilter = OutputImageListType::New(); + this->SetNthOutput(1,infFilter.GetPointer()); + OutputImageListPointerType outputList = OutputImageListType::New(); + this->SetNthOutput(2,outputList.GetPointer()); + OutputImageListPointerType supDeci = OutputImageListType::New(); + this->SetNthOutput(3,supDeci.GetPointer()); + OutputImageListPointerType infDeci = OutputImageListType::New(); + this->SetNthOutput(4,infDeci.GetPointer()); +} +/** + * Get The inputList at full resolution. + * \return The analysed image at each pyramid level + * resampled at full resolution. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::OutputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetOutput(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(2)); +} +/** + * Get The SupFilter details at full resolution. + * \return The brighter details extracted from the filtering operation. + * resampled at full resolution. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::OutputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetSupFilterFullResolution(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(0)); +} +/** + * Get The InfFilter details at full resolution. + * \return The darker details extracted from the filtering operation. + * resampled at full resolution. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::OutputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetInfFilterFullResolution(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(1)); +} +/** + * Get The SupDeci details at full resolution. + * \return The brighter details extracted from the resampling operation. + * resampled at full resolution. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::OutputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetSupDeciFullResolution(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(3)); +} +/** + * Get The InfDeci details at full resolution. + * \return The brighter details extracted from the resampling operation. + * resampled at full resolution. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::OutputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetInfDeciFullResolution(void) +{ + return dynamic_cast<OutputImageListType*>(this->itk::ProcessObject::GetOutput(4)); +} +/** + * Set The input list. + * \param imageList The analysed image at each level of the pyramid. + */ +template <class TInputImage, class TOutputImage> +void +MRToMSConverter<TInputImage,TOutputImage> +::SetInput(InputImageListType * imageList) +{ + this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); +} +/** + * Set The SupFilter details + * \param imageList The brighter details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage> +void +MRToMSConverter<TInputImage,TOutputImage> +::SetSupFilter(InputImageListType * imageList) +{ + this->SetNthInput(0,const_cast<InputImageListType *>(imageList)); +} +/** + * Set The InfFilter details + * \param imageList The darker details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage> +void +MRToMSConverter<TInputImage,TOutputImage> +::SetInfFilter(InputImageListType * imageList) +{ + this->SetNthInput(1,const_cast<InputImageListType *>(imageList)); +} +/** + * Set The SupDeci details + * \param imageList The brighter details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage> +void +MRToMSConverter<TInputImage,TOutputImage> +::SetSupDeci(InputImageListType * imageList) +{ + this->SetNthInput(3,const_cast<InputImageListType *>(imageList)); +} +/** + * Set The InfDeci details + * \param imageList The darker details extracted from the filtering operation. + */ +template <class TInputImage, class TOutputImage> +void +MRToMSConverter<TInputImage,TOutputImage> +::SetInfDeci(InputImageListType * imageList) +{ + this->SetNthInput(4,const_cast<InputImageListType *>(imageList)); +} +/** + * Get the input list. + * \return The list of the analysed image at each pyramid level. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::InputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetInput(void) +{ + return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(2)); +} +/** + * Get The SupFilter details. + * \return The brighter details extracted from the filtering operation + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::InputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetSupFilter(void) +{ + return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(0)); +} +/** + * Get The InfFilter details. + * \return The darker details extracted from the filtering operation + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::InputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetInfFilter(void) +{ + return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(1)); +} +/** + * Get The SupDeci details. + * \return The brighter details extracted from the resampling operation + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::InputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetSupDeci(void) +{ + return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(3)); +} +/** + * Get The InfDeci details. + * \return The darker details extracted from the resampling operation. + */ +template <class TInputImage, class TOutputImage> +typename MRToMSConverter<TInputImage,TOutputImage> +::InputImageListType* +MRToMSConverter<TInputImage,TOutputImage> +::GetInfDeci(void) +{ + return dynamic_cast<InputImageListType *>(this->itk::ProcessObject::GetInput(4)); +} +/** + * Main computation method + */ +template <class TInputImage,class TOutputImage> +void +MRToMSConverter<TInputImage, TOutputImage> +::GenerateData() +{ + // Input images lists pointers + InputImageListPointerType supFilter = this->GetSupFilter(); + InputImageListPointerType infFilter = this->GetInfFilter(); + InputImageListPointerType supDeci = this->GetSupDeci(); + InputImageListPointerType infDeci = this->GetInfDeci(); + InputImageListPointerType inputList = this->GetInput(); - // Output images lists pointers - OutputImageListPointerType supFilterFullResolution = this->GetSupFilterFullResolution(); - OutputImageListPointerType infFilterFullResolution = this->GetInfFilterFullResolution(); - OutputImageListPointerType supDeciFullResolution = this->GetSupDeciFullResolution(); - OutputImageListPointerType infDeciFullResolution = this->GetInfDeciFullResolution(); - OutputImageListPointerType outputList = this->GetOutput(); + // Output images lists pointers + OutputImageListPointerType supFilterFullResolution = this->GetSupFilterFullResolution(); + OutputImageListPointerType infFilterFullResolution = this->GetInfFilterFullResolution(); + OutputImageListPointerType supDeciFullResolution = this->GetSupDeciFullResolution(); + OutputImageListPointerType infDeciFullResolution = this->GetInfDeciFullResolution(); + OutputImageListPointerType outputList = this->GetOutput(); - // typedef of the resampling filter - typedef otb::MorphologicalPyramid::Resampler<InputImageType,OutputImageType> ResamplerType; + // typedef of the resampling filter + typedef otb::MorphologicalPyramid::Resampler<InputImageType,OutputImageType> ResamplerType; - // Definition of the resampler filters - typename ResamplerType::Pointer resampler; + // Definition of the resampler filters + typename ResamplerType::Pointer resampler; - // Full resolution size - typename InputImageType::SizeType frsize = supFilter->Front()->GetLargestPossibleRegion().GetSize(); - otbMsgDevMacro(<<"MRToMSConverter: Full resolution size: "<<frsize); + // Full resolution size + typename InputImageType::SizeType frsize = supFilter->Front()->GetLargestPossibleRegion().GetSize(); + otbMsgDevMacro(<<"MRToMSConverter: Full resolution size: "<<frsize); - // SupFilter resampling - otbMsgDevMacro(<<"MRToMSConverter: SupFilter resampling."); - InputImageListIteratorType it = supFilter->Begin(); - // The first image does not need any resampling - supFilterFullResolution->PushBack(it.Get()); - ++it; - for(;it!=supFilter->End();++it) + // SupFilter resampling + otbMsgDevMacro(<<"MRToMSConverter: SupFilter resampling."); + InputImageListIteratorType it = supFilter->Begin(); + // The first image does not need any resampling + supFilterFullResolution->PushBack(it.Get()); + ++it; + for (;it!=supFilter->End();++it) { resampler = ResamplerType::New(); resampler->SetSize(frsize); @@ -272,13 +272,13 @@ namespace otb resampler->Update(); supFilterFullResolution->PushBack(resampler->GetOutput()); } - otbMsgDevMacro(<<"MRToMSConverter: InfFilter resampling."); - // InfFilter resampling - it = infFilter->Begin(); - // The first image does not need any resampling - infFilterFullResolution->PushBack(it.Get()); - ++it; - for(;it!=infFilter->End();++it) + otbMsgDevMacro(<<"MRToMSConverter: InfFilter resampling."); + // InfFilter resampling + it = infFilter->Begin(); + // The first image does not need any resampling + infFilterFullResolution->PushBack(it.Get()); + ++it; + for (;it!=infFilter->End();++it) { resampler = ResamplerType::New(); resampler->SetSize(frsize); @@ -287,7 +287,7 @@ namespace otb infFilterFullResolution->PushBack(resampler->GetOutput()); } - if(inputList) + if (inputList) { otbMsgDevMacro(<<"MRToMSConverter: Optional inputList resampling."); // Analyse image resampling @@ -295,17 +295,17 @@ namespace otb // The first image does not need any resampling outputList->PushBack(it.Get()); ++it; - for(;it!=inputList->End();++it) - { - resampler = ResamplerType::New(); - resampler->SetSize(frsize); - resampler->SetInput(it.Get()); - resampler->Update(); - outputList->PushBack(resampler->GetOutput()); - } + for (;it!=inputList->End();++it) + { + resampler = ResamplerType::New(); + resampler->SetSize(frsize); + resampler->SetInput(it.Get()); + resampler->Update(); + outputList->PushBack(resampler->GetOutput()); + } } - if(supDeci) + if (supDeci) { otbMsgDevMacro(<<"MRToMSConverter: Optional supDeci resampling."); // SupDeci resampling @@ -313,17 +313,17 @@ namespace otb // The first image does not need any resampling supDeciFullResolution->PushBack(it.Get()); ++it; - for(;it!=supDeci->End();++it) - { - resampler = ResamplerType::New(); - resampler->SetSize(frsize); - resampler->SetInput(it.Get()); - resampler->Update(); - supDeciFullResolution->PushBack(resampler->GetOutput()); - } + for (;it!=supDeci->End();++it) + { + resampler = ResamplerType::New(); + resampler->SetSize(frsize); + resampler->SetInput(it.Get()); + resampler->Update(); + supDeciFullResolution->PushBack(resampler->GetOutput()); + } } - if(infDeci) + if (infDeci) { otbMsgDevMacro(<<"MRToMSConverter: Optional infDeci resampling."); // InfDeci resampling @@ -331,26 +331,26 @@ namespace otb // The first image does not need any resampling infDeciFullResolution->PushBack(it.Get()); ++it; - for(;it!=infDeci->End();++it) - { - resampler = ResamplerType::New(); - resampler->SetSize(frsize); - resampler->SetInput(it.Get()); - resampler->Update(); - infDeciFullResolution->PushBack(resampler->GetOutput()); - } - } - } - /** - * PrintSelf method - */ - template <class TInputImage,class TOutputImage> - void - MRToMSConverter<TInputImage, TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + for (;it!=infDeci->End();++it) { - Superclass::PrintSelf(os,indent); + resampler = ResamplerType::New(); + resampler->SetSize(frsize); + resampler->SetInput(it.Get()); + resampler->Update(); + infDeciFullResolution->PushBack(resampler->GetOutput()); } - } // End namespace MorphologicalPyramid + } +} +/** + * PrintSelf method + */ +template <class TInputImage,class TOutputImage> +void +MRToMSConverter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} +} // End namespace MorphologicalPyramid } // End namespace otb #endif diff --git a/Code/MultiScale/otbMorphologicalPyramidResampler.h b/Code/MultiScale/otbMorphologicalPyramidResampler.h index 1c11a486ab958ea36c2cd3b8018bdb36d2289a2b..347b9451fc0283e33277e8460ce6c978d2a1f1ea 100644 --- a/Code/MultiScale/otbMorphologicalPyramidResampler.h +++ b/Code/MultiScale/otbMorphologicalPyramidResampler.h @@ -22,74 +22,74 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace MorphologicalPyramid - { - /** - * \class Resampler - * \brief This class performs the resampling of the given image to the given size. - * - * This class performs the resampling of the given image to the given size.It is used - * in the MorphologicalPyramidAnalyseFilter and MorphologicalPyramidSynthesisFilter. - * - * The resampling is done by the itk::ResampleImageFilter, templated with the interpolator - * itk::LinearInterpolateImageFunction and the transform itk::ScaleTransform. - * - * \sa MorphologicalPyramidAnalyseFilter - * \sa MorphologicalPyramidSynthesisFilter - * \sa ResampleImageFilter - * \sa LinearInterpolateImageFunction - * \sa ScaleTransform - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT Resampler - : public itk::ImageToImageFilter<TInputImage,TOutputImage> - { - public : - /** Standard typedefs */ - typedef Resampler Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory macro */ - itkNewMacro(Self); - /** Type macro */ - itkTypeMacro(Resampler,ImageToImageFilter); - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointer; - typedef typename InputImageType::Pointer InputImagePointer; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename TInputImage::PixelType PixelType; - typedef typename InputImageType::ConstPointer InputImageConstPointer; - typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::SpacingType SpacingType; - /** Size parameter accessor */ - itkSetMacro(Size,SizeType); - itkGetMacro(Size,SizeType); +namespace MorphologicalPyramid +{ +/** + * \class Resampler + * \brief This class performs the resampling of the given image to the given size. + * + * This class performs the resampling of the given image to the given size.It is used + * in the MorphologicalPyramidAnalyseFilter and MorphologicalPyramidSynthesisFilter. + * + * The resampling is done by the itk::ResampleImageFilter, templated with the interpolator + * itk::LinearInterpolateImageFunction and the transform itk::ScaleTransform. + * + * \sa MorphologicalPyramidAnalyseFilter + * \sa MorphologicalPyramidSynthesisFilter + * \sa ResampleImageFilter + * \sa LinearInterpolateImageFunction + * \sa ScaleTransform + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT Resampler + : public itk::ImageToImageFilter<TInputImage,TOutputImage> +{ +public : + /** Standard typedefs */ + typedef Resampler Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory macro */ + itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(Resampler,ImageToImageFilter); + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename TInputImage::PixelType PixelType; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename OutputImageType::SizeType SizeType; + typedef typename OutputImageType::SpacingType SpacingType; + /** Size parameter accessor */ + itkSetMacro(Size,SizeType); + itkGetMacro(Size,SizeType); - protected: - /** Constructor */ - Resampler(); - /** Destructor */ - ~Resampler() {}; - /** Generate output information */ - virtual void GenerateOutputInformation(); - /** Configure input requested region to be the largest possible region */ - virtual void GenerateInputRequestedRegion(); - /** Configure output requested region to be the largest possible region */ - virtual void EnlargeOutputRequestedRegion(itk::DataObject *itkNotUsed(output)); - /** Main computation method */ - void GenerateData(); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : - Resampler(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - /// Output image size - SizeType m_Size; - }; - } // End namespace MorphologicalPyramid +protected: + /** Constructor */ + Resampler(); + /** Destructor */ + ~Resampler() {}; + /** Generate output information */ + virtual void GenerateOutputInformation(); + /** Configure input requested region to be the largest possible region */ + virtual void GenerateInputRequestedRegion(); + /** Configure output requested region to be the largest possible region */ + virtual void EnlargeOutputRequestedRegion(itk::DataObject *itkNotUsed(output)); + /** Main computation method */ + void GenerateData(); + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; +private : + Resampler(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + /// Output image size + SizeType m_Size; +}; +} // End namespace MorphologicalPyramid }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/MultiScale/otbMorphologicalPyramidResampler.txx b/Code/MultiScale/otbMorphologicalPyramidResampler.txx index ccdd9640b1b4120070ddf5ab6ed680153aa1e944..a120fc02e5c578863a362b0e663893dd32c3b10b 100644 --- a/Code/MultiScale/otbMorphologicalPyramidResampler.txx +++ b/Code/MultiScale/otbMorphologicalPyramidResampler.txx @@ -37,14 +37,14 @@ template <class TInputImage,class TOutputImage> Resampler<TInputImage, TOutputImage> ::Resampler() { - for(int i=0;i<InputImageType::ImageDimension;++i) + for (int i=0;i<InputImageType::ImageDimension;++i) { - m_Size[i]=0; + m_Size[i]=0; } } - /** - * Configure input requested region to be the largest possible region. - */ +/** + * Configure input requested region to be the largest possible region. + */ template <class TInputImage,class TOutputImage> void Resampler<TInputImage, TOutputImage> @@ -57,10 +57,10 @@ Resampler<TInputImage, TOutputImage> OutputImagePointer outputPtr = this->GetOutput(); // If the pointers are not correct if ( !inputPtr || !outputPtr ) - { + { // exit return; - } + } // else // Configure input requested region to be the largest possible region inputPtr->SetRequestedRegion( inputPtr->GetLargestPossibleRegion()); @@ -88,22 +88,22 @@ Resampler<TInputImage,TOutputImage> // Input and output image pointers retrieval InputImageConstPointer inputPtr = this->GetInput(); OutputImagePointer outputPtr = this->GetOutput(); - // If the pointers are not correct + // If the pointers are not correct if ( !inputPtr || !outputPtr ) - { + { // exit return; - } + } unsigned int i; // Computing output spacing, size and index from input data const typename InputImageType::SpacingType& inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::IndexType& inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); typename OutputImageType::IndexType outputStartIndex; typename OutputImageType::SpacingType spacing; - for (i = 0; i < OutputImageType::ImageDimension; i++) - { - outputStartIndex[i] = inputStartIndex[i]; - } + for (i = 0; i < OutputImageType::ImageDimension; i++) + { + outputStartIndex[i] = inputStartIndex[i]; + } // Affectation du spacing � l'image de sortie outputPtr->SetSpacing( inputSpacing ); // G�n�ration de la r�gion de l'image de sortie diff --git a/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.h b/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.h index 5f4cbc6fa93a33974b4c8d76a4f21e881e1aa881..94f6795b0ed6e5afe7832e96db8240bf989ce091 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.h +++ b/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.h @@ -54,7 +54,7 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT MorphologicalPyramidSegmentationFilter - : public ImageListToImageListFilter<TInputImage,TOutputImage> + : public ImageListToImageListFilter<TInputImage,TOutputImage> { public: /** Standard typedefs */ @@ -137,12 +137,12 @@ protected: MorphologicalPyramidSegmentationFilter(); /** Destructor */ ~MorphologicalPyramidSegmentationFilter(); - virtual void GenerateOutputInformation(){}; // does nothing + virtual void GenerateOutputInformation() {}; // does nothing /** Main computation method */ virtual void GenerateData(); /** Printself method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: unsigned long m_MinimumObjectSize; /** Quantile for seeds determination */ double m_SeedsQuantile; diff --git a/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.txx b/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.txx index fadbe9ea6ebc09807f47390235b672fb20634a3a..10c633702f524b9b6741ce89e2557b661000db9b 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.txx +++ b/Code/MultiScale/otbMorphologicalPyramidSegmentationFilter.txx @@ -79,7 +79,7 @@ void MorphologicalPyramidSegmentationFilter<TInputImage,TOutputImage> ::SetDarkerDetails(InputImageListType * imageList) { -this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); + this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); } /** * Get the reference image @@ -166,35 +166,35 @@ MorphologicalPyramidSegmentationFilter<TInputImage,TOutputImage> // Segmentation filter definition typename InputImageListType::Iterator it; // Segment the supFilter details - for(it= brighter->Begin();it!=brighter->End();++it) - { - typename SegmenterType::Pointer segmenter = SegmenterType::New(); - segmenter->SetMinimumObjectSize(m_MinimumObjectSize); - segmenter->SetSeedsQuantile(m_SeedsQuantile); - segmenter->SetConnectedThresholdQuantile(m_ConnectedThresholdQuantile); - segmenter->SetOriginalImage(referenceImage); - segmenter->SetDetailsImage(it.Get()); - segmenter->Update(); - m_NumberOfObjectsVector.push_back(segmenter->GetNumberOfObjects()); - outputList->PushBack(segmenter->GetOutput()); - } + for (it= brighter->Begin();it!=brighter->End();++it) + { + typename SegmenterType::Pointer segmenter = SegmenterType::New(); + segmenter->SetMinimumObjectSize(m_MinimumObjectSize); + segmenter->SetSeedsQuantile(m_SeedsQuantile); + segmenter->SetConnectedThresholdQuantile(m_ConnectedThresholdQuantile); + segmenter->SetOriginalImage(referenceImage); + segmenter->SetDetailsImage(it.Get()); + segmenter->Update(); + m_NumberOfObjectsVector.push_back(segmenter->GetNumberOfObjects()); + outputList->PushBack(segmenter->GetOutput()); + } // Segment the infFilter details - for(it= darker->Begin();it!= darker->End();++it) - { - typename SegmenterType::Pointer segmenter = SegmenterType::New(); - segmenter->SetMinimumObjectSize(m_MinimumObjectSize); - segmenter->SetSeedsQuantile(m_SeedsQuantile); - segmenter->SetConnectedThresholdQuantile(m_ConnectedThresholdQuantile); - segmenter->SetOriginalImage(referenceImage); - segmenter->SetSegmentDarkDetailsBool(true); - - segmenter->SetDetailsImage(it.Get()); - segmenter->Update(); - m_NumberOfObjectsVector.push_back(segmenter->GetNumberOfObjects()); - outputList->PushBack(segmenter->GetOutput()); - } + for (it= darker->Begin();it!= darker->End();++it) + { + typename SegmenterType::Pointer segmenter = SegmenterType::New(); + segmenter->SetMinimumObjectSize(m_MinimumObjectSize); + segmenter->SetSeedsQuantile(m_SeedsQuantile); + segmenter->SetConnectedThresholdQuantile(m_ConnectedThresholdQuantile); + segmenter->SetOriginalImage(referenceImage); + segmenter->SetSegmentDarkDetailsBool(true); + + segmenter->SetDetailsImage(it.Get()); + segmenter->Update(); + m_NumberOfObjectsVector.push_back(segmenter->GetNumberOfObjects()); + outputList->PushBack(segmenter->GetOutput()); + } } /** * PrintSelf method diff --git a/Code/MultiScale/otbMorphologicalPyramidSegmenter.h b/Code/MultiScale/otbMorphologicalPyramidSegmenter.h index ae95c4aca3d21412f0fadea0b4de1a1e17cd947d..324a99eb277cf3fcb9332ef93e36c4cdfefdd6f6 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSegmenter.h +++ b/Code/MultiScale/otbMorphologicalPyramidSegmenter.h @@ -22,128 +22,128 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - namespace MorphologicalPyramid - { - /** - * \class Segmenter - * \brief This class performs the segmentation of a detail image extracted from a - * morphological pyramid analysis. - * - * This class performs the segmentation of a detail image extracted from a - * morphological pyramid analysis. - * - * The Segmentation is perfomed using the ConnectedThresholdImageFilter. The seeds - * are extracted from the image using the ImageToPointSetFilter. The thresolds are set - * by using quantiles computed with the HistogramGenerator. - * - * \sa MorphologicalPyramidAnalyseFilter - * \sa MorphologicalPyramidSynthesisFilter - * \sa ResampleImageFilter - * \sa LinearInterpolateImageFunction - * \sa ScaleTransform - */ - template <class TInputImage, class TOutputImage> - class ITK_EXPORT Segmenter - : public itk::ImageToImageFilter<TInputImage,TOutputImage> - { - public : - /** Standard typedefs */ - typedef Segmenter Self; - typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Creation through object factory macro */ - itkNewMacro(Self); - /** Type macro */ - itkTypeMacro(Segmenter,ImageToImageFilter); - /** Template parameters typedefs */ - typedef TInputImage InputImageType; - typedef typename InputImageType::PixelType InputPixelType; - typedef typename InputImageType::Pointer InputImagePointerType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointerType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::SpacingType SpacingType; +namespace MorphologicalPyramid +{ +/** + * \class Segmenter + * \brief This class performs the segmentation of a detail image extracted from a + * morphological pyramid analysis. + * + * This class performs the segmentation of a detail image extracted from a + * morphological pyramid analysis. + * + * The Segmentation is perfomed using the ConnectedThresholdImageFilter. The seeds + * are extracted from the image using the ImageToPointSetFilter. The thresolds are set + * by using quantiles computed with the HistogramGenerator. + * + * \sa MorphologicalPyramidAnalyseFilter + * \sa MorphologicalPyramidSynthesisFilter + * \sa ResampleImageFilter + * \sa LinearInterpolateImageFunction + * \sa ScaleTransform + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT Segmenter + : public itk::ImageToImageFilter<TInputImage,TOutputImage> +{ +public : + /** Standard typedefs */ + typedef Segmenter Self; + typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Creation through object factory macro */ + itkNewMacro(Self); + /** Type macro */ + itkTypeMacro(Segmenter,ImageToImageFilter); + /** Template parameters typedefs */ + typedef TInputImage InputImageType; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::Pointer InputImagePointerType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointerType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::SizeType SizeType; + typedef typename OutputImageType::SpacingType SpacingType; - /** ImageDimension constants */ - itkStaticConstMacro(DetailsImageDimension, unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OriginalImageDimension, unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension); - /** - * Set the details image. - * \param detailsImage The details image from the morphological pyramid - */ - void SetDetailsImage(const InputImageType * detailsImage); - /** - * Get the details image. - * \return detailsImage The input details image. - */ - InputImageType * GetDetailsImage(void); - /** - * Set the original image. - * \param originalImage The original image to segment. - */ - void SetOriginalImage(const InputImageType * originalImage); - /** - * Get the original image. - * \return originalImage The original image to segment. - */ - InputImageType * GetOriginalImage(void); + /** ImageDimension constants */ + itkStaticConstMacro(DetailsImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OriginalImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension); + /** + * Set the details image. + * \param detailsImage The details image from the morphological pyramid + */ + void SetDetailsImage(const InputImageType * detailsImage); + /** + * Get the details image. + * \return detailsImage The input details image. + */ + InputImageType * GetDetailsImage(void); + /** + * Set the original image. + * \param originalImage The original image to segment. + */ + void SetOriginalImage(const InputImageType * originalImage); + /** + * Get the original image. + * \return originalImage The original image to segment. + */ + InputImageType * GetOriginalImage(void); - /** Min object size parameter accessor */ - itkSetMacro(MinimumObjectSize,unsigned long); - itkGetMacro(MinimumObjectSize,unsigned long); - /** Quantile for seeds extraction */ - itkSetMacro(SeedsQuantile,double); - itkGetMacro(SeedsQuantile,double); - /** Quantile for connected thresholding */ - itkSetMacro(ConnectedThresholdQuantile,double); - itkGetMacro(ConnectedThresholdQuantile,double); - /** Toogle the darker detail segmentation */ - itkSetMacro(SegmentDarkDetailsBool,bool); - itkGetMacro(SegmentDarkDetailsBool,bool); - itkBooleanMacro(SegmentDarkDetailsBool); - /** Get the number of segmented objects */ - itkGetMacro(NumberOfObjects,OutputPixelType); + /** Min object size parameter accessor */ + itkSetMacro(MinimumObjectSize,unsigned long); + itkGetMacro(MinimumObjectSize,unsigned long); + /** Quantile for seeds extraction */ + itkSetMacro(SeedsQuantile,double); + itkGetMacro(SeedsQuantile,double); + /** Quantile for connected thresholding */ + itkSetMacro(ConnectedThresholdQuantile,double); + itkGetMacro(ConnectedThresholdQuantile,double); + /** Toogle the darker detail segmentation */ + itkSetMacro(SegmentDarkDetailsBool,bool); + itkGetMacro(SegmentDarkDetailsBool,bool); + itkBooleanMacro(SegmentDarkDetailsBool); + /** Get the number of segmented objects */ + itkGetMacro(NumberOfObjects,OutputPixelType); - protected: - /** Constructor */ - Segmenter(); - /** Destructor */ - ~Segmenter() {}; - /** Main computation method */ - void GenerateData(void); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Configure the input datas. - */ - void GenerateInputRequestedRegion(void); - /** - * Configure the output data. - */ - void EnlargeOutputRequestedRegion(void); +protected: + /** Constructor */ + Segmenter(); + /** Destructor */ + ~Segmenter() {}; + /** Main computation method */ + void GenerateData(void); + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Configure the input datas. + */ + void GenerateInputRequestedRegion(void); + /** + * Configure the output data. + */ + void EnlargeOutputRequestedRegion(void); - private : - Segmenter(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - /** Minimum size for the segmented object */ - unsigned long m_MinimumObjectSize; - /** Quantile for seeds determination */ - double m_SeedsQuantile; - /** Quantile to set the connectedThresholdFilter threshold */ - double m_ConnectedThresholdQuantile; - /** Set to true if the details to segment are darker than background */ - bool m_SegmentDarkDetailsBool; - /** Number of segmented objects */ - OutputPixelType m_NumberOfObjects; - }; - } // End namespace MorphologicalPyramid +private : + Segmenter(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + /** Minimum size for the segmented object */ + unsigned long m_MinimumObjectSize; + /** Quantile for seeds determination */ + double m_SeedsQuantile; + /** Quantile to set the connectedThresholdFilter threshold */ + double m_ConnectedThresholdQuantile; + /** Set to true if the details to segment are darker than background */ + bool m_SegmentDarkDetailsBool; + /** Number of segmented objects */ + OutputPixelType m_NumberOfObjects; +}; +} // End namespace MorphologicalPyramid }// End namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/MultiScale/otbMorphologicalPyramidSegmenter.txx b/Code/MultiScale/otbMorphologicalPyramidSegmenter.txx index 71a62c22e1d8f377b07068322baaf501306de66c..888ba03c9400322bd793e0c0b48761fdfe6e2aa1 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSegmenter.txx +++ b/Code/MultiScale/otbMorphologicalPyramidSegmenter.txx @@ -60,12 +60,12 @@ void Segmenter<TInputImage, TOutputImage> ::SetDetailsImage(const InputImageType * detailsImage) { -this->SetNthInput(0,const_cast<TInputImage *>(detailsImage)); + this->SetNthInput(0,const_cast<TInputImage *>(detailsImage)); } - /** - * Set the details image. - * \return detailsImage The input details image. - */ +/** + * Set the details image. + * \return detailsImage The input details image. + */ template <class TInputImage,class TOutputImage> typename Segmenter<TInputImage, TOutputImage>::InputImageType * Segmenter<TInputImage, TOutputImage> @@ -73,10 +73,10 @@ Segmenter<TInputImage, TOutputImage> { return const_cast<InputImageType *>(this->GetInput(0)); } - /** - * Set the original image. - * \param originalImage The original image to segment. - */ +/** + * Set the original image. + * \param originalImage The original image to segment. + */ template <class TInputImage,class TOutputImage> void Segmenter<TInputImage, TOutputImage> @@ -114,9 +114,9 @@ Segmenter<TInputImage, TOutputImage> const_cast< InputImageType * >( this->GetInput(1) ); if ( !detailsPtr || !origPtr ) - { + { return; - } + } // We need to // configure the inputs such that all the data is available. @@ -132,7 +132,7 @@ Segmenter<TInputImage, TOutputImage> ::EnlargeOutputRequestedRegion(void) { this->GetOutput() - ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); } /** @@ -190,17 +190,17 @@ Segmenter<TInputImage, TOutputImage> // If we want to segment darker detail, the original image must have its itensity inverted - if(m_SegmentDarkDetailsBool) - { - invert = InvertFilterType::New(); - invert->SetInput(original); - invert->SetMaximum(minMax->GetMaximum()); - cast2->SetInput(invert->GetOutput()); - } + if (m_SegmentDarkDetailsBool) + { + invert = InvertFilterType::New(); + invert->SetInput(original); + invert->SetMaximum(minMax->GetMaximum()); + cast2->SetInput(invert->GetOutput()); + } else - { - cast2->SetInput(original); - } + { + cast2->SetInput(original); + } mult->SetInput1(cast1->GetOutput()); mult->SetInput2(cast2->GetOutput()); mult->Update(); @@ -252,14 +252,14 @@ Segmenter<TInputImage, TOutputImage> connectedThreshold->ClearSeeds(); connectedThreshold->SetInput(mult->GetOutput()); PointSetIteratorType it = pointSetFilter->GetOutput()->GetPoints()->Begin(); - while(it!=pointSetFilter->GetOutput()->GetPoints()->End()) - { - typename OutputImageType::IndexType index; - index[0]=static_cast<long int>(it.Value()[0]); - index[1]=static_cast<long int>(it.Value()[1]); - connectedThreshold->AddSeed(index); - it++; - } + while (it!=pointSetFilter->GetOutput()->GetPoints()->End()) + { + typename OutputImageType::IndexType index; + index[0]=static_cast<long int>(it.Value()[0]); + index[1]=static_cast<long int>(it.Value()[1]); + connectedThreshold->AddSeed(index); + it++; + } // segmentation connectedThreshold->SetLower(connectedThresholdValue); @@ -277,23 +277,23 @@ Segmenter<TInputImage, TOutputImage> threshold = ThresholdFilterType::New(); threshold->SetInput(relabeler->GetOutput()); OutputPixelType num = 0; - if(relabeler->GetNumberOfObjects()==1) - { - unsigned int surface = mult->GetOutput()->GetLargestPossibleRegion().GetSize()[0] - *mult->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; - if(relabeler->GetSizeOfObjectsInPixels()[0]==surface) - { - num = 0; - } - else + if (relabeler->GetNumberOfObjects()==1) { - num=1; - } + unsigned int surface = mult->GetOutput()->GetLargestPossibleRegion().GetSize()[0] + *mult->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; + if (relabeler->GetSizeOfObjectsInPixels()[0]==surface) + { + num = 0; } - else + else { - num= static_cast<OutputPixelType>(relabeler->GetNumberOfObjects()); + num=1; } + } + else + { + num= static_cast<OutputPixelType>(relabeler->GetNumberOfObjects()); + } threshold->ThresholdOutside(0,num); // Output connection diff --git a/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.h b/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.h index 26bad9a9f6a144eeb4e197a9c782aee8dda901ca..c5d2c7d11a8095bc06d72482617904e5ca2f4f08 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.h +++ b/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.h @@ -42,10 +42,10 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT MorphologicalPyramidSynthesisFilter - : public ImageToImageListFilter<TInputImage,TOutputImage> + : public ImageToImageListFilter<TInputImage,TOutputImage> { public: -/** Standard typedefs */ + /** Standard typedefs */ typedef MorphologicalPyramidSynthesisFilter Self; typedef ImageToImageListFilter<TInputImage,TOutputImage> Superclass; typedef itk::SmartPointer<Self> Pointer; @@ -124,7 +124,7 @@ protected: MorphologicalPyramidSynthesisFilter(); /** Destructor */ ~MorphologicalPyramidSynthesisFilter(); - virtual void GenerateOutputInformation(){}; // does nothing + virtual void GenerateOutputInformation() {}; // does nothing /** Main computation method */ virtual void GenerateData(); /** Printself method */ diff --git a/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.txx b/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.txx index b419943eea51eab576f19fd0e5fb36a52b746c2f..44ab9d0ef8fbed7ae83786d7d37242f537c65f23 100644 --- a/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.txx +++ b/Code/MultiScale/otbMorphologicalPyramidSynthesisFilter.txx @@ -54,39 +54,39 @@ MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> { this->SetNthInput(1,const_cast<InputImageListType *>(imageList)); } - /** - * Set The InfFilter details - * \param imageList The darker details extracted from the filtering operation. - */ +/** + * Set The InfFilter details + * \param imageList The darker details extracted from the filtering operation. + */ template <class TInputImage, class TOutputImage> void MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> ::SetInfFilter(InputImageListType * imageList) { -this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); + this->SetNthInput(2,const_cast<InputImageListType *>(imageList)); } - /** - * Set The SupDeci details - * \param imageList The brighter details extracted from the filtering operation. - */ +/** + * Set The SupDeci details + * \param imageList The brighter details extracted from the filtering operation. + */ template <class TInputImage, class TOutputImage> void MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> ::SetSupDeci(InputImageListType * imageList) { -this->SetNthInput(3,const_cast<InputImageListType *>(imageList)); + this->SetNthInput(3,const_cast<InputImageListType *>(imageList)); } - /** - * Set The InfDeci details - * \param imageList The darker details extracted from the filtering operation. - */ +/** + * Set The InfDeci details + * \param imageList The darker details extracted from the filtering operation. + */ template <class TInputImage, class TOutputImage> void MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> ::SetInfDeci(InputImageListType * imageList) { -this->SetNthInput(4,const_cast<InputImageListType *>(imageList)); + this->SetNthInput(4,const_cast<InputImageListType *>(imageList)); } /** @@ -182,11 +182,11 @@ MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> ImageListIterator it = supFilter->Begin(); - while(it!=supFilter->End()) - { - size.push_back(it.Get()->GetLargestPossibleRegion().GetSize()); - ++it; - } + while (it!=supFilter->End()) + { + size.push_back(it.Get()->GetLargestPossibleRegion().GetSize()); + ++it; + } otbMsgDevMacro(<<"MorphologicalPyramidSynthesisFilter : Size vector computation OK"); // Iterators definition @@ -197,18 +197,18 @@ MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> SizeReverseIterator itSize = size.rbegin(); int i =1; - //--------------------------------------------------------// +//--------------------------------------------------------// // Main loop // //--------------------------------------------------------// - while( itinfFilter!=infFilter->ReverseEnd() - && itsupFilter!=supFilter->ReverseEnd() - && itinfDeci!=infDeci->ReverseEnd() - && itsupDeci!=supDeci->ReverseEnd() - && itSize!=size.rend()) - { + while ( itinfFilter!=infFilter->ReverseEnd() + && itsupFilter!=supFilter->ReverseEnd() + && itinfDeci!=infDeci->ReverseEnd() + && itsupDeci!=supDeci->ReverseEnd() + && itSize!=size.rend()) + { - ++i; - // Upsampling current image + ++i; + // Upsampling current image resampler = ResamplerType::New(); resampler->SetSize(*itSize); resampler->SetInput(currentImage); @@ -243,9 +243,9 @@ MorphologicalPyramidSynthesisFilter<TInputImage,TOutputImage> ++itsupDeci; ++itinfDeci; ++itSize; - } - otbMsgDevMacro(<<"MorphologicalPyramidSynthesisFilter: Exiting main method."); } + otbMsgDevMacro(<<"MorphologicalPyramidSynthesisFilter: Exiting main method."); +} /** * PrintSelf method */ diff --git a/Code/MultiScale/otbMultiScaleConvexOrConcaveClassificationFilter.h b/Code/MultiScale/otbMultiScaleConvexOrConcaveClassificationFilter.h index fff68b5afc57ae20431c6ffb0e8ee022865ba4a2..d62b2048afffec66aed00899405cc8dc5ba76437 100644 --- a/Code/MultiScale/otbMultiScaleConvexOrConcaveClassificationFilter.h +++ b/Code/MultiScale/otbMultiScaleConvexOrConcaveClassificationFilter.h @@ -22,53 +22,53 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class MultiScaleConvexOrConcaveDecisionRule - * \brief This Functor apply a classification rule on two membership value along with two labels. - * - * \par - * This algorithm is based on the following publication: - * \par - * Martino Pesaresi and Jon Alti Benediktsson, Member, IEEE: - * A new approach for the morphological segmentation of high resolution - * satellite imagery. IEEE Transactions on geoscience and remote sensing, vol. 39, - * NO. 2, February 2001, p. 309-320. - * \par - * - * Given \f$x_1\f$ and \f$x_2\f$ two membership values, \f$L_1,L_2\f$ two labels associated, - * and \f$\sigma\f$ a tolerance value, the following decision rule is applied: - * - * \f[ - * L=\left\{\begin{array}{lcl} - * L_{1} &:& x_{1}>x_{2} \quad and \quad x_{1}>\sigma\\ - * L_{2} &:& x_{2}>x_{1} \quad and \quad x_{2}>\sigma\\ - * 0 &:& otherwise. - * \end{array}\right. - * \f] - * - * To help the distinction between \f$L_{1}\f$ labels and \f$L_{2}\f$, - * this functor adds the m_LabelSeparators value to the \f$L_{1}\f$ labels. - * - * This functor is the decision rule used for multi-scale classification using - * morphological profiles. - */ - template<class TInput,class TLabeled> - class MultiScaleConvexOrConcaveDecisionRule - { - - public: +{ +/** \class MultiScaleConvexOrConcaveDecisionRule + * \brief This Functor apply a classification rule on two membership value along with two labels. + * + * \par + * This algorithm is based on the following publication: + * \par + * Martino Pesaresi and Jon Alti Benediktsson, Member, IEEE: + * A new approach for the morphological segmentation of high resolution + * satellite imagery. IEEE Transactions on geoscience and remote sensing, vol. 39, + * NO. 2, February 2001, p. 309-320. + * \par + * + * Given \f$x_1\f$ and \f$x_2\f$ two membership values, \f$L_1,L_2\f$ two labels associated, + * and \f$\sigma\f$ a tolerance value, the following decision rule is applied: + * + * \f[ + * L=\left\{\begin{array}{lcl} + * L_{1} &:& x_{1}>x_{2} \quad and \quad x_{1}>\sigma\\ + * L_{2} &:& x_{2}>x_{1} \quad and \quad x_{2}>\sigma\\ + * 0 &:& otherwise. + * \end{array}\right. + * \f] + * + * To help the distinction between \f$L_{1}\f$ labels and \f$L_{2}\f$, + * this functor adds the m_LabelSeparators value to the \f$L_{1}\f$ labels. + * + * This functor is the decision rule used for multi-scale classification using + * morphological profiles. + */ +template<class TInput,class TLabeled> +class MultiScaleConvexOrConcaveDecisionRule +{ + +public: /** * Constructor */ MultiScaleConvexOrConcaveDecisionRule() - { - m_Sigma = 0.0; - m_LabelSeparator = 10; - } + { + m_Sigma = 0.0; + m_LabelSeparator = 10; + } /** * Destructor */ - ~MultiScaleConvexOrConcaveDecisionRule(){}; + ~MultiScaleConvexOrConcaveDecisionRule() {}; /** * Label the pixel to convex, concave or flat * \return The label of the pixel @@ -78,60 +78,60 @@ namespace Functor * \param cloDeChar The characteristic of the closing profile */ inline TLabeled operator()(const TInput& opDeMax, const TInput& cloDeMax,const TLabeled& opDeChar, const TLabeled& cloDeChar) + { + TLabeled resp = 0; + + if ( opDeMax>cloDeMax && static_cast<double>(opDeMax)>m_Sigma) + { + resp = m_LabelSeparator + opDeChar; + } + else if (cloDeMax>opDeMax && static_cast<double>(cloDeMax)>m_Sigma) { - TLabeled resp = 0; - - if( opDeMax>cloDeMax && static_cast<double>(opDeMax)>m_Sigma) - { - resp = m_LabelSeparator + opDeChar; - } - else if (cloDeMax>opDeMax && static_cast<double>(cloDeMax)>m_Sigma) - { - resp = cloDeChar; - } - return resp; + resp = cloDeChar; } + return resp; + } /** * Set the tolerance value * \param sigma the tolerance value */ void SetSigma(const double & sigma) - { - m_Sigma = sigma; - } + { + m_Sigma = sigma; + } /** * Get the tolerance value * \return the tolerance value */ double GetSigma(void) - { - return m_Sigma; - } + { + return m_Sigma; + } /** * Set the label separator * \param labelSeparator the label separator */ void SetLabelSeparator(const TLabeled& labelSeparator) - { - m_LabelSeparator = labelSeparator; - } + { + m_LabelSeparator = labelSeparator; + } /** * Get the label separator * \return the label separator */ TLabeled GetLabelSeparator(void) - { - return m_LabelSeparator; - } + { + return m_LabelSeparator; + } - private: +private: /** Sigma (tolerance) parameter */ double m_Sigma; /** Seperate between convex and concave labels */ TLabeled m_LabelSeparator; - }; - } //end namespace Functor +}; +} //end namespace Functor /** \class MultiScaleConvexOrConcaveClassificationFilter * \brief Apply the MultiScaleConvexOrConcaveDecisionRule to whole images. @@ -141,16 +141,16 @@ namespace Functor */ template <class TInputImage, class TOutputImage> class ITK_EXPORT MultiScaleConvexOrConcaveClassificationFilter - : public QuaternaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage,TOutputImage,TOutputImage, - Functor::MultiScaleConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> > + : public QuaternaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage,TOutputImage,TOutputImage, + Functor::MultiScaleConvexOrConcaveDecisionRule<typename TInputImage::PixelType, + typename TOutputImage::PixelType> > { - public: +public: /** Standard typedefs */ typedef MultiScaleConvexOrConcaveClassificationFilter Self; typedef QuaternaryFunctorImageFilter<TInputImage,TInputImage, TOutputImage,TOutputImage,TOutputImage, - Functor::MultiScaleConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> >Superclass; + Functor::MultiScaleConvexOrConcaveDecisionRule<typename TInputImage::PixelType, + typename TOutputImage::PixelType> >Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -165,43 +165,43 @@ class ITK_EXPORT MultiScaleConvexOrConcaveClassificationFilter typedef TOutputImage OutputImageType; typedef typename OutputImageType::PixelType LabelType; typedef Functor::MultiScaleConvexOrConcaveDecisionRule<typename TInputImage::PixelType, - typename TOutputImage::PixelType> DecisionFunctorType; + typename TOutputImage::PixelType> DecisionFunctorType; /** * Set the opening profile derivative maxima image * \param derivativeMaxima the opening profile derivative maxima image * */ void SetOpeningProfileDerivativeMaxima(const TInputImage * derivativeMaxima) - { - this->SetInput1(derivativeMaxima); - } + { + this->SetInput1(derivativeMaxima); + } /** * Set the opening profile characteristics image * \param characteristics the opening profile characteristics image * */ void SetOpeningProfileCharacteristics(const TOutputImage * characteristics) - { - this->SetInput3(characteristics); - } + { + this->SetInput3(characteristics); + } /** * Set the closing profile derivative maxima image * \param derivativeMaxima the closing profile derivative maxima image * */ void SetClosingProfileDerivativeMaxima(const TInputImage * derivativeMaxima) - { - this->SetInput2(derivativeMaxima); - } + { + this->SetInput2(derivativeMaxima); + } /** * Set the closing profile characteristics image * \param characteristics the closing profile characteristics image * */ void SetClosingProfileCharacteristics(const TOutputImage * characteristics) - { - this->SetInput4(characteristics); - } + { + this->SetInput4(characteristics); + } /** Set/Get the tolerance value */ itkSetMacro(Sigma,double); @@ -213,27 +213,27 @@ class ITK_EXPORT MultiScaleConvexOrConcaveClassificationFilter /** Set the functor parameters before calling the ThreadedGenerateData() */ virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctor().SetLabelSeparator(m_LabelSeparator); - this->GetFunctor().SetSigma(m_Sigma); - } + { + this->GetFunctor().SetLabelSeparator(m_LabelSeparator); + this->GetFunctor().SetSigma(m_Sigma); + } protected: /** Constructor */ MultiScaleConvexOrConcaveClassificationFilter() - { - m_LabelSeparator = 10; - m_Sigma = 0.0; - }; + { + m_LabelSeparator = 10; + m_Sigma = 0.0; + }; /** Destructor */ virtual ~MultiScaleConvexOrConcaveClassificationFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"LabelSeparator: "<<m_LabelSeparator<<std::endl; - os<<indent<<"Sigma: "<<m_Sigma<<std::endl; - } + { + Superclass::PrintSelf(os,indent); + os<<indent<<"LabelSeparator: "<<m_LabelSeparator<<std::endl; + os<<indent<<"Sigma: "<<m_Sigma<<std::endl; + } private: MultiScaleConvexOrConcaveClassificationFilter(const Self&); //purposely not implemented diff --git a/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.h b/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.h index 0e461525ff431b899a0ee4980f05f1065046b05d..c19be397dbd17ec51487b756e433e00522367a32 100644 --- a/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.h +++ b/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.h @@ -38,9 +38,9 @@ namespace otb */ template <class TInputImage, class TOutputImage, class TLabeledImage> class ITK_EXPORT ProfileDerivativeToMultiScaleCharacteristicsFilter - : public ImageListToImageFilter<TInputImage, TOutputImage> + : public ImageListToImageFilter<TInputImage, TOutputImage> { - public: +public: /** Standard typedefs */ typedef ProfileDerivativeToMultiScaleCharacteristicsFilter Self; typedef ImageListToImageFilter<TInputImage, TOutputImage> Superclass; @@ -80,7 +80,7 @@ class ITK_EXPORT ProfileDerivativeToMultiScaleCharacteristicsFilter itkGetMacro(Step,LabeledPixelType); - protected: +protected: /** Main computation method */ virtual void GenerateData(void); @@ -100,7 +100,7 @@ class ITK_EXPORT ProfileDerivativeToMultiScaleCharacteristicsFilter ProfileDerivativeToMultiScaleCharacteristicsFilter(); /** Destructor */ virtual ~ProfileDerivativeToMultiScaleCharacteristicsFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.txx b/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.txx index d13632839ddacc4ea7ff8f1395eb485b58e29fe0..f3e55c0be441045a14462a211dc3c42a7c9bfbeb 100644 --- a/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.txx +++ b/Code/MultiScale/otbProfileDerivativeToMultiScaleCharacteristicsFilter.txx @@ -43,11 +43,11 @@ ProfileDerivativeToMultiScaleCharacteristicsFilter<TInputImage,TOutputImage,TLab ::GetOutputCharacteristics(void) { if (this->GetNumberOfOutputs() < 2) - { - return 0; - } + { + return 0; + } return static_cast<LabeledImageType * > - (this->itk::ProcessObject::GetOutput(1) ); + (this->itk::ProcessObject::GetOutput(1) ); } /** * GenerateOutputInformation @@ -60,12 +60,12 @@ ProfileDerivativeToMultiScaleCharacteristicsFilter<TInputImage,TOutputImage,TLab InputImageListPointerType inputPtr = this->GetInput(); OutputImagePointerType outputPtr = this->GetOutput(); LabeledImagePointerType outputLabeledPtr = this->GetOutputCharacteristics(); - if(inputPtr->Size()>0) - { - typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - outputPtr->CopyInformation(inputListIt.Get()); - outputLabeledPtr->CopyInformation(inputListIt.Get()); - } + if (inputPtr->Size()>0) + { + typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); + outputPtr->CopyInformation(inputListIt.Get()); + outputLabeledPtr->CopyInformation(inputListIt.Get()); + } } /** * GenerateInputRequestedRegion @@ -85,49 +85,49 @@ ProfileDerivativeToMultiScaleCharacteristicsFilter<TInputImage,TOutputImage,TLab * Compute the appropriate requested region: * This is the smaller region containing the two output regions */ - if(region1==this->GetOutput()->GetLargestPossibleRegion() - &®ion2!=this->GetOutputCharacteristics()->GetLargestPossibleRegion()) - { - region = region2; - } - else if(region1!=this->GetOutput()->GetLargestPossibleRegion() - &®ion2==this->GetOutputCharacteristics()->GetLargestPossibleRegion()) - { - region = region1; - } + if (region1==this->GetOutput()->GetLargestPossibleRegion() + &®ion2!=this->GetOutputCharacteristics()->GetLargestPossibleRegion()) + { + region = region2; + } + else if (region1!=this->GetOutput()->GetLargestPossibleRegion() + &®ion2==this->GetOutputCharacteristics()->GetLargestPossibleRegion()) + { + region = region1; + } else - { - int xul1 = region1.GetIndex()[0]; - int xul2 = region2.GetIndex()[0]; - int yul1 = region1.GetIndex()[1]; - int yul2 = region2.GetIndex()[1]; - int xlr1 = region1.GetIndex()[0]+region1.GetSize()[0]; - int xlr2 = region2.GetIndex()[0]+region2.GetSize()[0]; - int ylr1 = region1.GetIndex()[1]+region1.GetSize()[1]; - int ylr2 = region2.GetIndex()[1]+region2.GetSize()[1]; - - int xul = std::min(xul1,xul2); - int yul = std::min(yul1,yul2); - int xlr = std::max(xlr1,xlr2); - int ylr = std::max(ylr1,ylr2); - - typename RegionType::IndexType index; - index[0]=xul; - index[1]=yul; - - typename RegionType::SizeType size; - size[0]=static_cast<unsigned int>(xlr-xul); - size[1]=static_cast<unsigned int>(ylr-yul); - - region.SetIndex(index); - region.SetSize(size); - } + { + int xul1 = region1.GetIndex()[0]; + int xul2 = region2.GetIndex()[0]; + int yul1 = region1.GetIndex()[1]; + int yul2 = region2.GetIndex()[1]; + int xlr1 = region1.GetIndex()[0]+region1.GetSize()[0]; + int xlr2 = region2.GetIndex()[0]+region2.GetSize()[0]; + int ylr1 = region1.GetIndex()[1]+region1.GetSize()[1]; + int ylr2 = region2.GetIndex()[1]+region2.GetSize()[1]; + + int xul = std::min(xul1,xul2); + int yul = std::min(yul1,yul2); + int xlr = std::max(xlr1,xlr2); + int ylr = std::max(ylr1,ylr2); + + typename RegionType::IndexType index; + index[0]=xul; + index[1]=yul; + + typename RegionType::SizeType size; + size[0]=static_cast<unsigned int>(xlr-xul); + size[1]=static_cast<unsigned int>(ylr-yul); + + region.SetIndex(index); + region.SetSize(size); + } - while(inputListIt!=inputPtr->End()) - { - inputListIt.Get()->SetRequestedRegion(region); - ++inputListIt; - } + while (inputListIt!=inputPtr->End()) + { + inputListIt.Get()->SetRequestedRegion(region); + ++inputListIt; + } } /** * Main computation method @@ -162,11 +162,11 @@ ProfileDerivativeToMultiScaleCharacteristicsFilter<TInputImage,TOutputImage,TLab InputIteratorListType inputIteratorList; // fills the vector of input iterators - for(;inputListIt!=inputPtr->End();++inputListIt) - { - inputIteratorList.push_back(InputIteratorType(inputListIt.Get(),inputListIt.Get()->GetRequestedRegion())); - inputIteratorList.back().GoToBegin(); - } + for (;inputListIt!=inputPtr->End();++inputListIt) + { + inputIteratorList.push_back(InputIteratorType(inputListIt.Get(),inputListIt.Get()->GetRequestedRegion())); + inputIteratorList.back().GoToBegin(); + } // walk through the output images OutputIteratorType outputIt(outputPtr,outputPtr->GetRequestedRegion()); @@ -175,41 +175,41 @@ ProfileDerivativeToMultiScaleCharacteristicsFilter<TInputImage,TOutputImage,TLab labeledIt.GoToBegin(); bool inputIteratorsAtEnd = false; - for(typename InputIteratorListType::iterator it = inputIteratorList.begin(); - it != inputIteratorList.end();++it) + for (typename InputIteratorListType::iterator it = inputIteratorList.begin(); + it != inputIteratorList.end();++it) { inputIteratorsAtEnd = inputIteratorsAtEnd || it->IsAtEnd(); } - while(!outputIt.IsAtEnd() && !labeledIt.IsAtEnd() && !inputIteratorsAtEnd) - { - unsigned int index = 0; - OutputPixelType outputPixel = 0; - LabeledPixelType outputChar = 0; - - // for each input iterator, check the output and characteristics - for(typename InputIteratorListType::iterator it = inputIteratorList.begin(); - it != inputIteratorList.end();++it) + while (!outputIt.IsAtEnd() && !labeledIt.IsAtEnd() && !inputIteratorsAtEnd) { - if(it->Get()>outputPixel) + unsigned int index = 0; + OutputPixelType outputPixel = 0; + LabeledPixelType outputChar = 0; + + // for each input iterator, check the output and characteristics + for (typename InputIteratorListType::iterator it = inputIteratorList.begin(); + it != inputIteratorList.end();++it) + { + if (it->Get()>outputPixel) { outputPixel = it->Get(); outputChar = m_InitialValue+m_Step*(static_cast<LabeledPixelType>(index)); } - ++index; - } - outputIt.Set(outputPixel); - labeledIt.Set(outputChar); - ++outputIt; - ++labeledIt; - for(typename InputIteratorListType::iterator it = inputIteratorList.begin(); - it != inputIteratorList.end();++it) - { - ++(*it); - inputIteratorsAtEnd = inputIteratorsAtEnd || it->IsAtEnd(); - } + ++index; + } + outputIt.Set(outputPixel); + labeledIt.Set(outputChar); + ++outputIt; + ++labeledIt; + for (typename InputIteratorListType::iterator it = inputIteratorList.begin(); + it != inputIteratorList.end();++it) + { + ++(*it); + inputIteratorsAtEnd = inputIteratorsAtEnd || it->IsAtEnd(); } + } } /** * PrintSelf Method diff --git a/Code/MultiScale/otbProfileToProfileDerivativeFilter.h b/Code/MultiScale/otbProfileToProfileDerivativeFilter.h index 04f1149130ab039fdc65d59d9094b4164b73043d..e1b76fef47d725d87cdaab91c78e4a32d9a92325 100644 --- a/Code/MultiScale/otbProfileToProfileDerivativeFilter.h +++ b/Code/MultiScale/otbProfileToProfileDerivativeFilter.h @@ -40,9 +40,9 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ProfileToProfileDerivativeFilter - : public ImageListToImageListFilter<TInputImage,TOutputImage> + : public ImageListToImageListFilter<TInputImage,TOutputImage> { - public: +public: /** Standard typedefs */ typedef ProfileToProfileDerivativeFilter Self; typedef ImageListToImageListFilter<TInputImage,TOutputImage> Superclass; @@ -84,7 +84,7 @@ protected: ProfileToProfileDerivativeFilter(); /** Destructor */ virtual ~ProfileToProfileDerivativeFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/MultiScale/otbProfileToProfileDerivativeFilter.txx b/Code/MultiScale/otbProfileToProfileDerivativeFilter.txx index ad20f8d0d6da2f3a9ed7a656ced92f8074103d35..402aa423bed9624e028ed57705ecf5b5a9b1f357 100644 --- a/Code/MultiScale/otbProfileToProfileDerivativeFilter.txx +++ b/Code/MultiScale/otbProfileToProfileDerivativeFilter.txx @@ -42,34 +42,34 @@ ProfileToProfileDerivativeFilter<TInputImageList,TOutputImageList> // Retrieving input/output pointers InputImageListPointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); - if(outputPtr) - { - if(outputPtr->Size()!=inputPtr->Size()-1) + if (outputPtr) { - // in this case, clear the list - outputPtr->Clear(); - typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - ++inputListIt; - while(inputListIt!=inputPtr->End()) + if (outputPtr->Size()!=inputPtr->Size()-1) + { + // in this case, clear the list + outputPtr->Clear(); + typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); + ++inputListIt; + while (inputListIt!=inputPtr->End()) { outputPtr->PushBack(OutputImageType::New()); ++inputListIt; } - } + } - // For each input image - typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); - typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); - ++inputListIt; - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) - { - // Create the output image and set its information - outputListIt.Get()->CopyInformation(inputListIt.Get()); - outputListIt.Get()->SetLargestPossibleRegion(inputListIt.Get()->GetLargestPossibleRegion()); + // For each input image + typename InputImageListType::ConstIterator inputListIt = inputPtr->Begin(); + typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); ++inputListIt; - ++outputListIt; - } + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + { + // Create the output image and set its information + outputListIt.Get()->CopyInformation(inputListIt.Get()); + outputListIt.Get()->SetLargestPossibleRegion(inputListIt.Get()->GetLargestPossibleRegion()); + ++inputListIt; + ++outputListIt; } + } } /** Generate input requested region for each image in the List. */ template <class TInputImageList, class TOutputImageList> @@ -77,7 +77,7 @@ void ProfileToProfileDerivativeFilter<TInputImageList,TOutputImageList> ::GenerateInputRequestedRegion() { - // Retrieving input/output pointers + // Retrieving input/output pointers InputImageListPointerType inputPtr = this->GetInput(); OutputImageListPointerType outputPtr = this->GetOutput(); @@ -86,7 +86,7 @@ ProfileToProfileDerivativeFilter<TInputImageList,TOutputImageList> typename OutputImageListType::Iterator outputListIt = outputPtr->Begin(); // Use the filter to generate input requested region - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) { inputListIt.Get() ->SetRequestedRegion(outputListIt.Get()->GetRequestedRegion()); ++inputListIt; @@ -113,7 +113,7 @@ ProfileToProfileDerivativeFilter<TInputImageList,TOutputImageList> InputImagePointerType lastImage = inputListIt.Get(); ++inputListIt; - while(inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) + while (inputListIt!=inputPtr->End()&&outputListIt!=outputPtr->End()) { m_SubtractFilter->SetInput1(inputListIt.Get()); m_SubtractFilter->SetInput2(lastImage); diff --git a/Code/Projections/otbCompositeTransform.h b/Code/Projections/otbCompositeTransform.h index ddb80613bdc66a7bf29715589bf7484bc62d8a1a..eebf5f427a18c399285c7f79c26285059c5e114f 100644 --- a/Code/Projections/otbCompositeTransform.h +++ b/Code/Projections/otbCompositeTransform.h @@ -29,113 +29,114 @@ namespace otb { - /** \class CompositeTransform - - * \brief Class which compose two itk::Transform to obtain one itk::Transform - * T1 T2 T3 - * (x,y) -> (x',y') -> (x'',y'') => (x,y) -> (x'',y'') - * - * - * \ingroup Transform - */ - - typedef enum { - PROJDEFAULT=0, - PROJIDENTITY=1, - PROJMAPFORWARD=2, - PROJMAPINVERSE=3, - PROJSENSORFORWARD=4, - PROJSENSORINVERSE=5 - } ProjectionTypeEnum; - - template <class TFirstTransform, - class TSecondTransform, - class TScalarType=double, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2> - class ITK_EXPORT CompositeTransform: public itk::Transform<TScalarType, // Data type for scalars - NInputDimensions, // Number of dimensions in the input space - NOutputDimensions> // Number of dimensions in the output space - { - public : - - - /** Standard class typedefs */ - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef CompositeTransform Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef TFirstTransform FirstTransformType; - typedef typename TFirstTransform::Pointer FirstTransformPointerType; - typedef TSecondTransform SecondTransformType; - typedef typename TSecondTransform::Pointer SecondTransformPointerType; - - /** Standard vector type for this class. */ - // typedef typename TFirstTransform::InputVectorType FirstTransformInputVectorType; - // typedef typename TFirstTransform::OutputVectorType FirstTransformOutputVectorType; - - /** Standard covariant vector type for this class */ - // typedef typename TFirstTransform::InputCovariantVectorType FirstTransformInputCovariantVectorType; - // typedef typename TFirstTransform::OutputCovariantVectorType FirstTransformOutputCovariantVectorType; - - /** Standard vnl_vector type for this class. */ - // typedef typename TFirstTransform::InputVnlVectorType FirstTransformInputVnlVectorType; - // typedef typename TFirstTransform::OutputVnlVectorType FirstTransformOutputVnlVectorType; - - /** Standard coordinate point type for this class */ - typedef typename Superclass::InputPointType FirstTransformInputPointType; - typedef typename TFirstTransform::OutputPointType FirstTransformOutputPointType; - /** TSecondTransform::InputPointType is purposely not defined - * It contrains user to choose First Transform Output compatible - * with Second Transform Input */ - typedef typename Superclass::OutputPointType SecondTransformOutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( CompositeTransform, itk::Transform ); - - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension,unsigned int, NOutputDimensions); - itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int, NInputDimensions*(NInputDimensions+1)); - - /** Set first transformation */ - itkSetObjectMacro(FirstTransform,FirstTransformType); - - /** Set second transformation */ - itkSetObjectMacro(SecondTransform,SecondTransformType); - - - - /** Method to transform a point. */ - virtual SecondTransformOutputPointType TransformPoint(const FirstTransformInputPointType & ) const; - - /** Method to transform a vector. */ - // virtual OutputVectorType TransformVector(const InputVectorType &) const; - - /** Method to transform a vnl_vector. */ - // virtual OutputVnlVectorType TransformVector(const InputVnlVectorType &) const; - - /** Method to transform a CovariantVector. */ - // virtual OutputCovariantVectorType TransformCovariantVector(const InputCovariantVectorType &) const; - - protected: - CompositeTransform(); - ~CompositeTransform(); - - FirstTransformPointerType m_FirstTransform; - SecondTransformPointerType m_SecondTransform; - - private: - CompositeTransform(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class CompositeTransform + +* \brief Class which compose two itk::Transform to obtain one itk::Transform +* T1 T2 T3 +* (x,y) -> (x',y') -> (x'',y'') => (x,y) -> (x'',y'') +* + * +* \ingroup Transform +*/ + +typedef enum +{ + PROJDEFAULT=0, + PROJIDENTITY=1, + PROJMAPFORWARD=2, + PROJMAPINVERSE=3, + PROJSENSORFORWARD=4, + PROJSENSORINVERSE=5 +} ProjectionTypeEnum; + +template <class TFirstTransform, +class TSecondTransform, +class TScalarType=double, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2> +class ITK_EXPORT CompositeTransform: public itk::Transform<TScalarType, // Data type for scalars + NInputDimensions, // Number of dimensions in the input space + NOutputDimensions> // Number of dimensions in the output space +{ +public : + + + /** Standard class typedefs */ + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef CompositeTransform Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef TFirstTransform FirstTransformType; + typedef typename TFirstTransform::Pointer FirstTransformPointerType; + typedef TSecondTransform SecondTransformType; + typedef typename TSecondTransform::Pointer SecondTransformPointerType; + + /** Standard vector type for this class. */ + // typedef typename TFirstTransform::InputVectorType FirstTransformInputVectorType; + // typedef typename TFirstTransform::OutputVectorType FirstTransformOutputVectorType; + + /** Standard covariant vector type for this class */ + // typedef typename TFirstTransform::InputCovariantVectorType FirstTransformInputCovariantVectorType; + // typedef typename TFirstTransform::OutputCovariantVectorType FirstTransformOutputCovariantVectorType; + + /** Standard vnl_vector type for this class. */ + // typedef typename TFirstTransform::InputVnlVectorType FirstTransformInputVnlVectorType; + // typedef typename TFirstTransform::OutputVnlVectorType FirstTransformOutputVnlVectorType; + + /** Standard coordinate point type for this class */ + typedef typename Superclass::InputPointType FirstTransformInputPointType; + typedef typename TFirstTransform::OutputPointType FirstTransformOutputPointType; + /** TSecondTransform::InputPointType is purposely not defined + * It contrains user to choose First Transform Output compatible + * with Second Transform Input */ + typedef typename Superclass::OutputPointType SecondTransformOutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( CompositeTransform, itk::Transform ); + + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension,unsigned int, NOutputDimensions); + itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int, NInputDimensions*(NInputDimensions+1)); + + /** Set first transformation */ + itkSetObjectMacro(FirstTransform,FirstTransformType); + + /** Set second transformation */ + itkSetObjectMacro(SecondTransform,SecondTransformType); + + + + /** Method to transform a point. */ + virtual SecondTransformOutputPointType TransformPoint(const FirstTransformInputPointType & ) const; + + /** Method to transform a vector. */ + // virtual OutputVectorType TransformVector(const InputVectorType &) const; + + /** Method to transform a vnl_vector. */ + // virtual OutputVnlVectorType TransformVector(const InputVnlVectorType &) const; + + /** Method to transform a CovariantVector. */ + // virtual OutputCovariantVectorType TransformCovariantVector(const InputCovariantVectorType &) const; + +protected: + CompositeTransform(); + ~CompositeTransform(); + + FirstTransformPointerType m_FirstTransform; + SecondTransformPointerType m_SecondTransform; + +private: + CompositeTransform(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // namespace otb diff --git a/Code/Projections/otbCompositeTransform.txx b/Code/Projections/otbCompositeTransform.txx index 0f3cdc9f943676948577fcc5b0efdea0570bc7c6..9ddf5c53de43444a19030fe276c2f8002d2b1785 100644 --- a/Code/Projections/otbCompositeTransform.txx +++ b/Code/Projections/otbCompositeTransform.txx @@ -28,106 +28,106 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template<class TFirstTransform, - class TSecondTransform, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> - CompositeTransform<TFirstTransform, - TSecondTransform, - TScalarType, - NInputDimensions, - NOutputDimensions> - ::CompositeTransform() : Superclass(SpaceDimension,ParametersDimension) +template<class TFirstTransform, +class TSecondTransform, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> +CompositeTransform<TFirstTransform, +TSecondTransform, +TScalarType, +NInputDimensions, +NOutputDimensions> +::CompositeTransform() : Superclass(SpaceDimension,ParametersDimension) +{ + m_FirstTransform = 0; + m_SecondTransform = 0; +} + +template<class TFirstTransform, +class TSecondTransform, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> +CompositeTransform<TFirstTransform, +TSecondTransform, +TScalarType, +NInputDimensions, +NOutputDimensions> +::~CompositeTransform() +{ +} + + +template<class TFirstTransform, +class TSecondTransform, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> +typename CompositeTransform<TFirstTransform, +TSecondTransform, +TScalarType, +NInputDimensions, +NOutputDimensions>::SecondTransformOutputPointType +CompositeTransform<TFirstTransform, +TSecondTransform, +TScalarType, +NInputDimensions, +NOutputDimensions> +::TransformPoint(const FirstTransformInputPointType &point1) const +{ + FirstTransformOutputPointType geoPoint; + geoPoint=m_FirstTransform->TransformPoint(point1); + + SecondTransformOutputPointType outputPoint; + outputPoint=m_SecondTransform->TransformPoint(geoPoint); + +// otbMsgDevMacro(<< "Converting: " << point1 << " -> " << geoPoint<< " -> " << outputPoint); + + return outputPoint; +} + +/*template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> + typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputVectorType + CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> + ::TransformVector(const InputVectorType &vector1) const { - m_FirstTransform = 0; - m_SecondTransform = 0; + InputVectorType vectorTmp; + OutputVectorType vector2; + + vectorTmp=m_FirstTransform->TransformVector(vector1); + vector2=m_SecondTransform->TransformVector(vectorTmp); + + return vector2; } - template<class TFirstTransform, - class TSecondTransform, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> - CompositeTransform<TFirstTransform, - TSecondTransform, - TScalarType, - NInputDimensions, - NOutputDimensions> - ::~CompositeTransform() + template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> + typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputVnlVectorType + CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> + ::TransformVector(const InputVnlVectorType &vnlVector1) const { - } + InputVnlVectorType vnlVectorTmp; + OutputVnlVectorType vnlVector2; + vnlVectorTmp=m_FirstTransform->TransformVector(vnlVector1); + vnlVector2=m_SecondTransform->TransformVector(vnlVectorTmp); - template<class TFirstTransform, - class TSecondTransform, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> - typename CompositeTransform<TFirstTransform, - TSecondTransform, - TScalarType, - NInputDimensions, - NOutputDimensions>::SecondTransformOutputPointType - CompositeTransform<TFirstTransform, - TSecondTransform, - TScalarType, - NInputDimensions, - NOutputDimensions> - ::TransformPoint(const FirstTransformInputPointType &point1) const - { - FirstTransformOutputPointType geoPoint; - geoPoint=m_FirstTransform->TransformPoint(point1); - - SecondTransformOutputPointType outputPoint; - outputPoint=m_SecondTransform->TransformPoint(geoPoint); + return vnlVector2; + } -// otbMsgDevMacro(<< "Converting: " << point1 << " -> " << geoPoint<< " -> " << outputPoint); + template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> + typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputCovariantVectorType + CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> + ::TransformCovariantVector(const InputCovariantVectorType &covariantVector1) const + { + InputCovariantVectorType covariantVectorTmp; + OutputCovariantVectorType covariantVector2; + + covariantVectorTmp=m_FirstTransform->TransformCovariantVector(covariantVector1); + covariantVector2=m_SecondTransform->TransformCovariantVector(covariantVectorTmp); - return outputPoint; - } - - /*template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputVectorType - CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> - ::TransformVector(const InputVectorType &vector1) const - { - InputVectorType vectorTmp; - OutputVectorType vector2; - - vectorTmp=m_FirstTransform->TransformVector(vector1); - vector2=m_SecondTransform->TransformVector(vectorTmp); - - return vector2; - } - - template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputVnlVectorType - CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> - ::TransformVector(const InputVnlVectorType &vnlVector1) const - { - InputVnlVectorType vnlVectorTmp; - OutputVnlVectorType vnlVector2; - - vnlVectorTmp=m_FirstTransform->TransformVector(vnlVector1); - vnlVector2=m_SecondTransform->TransformVector(vnlVectorTmp); - - return vnlVector2; - } - - template<class TFirstTransform, class TSecondTransform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename CompositeTransform<TFirstTransform, TSecondTransform, TScalarType, NInputDimensions, NOutputDimensions>::OutputCovariantVectorType - CompositeTransform<TFirstTransform, TSecondTransform, TScalarType,NInputDimensions, NOutputDimensions> - ::TransformCovariantVector(const InputCovariantVectorType &covariantVector1) const - { - InputCovariantVectorType covariantVectorTmp; - OutputCovariantVectorType covariantVector2; - - covariantVectorTmp=m_FirstTransform->TransformCovariantVector(covariantVector1); - covariantVector2=m_SecondTransform->TransformCovariantVector(covariantVectorTmp); - - return covariantVector2; - }*/ + return covariantVector2; + }*/ diff --git a/Code/Projections/otbEckert4MapProjection.h b/Code/Projections/otbEckert4MapProjection.h index f0e22ab23df1c625f412bc4bfea25b32d5ba93a9..2ecec595e68ed43b299038d59713a4ab6b34483e 100644 --- a/Code/Projections/otbEckert4MapProjection.h +++ b/Code/Projections/otbEckert4MapProjection.h @@ -24,46 +24,46 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class Exckert4MapProjection - * \brief This class implements the Eckert4 map projection. - * It converts coordinates in longitude,latitude (WGS84) to Eckert4 map coordinates. - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT Eckert4MapProjection : public MapProjection<ossimEckert4Projection,transform> - { - public : - - /** Standard class typedefs. */ - typedef Eckert4MapProjection Self; - typedef MapProjection<ossimEckert4Projection,transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( Eckert4MapProjection, MapProjection ); - virtual void SetFalseEasting(double falseEasting); - virtual void SetFalseNorthing(double falseNorthing); - virtual double GetFalseNorthing() const; - virtual double GetFalseEasting() const; - virtual void SetParameters(double falseEasting,double falseNorthing); - virtual void SetDefaults(); - - protected : - Eckert4MapProjection(); - virtual ~Eckert4MapProjection(); - - private : - Eckert4MapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class Exckert4MapProjection + * \brief This class implements the Eckert4 map projection. + * It converts coordinates in longitude,latitude (WGS84) to Eckert4 map coordinates. + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT Eckert4MapProjection : public MapProjection<ossimEckert4Projection,transform> +{ +public : + + /** Standard class typedefs. */ + typedef Eckert4MapProjection Self; + typedef MapProjection<ossimEckert4Projection,transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( Eckert4MapProjection, MapProjection ); + virtual void SetFalseEasting(double falseEasting); + virtual void SetFalseNorthing(double falseNorthing); + virtual double GetFalseNorthing() const; + virtual double GetFalseEasting() const; + virtual void SetParameters(double falseEasting,double falseNorthing); + virtual void SetDefaults(); + +protected : + Eckert4MapProjection(); + virtual ~Eckert4MapProjection(); + +private : + Eckert4MapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // namespace otb diff --git a/Code/Projections/otbEckert4MapProjection.txx b/Code/Projections/otbEckert4MapProjection.txx index abadcbae7a7fa68c6991a403909b9a599f8b4cf7..2dde1c4c249917f3e361a7985735fd1026200e0f 100644 --- a/Code/Projections/otbEckert4MapProjection.txx +++ b/Code/Projections/otbEckert4MapProjection.txx @@ -24,67 +24,67 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - Eckert4MapProjection<transform> - ::Eckert4MapProjection() - { - } - - - template <InverseOrForwardTransformationEnum transform> - Eckert4MapProjection<transform> - ::~Eckert4MapProjection() - { - } - - ///False easting specification - template <InverseOrForwardTransformationEnum transform> - void Eckert4MapProjection<transform> - ::SetFalseEasting(double falseEasting) - { - this->m_MapProjection->setFalseEasting(falseEasting); - } - - ///False Northing specification - template <InverseOrForwardTransformationEnum transform> - void Eckert4MapProjection<transform> - ::SetFalseNorthing(double falseNorthing) - { - this->m_MapProjection->setFalseNorthing(falseNorthing); - } - - ///Set the defaul parameters - template <InverseOrForwardTransformationEnum transform> - void Eckert4MapProjection<transform> - ::SetDefaults() - { - this->m_MapProjection->setDefaults(); - } - - ///Get the false northing coordinates (avoid negative values) - template <InverseOrForwardTransformationEnum transform> - double Eckert4MapProjection<transform> - ::GetFalseNorthing() const - { - double falseNorthing=this->m_MapProjection->getFalseNorthing(); - return falseNorthing; - } - - ///Get the false easting coordinates (avoid negative values) - template <InverseOrForwardTransformationEnum transform> - double Eckert4MapProjection<transform> - ::GetFalseEasting() const - { - double falseEasting=this->m_MapProjection->getFalseEasting(); - return falseEasting; - } - - template <InverseOrForwardTransformationEnum transform> - void Eckert4MapProjection<transform> - ::SetParameters(double falseEasting,double falseNorthing) - { - this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); - } +template <InverseOrForwardTransformationEnum transform> +Eckert4MapProjection<transform> +::Eckert4MapProjection() +{ +} + + +template <InverseOrForwardTransformationEnum transform> +Eckert4MapProjection<transform> +::~Eckert4MapProjection() +{ +} + +///False easting specification +template <InverseOrForwardTransformationEnum transform> +void Eckert4MapProjection<transform> +::SetFalseEasting(double falseEasting) +{ + this->m_MapProjection->setFalseEasting(falseEasting); +} + +///False Northing specification +template <InverseOrForwardTransformationEnum transform> +void Eckert4MapProjection<transform> +::SetFalseNorthing(double falseNorthing) +{ + this->m_MapProjection->setFalseNorthing(falseNorthing); +} + +///Set the defaul parameters +template <InverseOrForwardTransformationEnum transform> +void Eckert4MapProjection<transform> +::SetDefaults() +{ + this->m_MapProjection->setDefaults(); +} + +///Get the false northing coordinates (avoid negative values) +template <InverseOrForwardTransformationEnum transform> +double Eckert4MapProjection<transform> +::GetFalseNorthing() const +{ + double falseNorthing=this->m_MapProjection->getFalseNorthing(); + return falseNorthing; +} + +///Get the false easting coordinates (avoid negative values) +template <InverseOrForwardTransformationEnum transform> +double Eckert4MapProjection<transform> +::GetFalseEasting() const +{ + double falseEasting=this->m_MapProjection->getFalseEasting(); + return falseEasting; +} + +template <InverseOrForwardTransformationEnum transform> +void Eckert4MapProjection<transform> +::SetParameters(double falseEasting,double falseNorthing) +{ + this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); +} } // namespace otb diff --git a/Code/Projections/otbForwardSensorModel.h b/Code/Projections/otbForwardSensorModel.h index 05fa2f00d13865b0d6ef05ba43fd48ba9cd82c79..fe53c052c3b56db7ca1e72b60435e418a922e496 100644 --- a/Code/Projections/otbForwardSensorModel.h +++ b/Code/Projections/otbForwardSensorModel.h @@ -27,73 +27,73 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class ForwardSensorModel - - * \brief Class for direct sensor models - * - * Based on ossimProjectionFactoryRegistry and ossimProjection methods. - * It takes as input an index and computes the world coordinates. - * (i,j,h) -> (lon,lat). - * Notice that the elevation h is optional. - * - * \ingroup Transform - * \ingroup Projection - */ - - template <class TScalarType, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2, - unsigned int NParametersDimensions=3> - class ITK_EXPORT ForwardSensorModel : public SensorModelBase<TScalarType, +/** \class ForwardSensorModel + + * \brief Class for direct sensor models + * + * Based on ossimProjectionFactoryRegistry and ossimProjection methods. + * It takes as input an index and computes the world coordinates. + * (i,j,h) -> (lon,lat). + * Notice that the elevation h is optional. + * + * \ingroup Transform + * \ingroup Projection + */ + +template <class TScalarType, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2, +unsigned int NParametersDimensions=3> +class ITK_EXPORT ForwardSensorModel : public SensorModelBase<TScalarType, NInputDimensions, NOutputDimensions, NParametersDimensions> - { +{ - public : - /** Standard class typedefs. */ - typedef ForwardSensorModel Self; - typedef SensorModelBase< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +public : + /** Standard class typedefs. */ + typedef ForwardSensorModel Self; + typedef SensorModelBase< TScalarType, + NInputDimensions, + NOutputDimensions, + NParametersDimensions > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; - /** Method for creation through the object factory. */ - itkNewMacro( Self ); + /** Method for creation through the object factory. */ + itkNewMacro( Self ); - /** Run-time type information (and related methods). */ - itkTypeMacro( ForwardSensorModel, SensorModelBase ); + /** Run-time type information (and related methods). */ + itkTypeMacro( ForwardSensorModel, SensorModelBase ); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! - /** Compute the world coordinates. */ - OutputPointType TransformPoint(const InputPointType &point) const; + /** Compute the world coordinates. */ + OutputPointType TransformPoint(const InputPointType &point) const; - protected: - ForwardSensorModel(); - virtual ~ForwardSensorModel(); +protected: + ForwardSensorModel(); + virtual ~ForwardSensorModel(); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : +private : - ForwardSensorModel(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + ForwardSensorModel(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - /** Difference between consecutives heights in iterative transform point with DEM */ - double m_Epsilon; + /** Difference between consecutives heights in iterative transform point with DEM */ + double m_Epsilon; - /** Number of iterations in iterative transform point with DEM */ - double m_NbIter; - }; + /** Number of iterations in iterative transform point with DEM */ + double m_NbIter; +}; } // namespace otb diff --git a/Code/Projections/otbForwardSensorModel.txx b/Code/Projections/otbForwardSensorModel.txx index 8db1572c3946b69863478081305d9f1618fb97d4..9575559eba843423381a03b10b6c66f4b29b5888 100644 --- a/Code/Projections/otbForwardSensorModel.txx +++ b/Code/Projections/otbForwardSensorModel.txx @@ -27,13 +27,13 @@ namespace otb { template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > ForwardSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> +NInputDimensions, +NOutputDimensions, +NParametersDimensions> ::ForwardSensorModel() { m_Epsilon = 0.0001; @@ -41,31 +41,31 @@ ForwardSensorModel< TScalarType, } template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > ForwardSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> +NInputDimensions, +NOutputDimensions, +NParametersDimensions> ::~ForwardSensorModel() { } template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - typename ForwardSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions>::OutputPointType - ForwardSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::TransformPoint(const InputPointType &point) const +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +typename ForwardSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions>::OutputPointType +ForwardSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::TransformPoint(const InputPointType &point) const { // otbMsgDevMacro(<< "Point in sensor geometry: (" << point[0] << "," << point[1] << ")"); @@ -75,7 +75,7 @@ template < class TScalarType, // Calculation ossimGpt ossimGPoint; - if( this->m_Model == NULL) + if ( this->m_Model == NULL) { itkExceptionMacro(<<"TransformPoint(): Invalid Model pointer m_Model == NULL !"); } @@ -138,15 +138,15 @@ template < class TScalarType, } template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - ForwardSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::PrintSelf(std::ostream& os, itk::Indent indent) const +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +ForwardSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os,indent); } diff --git a/Code/Projections/otbGenericMapProjection.h b/Code/Projections/otbGenericMapProjection.h index 1af3bb2f434e3da9e3bf3cbc2178ed96183ef96b..e93fdb63a56deacb872bc7168fbcda45d1c7193f 100644 --- a/Code/Projections/otbGenericMapProjection.h +++ b/Code/Projections/otbGenericMapProjection.h @@ -36,87 +36,87 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class GenericMapProjection - * \brief This is the base class for generic map projection transformation - * - * The forward transformation will transform the coordinate for the geographic to the - * cartographic. The inverse model will transform from the cartographic to the geographic. - * - * All derived class assume that the latitude and longitude are given according to the - * WGS84 ellipsoid model. - * - * \ingroup Projection - * - **/ - - typedef enum {FORWARD=0, INVERSE=1} InverseOrForwardTransformationEnum; - - template <InverseOrForwardTransformationEnum TDirectionOfMapping, - class TScalarType = double, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2> - class ITK_EXPORT GenericMapProjection: public itk::Transform<TScalarType, // Data type for scalars - NInputDimensions, // Number of dimensions in the input space - NOutputDimensions> // Number of dimensions in the output space - { - public : - /** Standard class typedefs. */ - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef GenericMapProjection Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef ossimProjection OssimMapProjectionType; - typedef itk::Point<ScalarType,NInputDimensions > InputPointType; - typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( GenericMapProjection, itk::Transform ); - - itkSetObjectMacro(MapProjection,OssimMapProjectionType); - virtual OssimMapProjectionType* GetMapProjection (); - virtual const OssimMapProjectionType* GetMapProjection () const; - - typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; - - itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,TDirectionOfMapping); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); - - - /** Return the Wkt representation of the projection*/ - virtual std::string GetWkt(); - - /** Instanciate the projection according to the Wkt specification*/ - virtual void SetWkt(std::string projectionRefWkt); - - virtual void PrintMap() const; - - OutputPointType TransformPoint(const InputPointType &point) const; - - virtual bool InstanciateProjection(); - - protected: - GenericMapProjection(); - virtual ~GenericMapProjection(); - OssimMapProjectionType* m_MapProjection; - std::string m_ProjectionRefWkt; - - bool reinstanciateProjection; - - private : - GenericMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class GenericMapProjection + * \brief This is the base class for generic map projection transformation + * + * The forward transformation will transform the coordinate for the geographic to the + * cartographic. The inverse model will transform from the cartographic to the geographic. + * + * All derived class assume that the latitude and longitude are given according to the + * WGS84 ellipsoid model. + * + * \ingroup Projection + * + **/ + +typedef enum {FORWARD=0, INVERSE=1} InverseOrForwardTransformationEnum; + +template <InverseOrForwardTransformationEnum TDirectionOfMapping, +class TScalarType = double, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2> +class ITK_EXPORT GenericMapProjection: public itk::Transform<TScalarType, // Data type for scalars + NInputDimensions, // Number of dimensions in the input space + NOutputDimensions> // Number of dimensions in the output space +{ +public : + /** Standard class typedefs. */ + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef GenericMapProjection Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef ossimProjection OssimMapProjectionType; + typedef itk::Point<ScalarType,NInputDimensions > InputPointType; + typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( GenericMapProjection, itk::Transform ); + + itkSetObjectMacro(MapProjection,OssimMapProjectionType); + virtual OssimMapProjectionType* GetMapProjection (); + virtual const OssimMapProjectionType* GetMapProjection () const; + + typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; + + itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,TDirectionOfMapping); + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); + + + /** Return the Wkt representation of the projection*/ + virtual std::string GetWkt(); + + /** Instanciate the projection according to the Wkt specification*/ + virtual void SetWkt(std::string projectionRefWkt); + + virtual void PrintMap() const; + + OutputPointType TransformPoint(const InputPointType &point) const; + + virtual bool InstanciateProjection(); + +protected: + GenericMapProjection(); + virtual ~GenericMapProjection(); + OssimMapProjectionType* m_MapProjection; + std::string m_ProjectionRefWkt; + + bool reinstanciateProjection; + +private : + GenericMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; diff --git a/Code/Projections/otbGenericMapProjection.txx b/Code/Projections/otbGenericMapProjection.txx index 1be6d938e6f654a660b6207bbb8570058a4a1b79..ecd020cb26cde1881972f36836d9aca005c12bc4 100644 --- a/Code/Projections/otbGenericMapProjection.txx +++ b/Code/Projections/otbGenericMapProjection.txx @@ -26,174 +26,174 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GenericMapProjection() : Superclass(SpaceDimension,ParametersDimension) - { - m_MapProjection = NULL; - m_ProjectionRefWkt.clear(); - reinstanciateProjection=true; - } +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GenericMapProjection() : Superclass(SpaceDimension,ParametersDimension) +{ + m_MapProjection = NULL; + m_ProjectionRefWkt.clear(); + reinstanciateProjection=true; +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::~GenericMapProjection() +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::~GenericMapProjection() +{ + if (m_MapProjection != NULL) { - if (m_MapProjection != NULL) - { - delete m_MapProjection; - } + delete m_MapProjection; } +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OssimMapProjectionType* - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetMapProjection () +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OssimMapProjectionType* +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetMapProjection () +{ + itkDebugMacro("returning MapProjection address " << this->m_MapProjection ); + if ((reinstanciateProjection) || (m_MapProjection == NULL)) { - itkDebugMacro("returning MapProjection address " << this->m_MapProjection ); - if ((reinstanciateProjection) || (m_MapProjection == NULL)) - { - this->InstanciateProjection(); - } - - return this->m_MapProjection; + this->InstanciateProjection(); } + return this->m_MapProjection; +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - const typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OssimMapProjectionType* - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetMapProjection () const - { - itkDebugMacro("returning MapProjection address " << this->m_MapProjection ); - if ((reinstanciateProjection) || (m_MapProjection == NULL)) - { - itkExceptionMacro(<<"m_MapProjection not up-to-date, call InstanciateProjection() first"); - } - return this->m_MapProjection; +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +const typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OssimMapProjectionType* +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetMapProjection () const +{ + itkDebugMacro("returning MapProjection address " << this->m_MapProjection ); + if ((reinstanciateProjection) || (m_MapProjection == NULL)) + { + itkExceptionMacro(<<"m_MapProjection not up-to-date, call InstanciateProjection() first"); } + return this->m_MapProjection; +} + - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - std::string - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetWkt() +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +std::string +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetWkt() +{ + ossimKeywordlist kwl; + this->GetMapProjection()->saveState(kwl); + ossimOgcWktTranslator wktTranslator; + std::string wkt; + wkt = wktTranslator.fromOssimKwl(kwl); + return wkt; +} + +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetWkt(std::string projectionRefWkt) +{ + this->m_ProjectionRefWkt=projectionRefWkt; + reinstanciateProjection = true; + this->InstanciateProjection(); + this->Modified(); +} + +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +bool +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::InstanciateProjection() +{ + if ((this->reinstanciateProjection) || (m_MapProjection == NULL)) { ossimKeywordlist kwl; - this->GetMapProjection()->saveState(kwl); ossimOgcWktTranslator wktTranslator; - std::string wkt; - wkt = wktTranslator.fromOssimKwl(kwl); - return wkt; - } - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetWkt(std::string projectionRefWkt) - { - this->m_ProjectionRefWkt=projectionRefWkt; - reinstanciateProjection = true; - this->InstanciateProjection(); - this->Modified(); - } + bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl); - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - bool - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::InstanciateProjection() - { - if ((this->reinstanciateProjection) || (m_MapProjection == NULL)) + if (!projectionInformationAvailable) { - ossimKeywordlist kwl; - ossimOgcWktTranslator wktTranslator; - - bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl); - - if (!projectionInformationAvailable) - { - itkExceptionMacro(<<"Impossible to create the projection from string: "<< m_ProjectionRefWkt); - } - - m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl); - this->reinstanciateProjection = false; - return true; + itkExceptionMacro(<<"Impossible to create the projection from string: "<< m_ProjectionRefWkt); } - return false; + + m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl); + this->reinstanciateProjection = false; + return true; } + return false; +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::TransformPoint(const InputPointType & point) const - { - OutputPointType outputPoint; +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::TransformPoint(const InputPointType & point) const +{ + OutputPointType outputPoint; // otbMsgDevMacro(<< "DirectionOfMapping: " << DirectionOfMapping); - switch(DirectionOfMapping) - { - case INVERSE: - { + switch (DirectionOfMapping) + { + case INVERSE: + { // otbMsgDevMacro(<< "Cartographic coordinates: (" << point[0] << "," << point[1] << ")"); //from "itk::point" to "ossim::ossimDpt" - ossimDpt ossimDPoint(point[0], point[1]); + ossimDpt ossimDPoint(point[0], point[1]); //map projection - ossimGpt ossimGPoint; - ossimGPoint=this->GetMapProjection()->inverse(ossimDPoint); - ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84() ); + ossimGpt ossimGPoint; + ossimGPoint=this->GetMapProjection()->inverse(ossimDPoint); + ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84() ); // otbGenericMsgDebugMacro(<< "Inverse : " << std::endl << m_MapProjection->print(std::cout)); - outputPoint[0]=ossimGPoint.lon; - outputPoint[1]=ossimGPoint.lat; + outputPoint[0]=ossimGPoint.lon; + outputPoint[1]=ossimGPoint.lat; // otbMsgDevMacro(<< "Geographic coordinates (lon, lat) : (" << outputPoint[0] << "," << outputPoint[1] << ")"); - break; - } - case FORWARD: - { + break; + } + case FORWARD: + { // otbMsgDevMacro(<< "Geographic coordinates (lon, lat) : (" << point[1] << "," << point[0] << ")"); //from "itk::point" to "ossim::ossimGpt" - ossimGpt ossimGPoint(point[1], point[0]); + ossimGpt ossimGPoint(point[1], point[0]); //map projection - ossimDpt ossimDPoint; - ossimDPoint=this->GetMapProjection()->forward(ossimGPoint); + ossimDpt ossimDPoint; + ossimDPoint=this->GetMapProjection()->forward(ossimGPoint); // otbGenericMsgDebugMacro(<< "Forward : ========================= " << std::endl << m_MapProjection->print(std::cout)); - outputPoint[0]=ossimDPoint.x; - outputPoint[1]=ossimDPoint.y; + outputPoint[0]=ossimDPoint.x; + outputPoint[1]=ossimDPoint.y; // otbMsgDevMacro(<< "Cartographic coordinates: (" << outputPoint[0] << "," << outputPoint[1] << ")"); - break; - } - default: - { - itkExceptionMacro(<<"Model is INVERSE or FORWARD only !!"); - break; - } - } - - return outputPoint; + break; } - - - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::PrintMap() const + default: { - std::cout << m_MapProjection->print(std::cout); + itkExceptionMacro(<<"Model is INVERSE or FORWARD only !!"); + break; } + } + + return outputPoint; +} + + +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +GenericMapProjection<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::PrintMap() const +{ + std::cout << m_MapProjection->print(std::cout); +} diff --git a/Code/Projections/otbInverseSensorModel.h b/Code/Projections/otbInverseSensorModel.h index 491efc3a38f9e3a6104346073ab9a02054016996..24580b7ffe8ea935ed03f22d81f7040c6a814144 100644 --- a/Code/Projections/otbInverseSensorModel.h +++ b/Code/Projections/otbInverseSensorModel.h @@ -28,71 +28,71 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class InverseSensorModel - * - * \brief Class for inverse sensor models - * - * Based on ossimProjectionFactoryRegistry and ossimProjection methods. - * It takes as input a world point and computes the index position of the - * corresponding point in the input image. - * (lon,lat,h) -> (i,j). - * Notice that the elevation h is optional. - * - * \ingroup Transform - * \ingroup Projection - */ - template <class TScalarType, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2, - unsigned int NParametersDimensions=3> - class ITK_EXPORT InverseSensorModel : public SensorModelBase<TScalarType, +/** \class InverseSensorModel + * + * \brief Class for inverse sensor models + * + * Based on ossimProjectionFactoryRegistry and ossimProjection methods. + * It takes as input a world point and computes the index position of the + * corresponding point in the input image. + * (lon,lat,h) -> (i,j). + * Notice that the elevation h is optional. + * + * \ingroup Transform + * \ingroup Projection + */ +template <class TScalarType, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2, +unsigned int NParametersDimensions=3> +class ITK_EXPORT InverseSensorModel : public SensorModelBase<TScalarType, NInputDimensions, NOutputDimensions, NParametersDimensions> - { +{ - public : - /** Standard class typedefs. */ - typedef InverseSensorModel Self; - typedef SensorModelBase< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +public : + /** Standard class typedefs. */ + typedef InverseSensorModel Self; + typedef SensorModelBase< TScalarType, + NInputDimensions, + NOutputDimensions, + NParametersDimensions > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; - /** Method for creation through the object factory. */ - itkNewMacro( Self ); + /** Method for creation through the object factory. */ + itkNewMacro( Self ); - /** Run-time type information (and related methods). */ - itkTypeMacro( InverseSensorModel, SensorModelBase ); + /** Run-time type information (and related methods). */ + itkTypeMacro( InverseSensorModel, SensorModelBase ); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! - // Transform of geographic point in image sensor index - virtual OutputPointType TransformPoint(const InputPointType &point) const; - // Transform of geographic point in image sensor index -- Backward Compatibility - // OutputPointType TransformPoint(const InputPointType &point, double height) const; + // Transform of geographic point in image sensor index + virtual OutputPointType TransformPoint(const InputPointType &point) const; + // Transform of geographic point in image sensor index -- Backward Compatibility + // OutputPointType TransformPoint(const InputPointType &point, double height) const; - protected: - InverseSensorModel(); - virtual ~InverseSensorModel(); +protected: + InverseSensorModel(); + virtual ~InverseSensorModel(); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private : +private : - InverseSensorModel(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented + InverseSensorModel(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; } // namespace otb diff --git a/Code/Projections/otbInverseSensorModel.txx b/Code/Projections/otbInverseSensorModel.txx index 4e4d2d4e78bc3315bcbdd8b96e7e352c77db7373..cfede3859d23da8a3b753053ca8071292323a547 100644 --- a/Code/Projections/otbInverseSensorModel.txx +++ b/Code/Projections/otbInverseSensorModel.txx @@ -26,99 +26,99 @@ namespace otb { - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - InverseSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::InverseSensorModel() - { - } - - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - InverseSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::~InverseSensorModel() - { - } +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +InverseSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::InverseSensorModel() +{ +} + +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +InverseSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::~InverseSensorModel() +{ +} - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - typename InverseSensorModel< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions>::OutputPointType - InverseSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::TransformPoint(const InputPointType &point) const - { +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +typename InverseSensorModel< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions>::OutputPointType +InverseSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::TransformPoint(const InputPointType &point) const +{ // otbMsgDevMacro(<< "Geographic point lon/lat : (" << point[0] << "," << point[1] << ")"); - // Transformation of "itk::point" in "ossim::ossimGpt" - ossimGpt ossimGPoint(point[1], point[0]); + // Transformation of "itk::point" in "ossim::ossimGpt" + ossimGpt ossimGPoint(point[1], point[0]); - if (this->m_UseDEM) - { + if (this->m_UseDEM) + { // otbMsgDevMacro(<< "USING DEM ! "); // otbMsgDevMacro(<< "Point : (" << point[1] << "," << point[0] << ")"); - double height = this->m_DEMHandler->GetHeightAboveMSL(point); + double height = this->m_DEMHandler->GetHeightAboveMSL(point); // otbMsgDevMacro(<< "height : " << height); - ossimGPoint.height(height); - } - else + ossimGPoint.height(height); + } + else + { + if (this->m_AverageElevation != -10000) { - if (this->m_AverageElevation != -10000) - { - ossimGPoint.height(this->m_AverageElevation); - } + ossimGPoint.height(this->m_AverageElevation); } + } - ossimDpt ossimDPoint; + ossimDpt ossimDPoint; - if( this->m_Model == NULL) - { - itkExceptionMacro(<<"TransformPoint(): Invalid Model pointer m_Model == NULL !"); - } + if ( this->m_Model == NULL) + { + itkExceptionMacro(<<"TransformPoint(): Invalid Model pointer m_Model == NULL !"); + } - this->m_Model->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information. + this->m_Model->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information. - OutputPointType outputPoint; + OutputPointType outputPoint; - outputPoint[0]=ossimDPoint.x; - outputPoint[1]=ossimDPoint.y; + outputPoint[0]=ossimDPoint.x; + outputPoint[1]=ossimDPoint.y; // otbMsgDevMacro(<< "Point in sensor geometry: (" << outputPoint[0] << "," << outputPoint[1] << ")"); - return outputPoint; - } - - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - InverseSensorModel< TScalarType, - NInputDimensions, - NOutputDimensions, - NParametersDimensions> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } + return outputPoint; +} + +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +InverseSensorModel< TScalarType, +NInputDimensions, +NOutputDimensions, +NParametersDimensions> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} } // namespace otb diff --git a/Code/Projections/otbLambert2EtenduProjection.h b/Code/Projections/otbLambert2EtenduProjection.h index 86c2add50f315df0f63c4bff9270891dea62f0f7..2169cf62c4e59867f9a83f6b4a1b87b981584950 100644 --- a/Code/Projections/otbLambert2EtenduProjection.h +++ b/Code/Projections/otbLambert2EtenduProjection.h @@ -25,40 +25,40 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class Lambert2EtenduProjection - * \brief This class implements the Lambert 2 Etendu map projection. - * It converts coordinates in longitude,latitude (WGS84) to Lambert 2 Etendu map coordinates. - * - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT Lambert2EtenduProjection : public LambertConformalConicMapProjection<transform> - { - public : - /** Standard class typedefs. */ - typedef Lambert2EtenduProjection Self; - typedef LambertConformalConicMapProjection<transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( Lambert2EtenduProjection, LambertConformalConicMapProjection ); - - - protected: - Lambert2EtenduProjection(); - virtual ~Lambert2EtenduProjection(); - - private : - Lambert2EtenduProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +/** \class Lambert2EtenduProjection +* \brief This class implements the Lambert 2 Etendu map projection. +* It converts coordinates in longitude,latitude (WGS84) to Lambert 2 Etendu map coordinates. +* + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT Lambert2EtenduProjection : public LambertConformalConicMapProjection<transform> +{ +public : + /** Standard class typedefs. */ + typedef Lambert2EtenduProjection Self; + typedef LambertConformalConicMapProjection<transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( Lambert2EtenduProjection, LambertConformalConicMapProjection ); + + +protected: + Lambert2EtenduProjection(); + virtual ~Lambert2EtenduProjection(); + +private : + Lambert2EtenduProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbLambert2EtenduProjection.txx b/Code/Projections/otbLambert2EtenduProjection.txx index b199b3a054251ce6fe57405ec6499244cf2989d4..177f8ab6102d659ea21b0ddbdffb7cb70d363988 100644 --- a/Code/Projections/otbLambert2EtenduProjection.txx +++ b/Code/Projections/otbLambert2EtenduProjection.txx @@ -24,35 +24,35 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - Lambert2EtenduProjection<transform> - ::Lambert2EtenduProjection() - { - itk::Point<double,2> origin; - origin[0]=2.33722778; - origin[1]=46.8; - std::string datum = "NTF"; - - - double parall1=45.89891944; - double parall2=47.69601389; - double falseEasting=600000; - double falseNorthing=2200000; - std::string ellipsoid = "CE"; - - - //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only - // SetOrigin required (remove SetEllipsoid) - this->SetOrigin(origin, datum); - this->SetEllipsoid(ellipsoid); - this->SetParameters(parall1, parall2, falseEasting, falseNorthing); - } - - template <InverseOrForwardTransformationEnum transform> - Lambert2EtenduProjection<transform> - ::~Lambert2EtenduProjection() - { - } +template <InverseOrForwardTransformationEnum transform> +Lambert2EtenduProjection<transform> +::Lambert2EtenduProjection() +{ + itk::Point<double,2> origin; + origin[0]=2.33722778; + origin[1]=46.8; + std::string datum = "NTF"; + + + double parall1=45.89891944; + double parall2=47.69601389; + double falseEasting=600000; + double falseNorthing=2200000; + std::string ellipsoid = "CE"; + + + //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only + // SetOrigin required (remove SetEllipsoid) + this->SetOrigin(origin, datum); + this->SetEllipsoid(ellipsoid); + this->SetParameters(parall1, parall2, falseEasting, falseNorthing); +} + +template <InverseOrForwardTransformationEnum transform> +Lambert2EtenduProjection<transform> +::~Lambert2EtenduProjection() +{ +} } // namespace otb diff --git a/Code/Projections/otbLambert93Projection.h b/Code/Projections/otbLambert93Projection.h index c7344a76482398f827d89c950469b46a70ff8b2e..63e456a97a6c32922f5779d8b4609a0a87a14394 100644 --- a/Code/Projections/otbLambert93Projection.h +++ b/Code/Projections/otbLambert93Projection.h @@ -25,40 +25,40 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class Lambert93Projection - * \brief This class implements the Lambert93 map projection (RGF93 french geodesic system). - * It converts coordinates in longitude,latitude (WGS84) to Lambert 93 map coordinates. - * - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT Lambert93Projection : public LambertConformalConicMapProjection<transform> - { - public : - /** Standard class typedefs. */ - typedef Lambert93Projection Self; - typedef LambertConformalConicMapProjection<transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( Lambert93Projection, LambertConformalConicMapProjection); - - - protected: - Lambert93Projection(); - virtual ~Lambert93Projection(); - - private : - Lambert93Projection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +/** \class Lambert93Projection +* \brief This class implements the Lambert93 map projection (RGF93 french geodesic system). +* It converts coordinates in longitude,latitude (WGS84) to Lambert 93 map coordinates. +* + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT Lambert93Projection : public LambertConformalConicMapProjection<transform> +{ +public : + /** Standard class typedefs. */ + typedef Lambert93Projection Self; + typedef LambertConformalConicMapProjection<transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( Lambert93Projection, LambertConformalConicMapProjection); + + +protected: + Lambert93Projection(); + virtual ~Lambert93Projection(); + +private : + Lambert93Projection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbLambert93Projection.txx b/Code/Projections/otbLambert93Projection.txx index e95a98706f76cf8fec6bd2b1fe21e03839a53703..1a272ebc1012520d5ab4db12635bed86afa5fd28 100644 --- a/Code/Projections/otbLambert93Projection.txx +++ b/Code/Projections/otbLambert93Projection.txx @@ -24,35 +24,35 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - Lambert93Projection<transform> - ::Lambert93Projection() - { - itk::Point<double,2> origin; - origin[0]=3; - origin[1]=46.5; - std::string datum = "WE"; //WGS84 datum - - - double parall1=44; - double parall2=49; - double falseEasting=700000; - double falseNorthing=6600000; - std::string ellipsoid = "RF"; //GRS-80 ellipsoid - - - //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only - // SetOrigin required (remove SetEllipsoid) - this->SetOrigin(origin, datum); - this->SetEllipsoid(ellipsoid); - this->SetParameters(parall1, parall2, falseEasting, falseNorthing); - } - - template <InverseOrForwardTransformationEnum transform> - Lambert93Projection<transform> - ::~Lambert93Projection() - { - } +template <InverseOrForwardTransformationEnum transform> +Lambert93Projection<transform> +::Lambert93Projection() +{ + itk::Point<double,2> origin; + origin[0]=3; + origin[1]=46.5; + std::string datum = "WE"; //WGS84 datum + + + double parall1=44; + double parall2=49; + double falseEasting=700000; + double falseNorthing=6600000; + std::string ellipsoid = "RF"; //GRS-80 ellipsoid + + + //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only + // SetOrigin required (remove SetEllipsoid) + this->SetOrigin(origin, datum); + this->SetEllipsoid(ellipsoid); + this->SetParameters(parall1, parall2, falseEasting, falseNorthing); +} + +template <InverseOrForwardTransformationEnum transform> +Lambert93Projection<transform> +::~Lambert93Projection() +{ +} } // namespace otb diff --git a/Code/Projections/otbLambertConformalConicMapProjection.h b/Code/Projections/otbLambertConformalConicMapProjection.h index c929cf28b68851988c74349b7a25c5c4a72210f1..63c642370bad0767c414b8859f88f29fb5819f6b 100644 --- a/Code/Projections/otbLambertConformalConicMapProjection.h +++ b/Code/Projections/otbLambertConformalConicMapProjection.h @@ -24,50 +24,50 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class LambertConformalConicMapProjection - * \brief This class implements the Lambert Conformal Conic map projection. - * It converts coordinates in longitude,latitude (WGS84) to Lambert Conformal Conic map coordinates. - * - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT LambertConformalConicMapProjection : public MapProjection<ossimLambertConformalConicProjection,transform> - { - public : - /** Standard class typedefs. */ - typedef LambertConformalConicMapProjection Self; - typedef MapProjection<ossimLambertConformalConicProjection,transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( LambertConformalConicMapProjection, MapProjection ); - - void SetStandardParallel1 (double degree); - void SetStandardParallel2 (double degree); - void SetStandardParallels (double parallel1Degree,double parallel2Degree); - void SetFalseEasting(double falseEasting); - void SetFalseNorthing(double falseNorthing); - double GetFalseNorthing() const; - double GetFalseEasting() const; - void SetParameters(double parallel1Degree,double parallel2Degree,double falseEasting,double falseNorthing); - void SetDefaults(); - - - protected: - LambertConformalConicMapProjection(); - virtual ~LambertConformalConicMapProjection(); - - private : - LambertConformalConicMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +/** \class LambertConformalConicMapProjection + * \brief This class implements the Lambert Conformal Conic map projection. + * It converts coordinates in longitude,latitude (WGS84) to Lambert Conformal Conic map coordinates. + * + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT LambertConformalConicMapProjection : public MapProjection<ossimLambertConformalConicProjection,transform> +{ +public : + /** Standard class typedefs. */ + typedef LambertConformalConicMapProjection Self; + typedef MapProjection<ossimLambertConformalConicProjection,transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( LambertConformalConicMapProjection, MapProjection ); + + void SetStandardParallel1 (double degree); + void SetStandardParallel2 (double degree); + void SetStandardParallels (double parallel1Degree,double parallel2Degree); + void SetFalseEasting(double falseEasting); + void SetFalseNorthing(double falseNorthing); + double GetFalseNorthing() const; + double GetFalseEasting() const; + void SetParameters(double parallel1Degree,double parallel2Degree,double falseEasting,double falseNorthing); + void SetDefaults(); + + +protected: + LambertConformalConicMapProjection(); + virtual ~LambertConformalConicMapProjection(); + +private : + LambertConformalConicMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbLambertConformalConicMapProjection.txx b/Code/Projections/otbLambertConformalConicMapProjection.txx index 7cb049827c80412d870d4cb37253641c06198c7b..ebc5c69bab5d6fb6e29b47331eb80511bf9a303f 100644 --- a/Code/Projections/otbLambertConformalConicMapProjection.txx +++ b/Code/Projections/otbLambertConformalConicMapProjection.txx @@ -24,93 +24,93 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - LambertConformalConicMapProjection<transform> - ::LambertConformalConicMapProjection() - { - } - - template <InverseOrForwardTransformationEnum transform> - LambertConformalConicMapProjection<transform> - ::~LambertConformalConicMapProjection() - { - } - - - /// Parallel1 specification - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetStandardParallel1(double degree) - { - this->m_MapProjection->setStandardParallel1(degree); - } - - /// Parallel2 specification - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetStandardParallel2(double degree) - { - this->m_MapProjection->setStandardParallel2(degree); - } - - /// Specification of the 2 parallels - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetStandardParallels(double parallel1Degree,double parallel2Degree) - { - this->m_MapProjection->setStandardParallels(parallel1Degree,parallel2Degree); - } - - /// False easting specification - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetFalseEasting(double falseEasting) - { - this->m_MapProjection->setFalseEasting(falseEasting); - } - - /// False Northing specification - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetFalseNorthing(double falseNorthing) - { - this->m_MapProjection->setFalseNorthing(falseNorthing); - } - - /// Set the parameters - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetParameters(double parallel1Degree,double parallel2Degree,double falseEasting,double falseNorthing) - { - this->m_MapProjection->setParameters(parallel1Degree, parallel2Degree, falseEasting, falseNorthing); - } - - /// Set the default parameters - template <InverseOrForwardTransformationEnum transform> - void LambertConformalConicMapProjection<transform> - ::SetDefaults() - { - this->m_MapProjection->setDefaults(); - } - - /// Get the False Northing (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double LambertConformalConicMapProjection<transform> - ::GetFalseNorthing() const - { - double falseNorthing=this->m_MapProjection->getFalseNorthing(); - - return falseNorthing; - } - - ///Get the False Easting (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double LambertConformalConicMapProjection<transform> - ::GetFalseEasting() const - { - double falseEasting=this->m_MapProjection->getFalseEasting(); - return falseEasting; - } +template <InverseOrForwardTransformationEnum transform> +LambertConformalConicMapProjection<transform> +::LambertConformalConicMapProjection() +{ +} + +template <InverseOrForwardTransformationEnum transform> +LambertConformalConicMapProjection<transform> +::~LambertConformalConicMapProjection() +{ +} + + +/// Parallel1 specification +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetStandardParallel1(double degree) +{ + this->m_MapProjection->setStandardParallel1(degree); +} + +/// Parallel2 specification +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetStandardParallel2(double degree) +{ + this->m_MapProjection->setStandardParallel2(degree); +} + +/// Specification of the 2 parallels +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetStandardParallels(double parallel1Degree,double parallel2Degree) +{ + this->m_MapProjection->setStandardParallels(parallel1Degree,parallel2Degree); +} + +/// False easting specification +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetFalseEasting(double falseEasting) +{ + this->m_MapProjection->setFalseEasting(falseEasting); +} + +/// False Northing specification +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetFalseNorthing(double falseNorthing) +{ + this->m_MapProjection->setFalseNorthing(falseNorthing); +} + +/// Set the parameters +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetParameters(double parallel1Degree,double parallel2Degree,double falseEasting,double falseNorthing) +{ + this->m_MapProjection->setParameters(parallel1Degree, parallel2Degree, falseEasting, falseNorthing); +} + +/// Set the default parameters +template <InverseOrForwardTransformationEnum transform> +void LambertConformalConicMapProjection<transform> +::SetDefaults() +{ + this->m_MapProjection->setDefaults(); +} + +/// Get the False Northing (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double LambertConformalConicMapProjection<transform> +::GetFalseNorthing() const +{ + double falseNorthing=this->m_MapProjection->getFalseNorthing(); + + return falseNorthing; +} + +///Get the False Easting (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double LambertConformalConicMapProjection<transform> +::GetFalseEasting() const +{ + double falseEasting=this->m_MapProjection->getFalseEasting(); + return falseEasting; +} } // namespace otb diff --git a/Code/Projections/otbMapProjection.h b/Code/Projections/otbMapProjection.h index 523295bef3b27080f4295661ca557c9d04e920b0..8dfbe4f70fd7c04f9ffce3244e22e1f38d39670d 100644 --- a/Code/Projections/otbMapProjection.h +++ b/Code/Projections/otbMapProjection.h @@ -37,113 +37,113 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class MapProjection - * \brief This is the base class for all geographic projections (UTM, Lambert, ...) - * - * The forward transformation will transform the coordinate for the geographic to the - * cartographic. The inverse model will transform from the cartographic to the geographic. - * - * All derived class assume that the latitude and longitude are given according to the - * WGS84 ellipsoid model. - * - * If you can't specify the map projection at compile time, you should use the - * GenericMapProjection instead. - * - * \ingroup Projection - * - **/ - - template <class TOssimMapProjection, - InverseOrForwardTransformationEnum TDirectionOfMapping, - class TScalarType = double, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2> - class ITK_EXPORT MapProjection: public itk::Transform<TScalarType, // Data type for scalars - NInputDimensions, // Number of dimensions in the input space - NOutputDimensions> // Number of dimensions in the output space - { - public : - /** Standard class typedefs. */ - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef MapProjection Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef TOssimMapProjection OssimMapProjectionType; - typedef itk::Point<ScalarType,NInputDimensions > InputPointType; - typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( MapProjection, itk::Transform ); - - virtual const OssimMapProjectionType* GetMapProjection () const; - virtual OssimMapProjectionType* GetMapProjection (); - - typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; - - itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,TDirectionOfMapping); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); - - - virtual void SetEllipsoid (); - void SetEllipsoid (const ossimEllipsoid &ellipsoid); - void SetEllipsoid(std::string code); - void SetEllipsoid(const double &major_axis, const double &minor_axis); - - OutputPointType TransformPoint(const InputPointType &point) const; - virtual InputPointType Origin(); - virtual double GetFalseNorthing() const; - virtual double GetFalseEasting() const; - virtual double GetStandardParallel1() const; - virtual double GetStandardParallel2() const; - virtual std::string GetProjectionName() const; - virtual bool IsGeographic() const; - virtual double GetA() const; - virtual double GetB() const; - virtual double GetF() const; - virtual OutputPointType GetMetersPerPixel() const; - virtual OutputPointType GetDecimalDegreesPerPixel() const; - virtual void SetAB(double a, double b); - virtual void SetOrigin(const InputPointType &origin); - virtual void SetOrigin(const InputPointType &origin, std::string datumCode); - virtual void SetMetersPerPixel(const OutputPointType &point); - virtual void SetDecimalDegreesPerPixel(const OutputPointType &point); - virtual void ComputeDegreesPerPixel(const InputPointType &ground, const OutputPointType &metersPerPixel, double &deltaLat, double &deltaLon); - virtual void ComputeMetersPerPixel(const InputPointType ¢er, double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel); - virtual void ComputeMetersPerPixel(double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel); - //virtual void SetMatrix(double rotation, const OutputPointType &scale, const OutputPointType &translation); - void SetFalseEasting(double falseEasting); - - /** Return the Wkt representation of the projection*/ - virtual std::string GetWkt() const; - - /** Instanciate the projection according to the Wkt specification*/ - virtual void SetWkt(std::string projectionRefWkt); - - virtual void PrintMap() const; - - - protected: - MapProjection(); - virtual ~MapProjection(); - OssimMapProjectionType* m_MapProjection; - std::string m_ProjectionRefWkt; - virtual void InstanciateProjection(); - - private : - MapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class MapProjection + * \brief This is the base class for all geographic projections (UTM, Lambert, ...) + * + * The forward transformation will transform the coordinate for the geographic to the + * cartographic. The inverse model will transform from the cartographic to the geographic. + * + * All derived class assume that the latitude and longitude are given according to the + * WGS84 ellipsoid model. + * + * If you can't specify the map projection at compile time, you should use the + * GenericMapProjection instead. + * + * \ingroup Projection + * + **/ + +template <class TOssimMapProjection, +InverseOrForwardTransformationEnum TDirectionOfMapping, +class TScalarType = double, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2> +class ITK_EXPORT MapProjection: public itk::Transform<TScalarType, // Data type for scalars + NInputDimensions, // Number of dimensions in the input space + NOutputDimensions> // Number of dimensions in the output space +{ +public : + /** Standard class typedefs. */ + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef MapProjection Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef TOssimMapProjection OssimMapProjectionType; + typedef itk::Point<ScalarType,NInputDimensions > InputPointType; + typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( MapProjection, itk::Transform ); + + virtual const OssimMapProjectionType* GetMapProjection () const; + virtual OssimMapProjectionType* GetMapProjection (); + + typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; + + itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,TDirectionOfMapping); + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); + + + virtual void SetEllipsoid (); + void SetEllipsoid (const ossimEllipsoid &ellipsoid); + void SetEllipsoid(std::string code); + void SetEllipsoid(const double &major_axis, const double &minor_axis); + + OutputPointType TransformPoint(const InputPointType &point) const; + virtual InputPointType Origin(); + virtual double GetFalseNorthing() const; + virtual double GetFalseEasting() const; + virtual double GetStandardParallel1() const; + virtual double GetStandardParallel2() const; + virtual std::string GetProjectionName() const; + virtual bool IsGeographic() const; + virtual double GetA() const; + virtual double GetB() const; + virtual double GetF() const; + virtual OutputPointType GetMetersPerPixel() const; + virtual OutputPointType GetDecimalDegreesPerPixel() const; + virtual void SetAB(double a, double b); + virtual void SetOrigin(const InputPointType &origin); + virtual void SetOrigin(const InputPointType &origin, std::string datumCode); + virtual void SetMetersPerPixel(const OutputPointType &point); + virtual void SetDecimalDegreesPerPixel(const OutputPointType &point); + virtual void ComputeDegreesPerPixel(const InputPointType &ground, const OutputPointType &metersPerPixel, double &deltaLat, double &deltaLon); + virtual void ComputeMetersPerPixel(const InputPointType ¢er, double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel); + virtual void ComputeMetersPerPixel(double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel); + //virtual void SetMatrix(double rotation, const OutputPointType &scale, const OutputPointType &translation); + void SetFalseEasting(double falseEasting); + + /** Return the Wkt representation of the projection*/ + virtual std::string GetWkt() const; + + /** Instanciate the projection according to the Wkt specification*/ + virtual void SetWkt(std::string projectionRefWkt); + + virtual void PrintMap() const; + + +protected: + MapProjection(); + virtual ~MapProjection(); + OssimMapProjectionType* m_MapProjection; + std::string m_ProjectionRefWkt; + virtual void InstanciateProjection(); + +private : + MapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; diff --git a/Code/Projections/otbMapProjection.txx b/Code/Projections/otbMapProjection.txx index 19d6f7ac29b06bbe28147b524460687b57d90ff6..5c38fa81046301ee23a6b0f6c4aceaf1be57c6c5 100644 --- a/Code/Projections/otbMapProjection.txx +++ b/Code/Projections/otbMapProjection.txx @@ -24,99 +24,99 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::MapProjection() : Superclass(SpaceDimension,ParametersDimension) - { - m_MapProjection = NULL; - m_ProjectionRefWkt.clear(); - this->InstanciateProjection(); - } - - +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::MapProjection() : Superclass(SpaceDimension,ParametersDimension) +{ + m_MapProjection = NULL; + m_ProjectionRefWkt.clear(); + this->InstanciateProjection(); +} - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::~MapProjection() - { - if (m_MapProjection != NULL) - { - delete m_MapProjection; - } - } - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - const TOssimMapProjection* - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetMapProjection () const +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::~MapProjection() +{ + if (m_MapProjection != NULL) { - return this->m_MapProjection; + delete m_MapProjection; } +} - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - TOssimMapProjection* - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetMapProjection () - { - return this->m_MapProjection; - } - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::InstanciateProjection () - { - m_MapProjection = new OssimMapProjectionType(); - } +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +const TOssimMapProjection* +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetMapProjection () const +{ + return this->m_MapProjection; +} +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +TOssimMapProjection* +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetMapProjection () +{ + return this->m_MapProjection; +} - /// Method to set the projection ellipsoid - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetEllipsoid() - { - ossimEllipsoid ellipsoid; - this->GetMapProjection()->setEllipsoid(ellipsoid); - } +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::InstanciateProjection () +{ + m_MapProjection = new OssimMapProjectionType(); +} - /// Method to set the projection ellipsoid by copy - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetEllipsoid(const ossimEllipsoid &ellipsoid) - { - this->GetMapProjection()->setEllipsoid(ellipsoid); - } - ///// Method to set the projection ellipsoid by knowing its code - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetEllipsoid(std::string code) - { - const ossimEllipsoid ellipsoid = *(ossimEllipsoidFactory::instance()->create(ossimString(code))); - this->GetMapProjection()->setEllipsoid(ellipsoid); - } +/// Method to set the projection ellipsoid +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetEllipsoid() +{ + ossimEllipsoid ellipsoid; + this->GetMapProjection()->setEllipsoid(ellipsoid); +} + +/// Method to set the projection ellipsoid by copy +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetEllipsoid(const ossimEllipsoid &ellipsoid) +{ + this->GetMapProjection()->setEllipsoid(ellipsoid); +} - ///// Method to set the projection ellipsoid by knowing its axis - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetEllipsoid(const double &major_axis, const double &minor_axis) - { - ossimEllipsoid ellipsoid(major_axis,minor_axis); - this->GetMapProjection()->setEllipsoid(ellipsoid); - } +///// Method to set the projection ellipsoid by knowing its code +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetEllipsoid(std::string code) +{ + const ossimEllipsoid ellipsoid = *(ossimEllipsoidFactory::instance()->create(ossimString(code))); + this->GetMapProjection()->setEllipsoid(ellipsoid); +} + +///// Method to set the projection ellipsoid by knowing its axis +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetEllipsoid(const double &major_axis, const double &minor_axis) +{ + ossimEllipsoid ellipsoid(major_axis,minor_axis); + this->GetMapProjection()->setEllipsoid(ellipsoid); +} + +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::TransformPoint(const InputPointType & point) const +{ + OutputPointType outputPoint; - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::TransformPoint(const InputPointType & point) const + switch (DirectionOfMapping) { - OutputPointType outputPoint; - - switch(DirectionOfMapping) - { - case INVERSE: + case INVERSE: { // otbMsgDevMacro(<< "Cartographic coordinates: (" << point[0] << "," << point[1] << ")"); @@ -126,7 +126,7 @@ namespace otb //map projection ossimGpt ossimGPoint; ossimGPoint=this->GetMapProjection()->inverse(ossimDPoint); - ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84() ); + ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84() ); // otbGenericMsgDebugMacro(<< "Inverse : " << std::endl << this->GetMapProjection()->print(std::cout)); outputPoint[0]=ossimGPoint.lon; @@ -134,14 +134,14 @@ namespace otb // otbMsgDevMacro(<< "Geographic coordinates (lon, lat) : (" << outputPoint[0] << "," << outputPoint[1] << ")"); break; } - case FORWARD: + case FORWARD: { // otbMsgDevMacro(<< "Geographic coordinates (lon, lat) : (" << point[1] << "," << point[0] << ")"); //from "itk::point" to "ossim::ossimGpt" ossimGpt ossimGPoint(point[1], point[0]); //map projection - ossimDpt ossimDPoint; + ossimDpt ossimDPoint; ossimDPoint=this->GetMapProjection()->forward(ossimGPoint); // otbGenericMsgDebugMacro(<< "Forward : ========================= " << std::endl << m_MapProjection->print(std::cout)); outputPoint[0]=ossimDPoint.x; @@ -151,273 +151,273 @@ namespace otb break; } - default: + default: { itkExceptionMacro(<<"Model is INVERSE or FORWARD only !!"); break; } - } - - return outputPoint; - } - - - - ///\return The geographic point corresponding to (0,0) - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::InputPointType - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::Origin() - { - ossimGpt ossimOrigin=this->GetMapProjection()->origin(); - InputPointType otbOrigin; - otbOrigin[0]= ossimOrigin.lat; - otbOrigin[1]= ossimOrigin.lon; - - return otbOrigin; - } - - ///\return The False Northing(avoid negative coordinates) - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetFalseNorthing() const - { - double falseNorthing=this->GetMapProjection()->getFalseNorthing(); - - return falseNorthing; - } - - ///\return The FalseEasting(avoid negative coordinates) - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetFalseEasting() const - { - double falseEasting=this->GetMapProjection()->getFalseEasting(); - - return falseEasting; - } - - ///\return The StandardParallel1(depends on the projection type) - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetStandardParallel1() const - { - double standardParallel1=this->GetMapProjection()->getStandardParallel1(); - - return standardParallel1; } - ///\return The StandardParallel2(depends on the projection type) - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetStandardParallel2() const - { - double standardParallel2=this->GetMapProjection()->getStandardParallel2(); - - return standardParallel2; - } + return outputPoint; +} - ///\return The projection name - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - std::string - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetProjectionName() const - { - std::string projectionName; - projectionName=this->GetMapProjection()->getProjectionName(); - return projectionName; - } - ///Check if the projection is geographic - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - bool - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::IsGeographic() const - { - return (this->GetMapProjection()->isGeographic()); - } +///\return The geographic point corresponding to (0,0) +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::InputPointType +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::Origin() +{ + ossimGpt ossimOrigin=this->GetMapProjection()->origin(); + InputPointType otbOrigin; + otbOrigin[0]= ossimOrigin.lat; + otbOrigin[1]= ossimOrigin.lon; + + return otbOrigin; +} + +///\return The False Northing(avoid negative coordinates) +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetFalseNorthing() const +{ + double falseNorthing=this->GetMapProjection()->getFalseNorthing(); - ///\return the major axis of the ellipsoid - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetA() const - { - double majorAxis=this->GetMapProjection()->getA(); + return falseNorthing; +} - return majorAxis; - } +///\return The FalseEasting(avoid negative coordinates) +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetFalseEasting() const +{ + double falseEasting=this->GetMapProjection()->getFalseEasting(); - ///\return the minor axis of the ellipsoid - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetB() const - { - double minorAxis=this->GetMapProjection()->getB(); + return falseEasting; +} - return minorAxis; - } +///\return The StandardParallel1(depends on the projection type) +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetStandardParallel1() const +{ + double standardParallel1=this->GetMapProjection()->getStandardParallel1(); - ///\return the flatening of the ellipsoid - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - double - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetF() const - { - double flattening=this->GetMapProjection()->getF(); + return standardParallel1; +} - return flattening; - } +///\return The StandardParallel2(depends on the projection type) +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetStandardParallel2() const +{ + double standardParallel2=this->GetMapProjection()->getStandardParallel2(); - ///\return The resolution in meters - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetMetersPerPixel() const - { - ossimDpt ossimMetersPerPixels=this->GetMapProjection()->getMetersPerPixel(); - OutputPointType metersPerPixels; + return standardParallel2; +} - metersPerPixels[0]=ossimMetersPerPixels.x; - metersPerPixels[1]=ossimMetersPerPixels.y; +///\return The projection name +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +std::string +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetProjectionName() const +{ + std::string projectionName; + projectionName=this->GetMapProjection()->getProjectionName(); - return metersPerPixels; - } + return projectionName; +} - ///\return The resolution in degree - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetDecimalDegreesPerPixel() const - { - ossimDpt ossimDecimalDegreesPerPixels=this->GetMapProjection()->getDecimalDegreesPerPixel(); - OutputPointType DecimalDegreesPerPixels; +///Check if the projection is geographic +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +bool +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::IsGeographic() const +{ + return (this->GetMapProjection()->isGeographic()); +} + +///\return the major axis of the ellipsoid +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetA() const +{ + double majorAxis=this->GetMapProjection()->getA(); - DecimalDegreesPerPixels[0]=ossimDecimalDegreesPerPixels.x; - DecimalDegreesPerPixels[1]=ossimDecimalDegreesPerPixels.y; + return majorAxis; +} - return DecimalDegreesPerPixels; - } +///\return the minor axis of the ellipsoid +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetB() const +{ + double minorAxis=this->GetMapProjection()->getB(); - ///Set the ellipsoid axis - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetAB(double a, double b) - { - this->GetMapProjection()->setAB(a,b); - } + return minorAxis; +} - ///Set the origin - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetOrigin(const InputPointType &origin) - { - ossimGpt ossimOrigin(origin[1], origin[0]); - this->GetMapProjection()->setOrigin(ossimOrigin); - //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only - // SetOrigin required (remove SetDatum) - this->GetMapProjection()->setDatum(ossimOrigin.datum()); - } +///\return the flatening of the ellipsoid +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +double +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetF() const +{ + double flattening=this->GetMapProjection()->getF(); - ///Set the origin in a given datum - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetOrigin(const InputPointType &origin, std::string datumCode) - { - ossimGpt ossimOrigin(origin[1], origin[0], 0, ossimDatumFactory::instance()->create(datumCode)); - this->GetMapProjection()->setOrigin(ossimOrigin); - this->GetMapProjection()->setDatum(ossimOrigin.datum()); - } + return flattening; +} - ///Set the map resolution in meters - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetMetersPerPixel(const OutputPointType &point) - { - ossimDpt ossimDPoint(point[0], point[1]); - this->GetMapProjection()->setMetersPerPixel(ossimDPoint); - } +///\return The resolution in meters +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetMetersPerPixel() const +{ + ossimDpt ossimMetersPerPixels=this->GetMapProjection()->getMetersPerPixel(); + OutputPointType metersPerPixels; - ///Set the map resolution in degree - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetDecimalDegreesPerPixel(const OutputPointType &point) - { - ossimDpt ossimDPoint(point[0], point[1]); - this->GetMapProjection()->setDecimalDegreesPerPixel(ossimDPoint); - } + metersPerPixels[0]=ossimMetersPerPixels.x; + metersPerPixels[1]=ossimMetersPerPixels.y; - ///\return an approximation of the resolution in degree - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::ComputeDegreesPerPixel(const InputPointType &ground, const OutputPointType &metersPerPixel, double &deltaLat, double &deltaLon) - { - ossimDpt ossimMetersPerPixel(metersPerPixel[0], metersPerPixel[1]); - ossimGpt ossimGround(ground[1],ground[0]); - this->GetMapProjection()->computeDegreesPerPixel(ossimGround,ossimMetersPerPixel,deltaLat,deltaLon); - } + return metersPerPixels; +} - ///\return an approximation of the resolution in meters - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::ComputeMetersPerPixel(const InputPointType ¢er, double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel) - { - //Correction - ossimGpt ossimCenter(center[1],center[0]); - ossimDpt ossimMetersPerPixel; - this->GetMapProjection()->computeMetersPerPixel(ossimCenter,deltaDegreesPerPixelLat, deltaDegreesPerPixelLon,ossimMetersPerPixel); - metersPerPixel[0]=ossimMetersPerPixel.x; - metersPerPixel[1]=ossimMetersPerPixel.y; - } +///\return The resolution in degree +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetDecimalDegreesPerPixel() const +{ + ossimDpt ossimDecimalDegreesPerPixels=this->GetMapProjection()->getDecimalDegreesPerPixel(); + OutputPointType DecimalDegreesPerPixels; - ///\return an approximation of the resolution in meters - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::ComputeMetersPerPixel(double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel) - { - ossimDpt ossimMetersPerPixel; - this->GetMapProjection()->computeMetersPerPixel(this->GetMapProjection()->origin(),deltaDegreesPerPixelLat, deltaDegreesPerPixelLon,ossimMetersPerPixel); - metersPerPixel[0]=ossimMetersPerPixel.x; - metersPerPixel[1]=ossimMetersPerPixel.y; - } + DecimalDegreesPerPixels[0]=ossimDecimalDegreesPerPixels.x; + DecimalDegreesPerPixels[1]=ossimDecimalDegreesPerPixels.y; - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - std::string - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::GetWkt() const - { - ossimKeywordlist kwl; - this->GetMapProjection()->saveState(kwl); - ossimOgcWktTranslator wktTranslator; - std::string wkt; - wkt = wktTranslator.fromOssimKwl(kwl); - return wkt; - } + return DecimalDegreesPerPixels; +} - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetWkt(std::string projectionRefWkt) - { - this->m_ProjectionRefWkt=projectionRefWkt; - this->Modified(); - } +///Set the ellipsoid axis +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetAB(double a, double b) +{ + this->GetMapProjection()->setAB(a,b); +} - template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::PrintMap() const - { - std::cout << this->GetMapProjection()->print(std::cout); - } +///Set the origin +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetOrigin(const InputPointType &origin) +{ + ossimGpt ossimOrigin(origin[1], origin[0]); + this->GetMapProjection()->setOrigin(ossimOrigin); + //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only + // SetOrigin required (remove SetDatum) + this->GetMapProjection()->setDatum(ossimOrigin.datum()); +} + +///Set the origin in a given datum +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetOrigin(const InputPointType &origin, std::string datumCode) +{ + ossimGpt ossimOrigin(origin[1], origin[0], 0, ossimDatumFactory::instance()->create(datumCode)); + this->GetMapProjection()->setOrigin(ossimOrigin); + this->GetMapProjection()->setDatum(ossimOrigin.datum()); +} + +///Set the map resolution in meters +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetMetersPerPixel(const OutputPointType &point) +{ + ossimDpt ossimDPoint(point[0], point[1]); + this->GetMapProjection()->setMetersPerPixel(ossimDPoint); +} + +///Set the map resolution in degree +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetDecimalDegreesPerPixel(const OutputPointType &point) +{ + ossimDpt ossimDPoint(point[0], point[1]); + this->GetMapProjection()->setDecimalDegreesPerPixel(ossimDPoint); +} + +///\return an approximation of the resolution in degree +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::ComputeDegreesPerPixel(const InputPointType &ground, const OutputPointType &metersPerPixel, double &deltaLat, double &deltaLon) +{ + ossimDpt ossimMetersPerPixel(metersPerPixel[0], metersPerPixel[1]); + ossimGpt ossimGround(ground[1],ground[0]); + this->GetMapProjection()->computeDegreesPerPixel(ossimGround,ossimMetersPerPixel,deltaLat,deltaLon); +} + +///\return an approximation of the resolution in meters +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::ComputeMetersPerPixel(const InputPointType ¢er, double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel) +{ + //Correction + ossimGpt ossimCenter(center[1],center[0]); + ossimDpt ossimMetersPerPixel; + this->GetMapProjection()->computeMetersPerPixel(ossimCenter,deltaDegreesPerPixelLat, deltaDegreesPerPixelLon,ossimMetersPerPixel); + metersPerPixel[0]=ossimMetersPerPixel.x; + metersPerPixel[1]=ossimMetersPerPixel.y; +} + +///\return an approximation of the resolution in meters +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::ComputeMetersPerPixel(double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, OutputPointType &metersPerPixel) +{ + ossimDpt ossimMetersPerPixel; + this->GetMapProjection()->computeMetersPerPixel(this->GetMapProjection()->origin(),deltaDegreesPerPixelLat, deltaDegreesPerPixelLon,ossimMetersPerPixel); + metersPerPixel[0]=ossimMetersPerPixel.x; + metersPerPixel[1]=ossimMetersPerPixel.y; +} + +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +std::string +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::GetWkt() const +{ + ossimKeywordlist kwl; + this->GetMapProjection()->saveState(kwl); + ossimOgcWktTranslator wktTranslator; + std::string wkt; + wkt = wktTranslator.fromOssimKwl(kwl); + return wkt; +} + +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetWkt(std::string projectionRefWkt) +{ + this->m_ProjectionRefWkt=projectionRefWkt; + this->Modified(); +} + +template<class TOssimMapProjection, InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +MapProjection<TOssimMapProjection, Transform, TScalarType, NInputDimensions, NOutputDimensions> +::PrintMap() const +{ + std::cout << this->GetMapProjection()->print(std::cout); +} diff --git a/Code/Projections/otbMapProjections.h b/Code/Projections/otbMapProjections.h index a24cb76081ac97e5693cbdbcbe2b0f3545e13746..2a8b6796695a1691024fbad8c7e504bdf72088c1 100644 --- a/Code/Projections/otbMapProjections.h +++ b/Code/Projections/otbMapProjections.h @@ -60,70 +60,70 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - typedef MapProjection<ossimAlbersProjection,INVERSE> AlbersInverseProjection; - typedef MapProjection<ossimAlbersProjection,FORWARD> AlbersForwardProjection; - typedef MapProjection<ossimAzimEquDistProjection,INVERSE> AzimEquDistInverseProjection; - typedef MapProjection<ossimAzimEquDistProjection,FORWARD> AzimEquDistForwardProjection; - typedef MapProjection<ossimBngProjection,INVERSE> BngInverseProjection; - typedef MapProjection<ossimBngProjection,FORWARD> BngForwardProjection; - typedef MapProjection<ossimBonneProjection,INVERSE> BonneInverseProjection; - typedef MapProjection<ossimBonneProjection,FORWARD> BonneForwardProjection; - typedef MapProjection<ossimCadrgProjection,INVERSE> CadrgInverseProjection; - typedef MapProjection<ossimCadrgProjection,FORWARD> CadrgForwardProjection; - typedef MapProjection<ossimCassiniProjection,INVERSE> CassiniInverseProjection; - typedef MapProjection<ossimCassiniProjection,FORWARD> CassiniForwardProjection; - typedef MapProjection<ossimCylEquAreaProjection,INVERSE> CylEquAreaInverseProjection; - typedef MapProjection<ossimCylEquAreaProjection,FORWARD> CylEquAreaForwardProjection; - typedef Eckert4MapProjection<INVERSE> Eckert4InverseProjection; - typedef Eckert4MapProjection<FORWARD> Eckert4ForwardProjection; - typedef MapProjection<ossimEckert6Projection,INVERSE> Eckert6InverseProjection; - typedef MapProjection<ossimEckert6Projection,FORWARD> Eckert6ForwardProjection; - typedef MapProjection<ossimGnomonicProjection,INVERSE> GnomonicInverseProjection; - typedef MapProjection<ossimGnomonicProjection,FORWARD> GnomonicForwardProjection; - typedef LambertConformalConicMapProjection<INVERSE> LambertConformalConicInverseProjection; - typedef LambertConformalConicMapProjection<FORWARD> LambertConformalConicForwardProjection; - typedef Lambert2EtenduProjection<INVERSE> Lambert2EtenduInverseProjection; - typedef Lambert2EtenduProjection<FORWARD> Lambert2EtenduForwardProjection; - typedef Lambert93Projection<INVERSE> Lambert93InverseProjection; - typedef Lambert93Projection<FORWARD> Lambert93ForwardProjection; - typedef SVY21MapProjection<INVERSE> SVY21InverseProjection; - typedef SVY21MapProjection<FORWARD> SVY21ForwardProjection; - typedef MapProjection<ossimLlxyProjection,INVERSE> LlxyInverseProjection; - typedef MapProjection<ossimLlxyProjection,FORWARD> LlxyForwardProjection; - typedef MapProjection<ossimEquDistCylProjection,INVERSE> EquDistCylInverseProjection; - typedef MapProjection<ossimEquDistCylProjection,FORWARD> EquDistCylForwardProjection; - typedef MapProjection<ossimMercatorProjection,INVERSE> MercatorInverseProjection; - typedef MapProjection<ossimMercatorProjection,FORWARD> MercatorForwardProjection; - typedef MapProjection<ossimMillerProjection,INVERSE> MillerInverseProjection; - typedef MapProjection<ossimMillerProjection,FORWARD> MillerForwardProjection; - typedef MollweidMapProjection<INVERSE> MollweidInverseProjection; - typedef MollweidMapProjection<FORWARD> MollweidForwardProjection; - typedef MapProjection<ossimNewZealandMapGridProjection,INVERSE> NewZealandMapGridInverseProjection; - typedef MapProjection<ossimNewZealandMapGridProjection,FORWARD> NewZealandMapGridForwardProjection; - typedef MapProjection<ossimObliqueMercatorProjection,INVERSE> ObliqueMercatorInverseProjection; - typedef MapProjection<ossimObliqueMercatorProjection,FORWARD> ObliqueMercatorForwardProjection; - typedef MapProjection<ossimOrthoGraphicProjection,INVERSE> OrthoGraphicInverseProjection; - typedef MapProjection<ossimOrthoGraphicProjection,FORWARD> OrthoGraphicForwardProjection; - typedef MapProjection<ossimPolarStereoProjection,INVERSE> PolarStereoInverseProjection; - typedef MapProjection<ossimPolarStereoProjection,FORWARD> PolarStereoForwardProjection; - typedef MapProjection<ossimPolyconicProjection,INVERSE> PolyconicInverseProjection; - typedef MapProjection<ossimPolyconicProjection,FORWARD> PolyconicForwardProjection; - typedef SinusoidalMapProjection<INVERSE> SinusoidalInverseProjection; - typedef SinusoidalMapProjection<FORWARD> SinusoidalForwardProjection; - typedef MapProjection<ossimSpaceObliqueMercatorProjection,INVERSE> SpaceObliqueMercatorInverseProjection; - typedef MapProjection<ossimSpaceObliqueMercatorProjection,FORWARD> SpaceObliqueMercatorForwardProjection; - typedef MapProjection<ossimStereographicProjection,INVERSE> StereographicInverseProjection; - typedef MapProjection<ossimStereographicProjection,FORWARD> StereographicForwardProjection; - typedef MapProjection<ossimTransCylEquAreaProjection,INVERSE> TransCylEquAreaInverseProjection; - typedef MapProjection<ossimTransCylEquAreaProjection,FORWARD> TransCylEquAreaForwardProjection; - typedef TransMercatorMapProjection<INVERSE> TransMercatorInverseProjection; - typedef TransMercatorMapProjection<FORWARD> TransMercatorForwardProjection; - typedef MapProjection<ossimUpsProjection,INVERSE> UpsInverseProjection; - typedef MapProjection<ossimUpsProjection,FORWARD> UpsForwardProjection; - typedef UtmMapProjection<INVERSE> UtmInverseProjection; - typedef UtmMapProjection<FORWARD> UtmForwardProjection; - typedef MapProjection<ossimVanDerGrintenProjection,INVERSE> VanDerGrintenInverseProjection; - typedef MapProjection<ossimVanDerGrintenProjection,FORWARD> VanDerGrintenForwardProjection; +typedef MapProjection<ossimAlbersProjection,INVERSE> AlbersInverseProjection; +typedef MapProjection<ossimAlbersProjection,FORWARD> AlbersForwardProjection; +typedef MapProjection<ossimAzimEquDistProjection,INVERSE> AzimEquDistInverseProjection; +typedef MapProjection<ossimAzimEquDistProjection,FORWARD> AzimEquDistForwardProjection; +typedef MapProjection<ossimBngProjection,INVERSE> BngInverseProjection; +typedef MapProjection<ossimBngProjection,FORWARD> BngForwardProjection; +typedef MapProjection<ossimBonneProjection,INVERSE> BonneInverseProjection; +typedef MapProjection<ossimBonneProjection,FORWARD> BonneForwardProjection; +typedef MapProjection<ossimCadrgProjection,INVERSE> CadrgInverseProjection; +typedef MapProjection<ossimCadrgProjection,FORWARD> CadrgForwardProjection; +typedef MapProjection<ossimCassiniProjection,INVERSE> CassiniInverseProjection; +typedef MapProjection<ossimCassiniProjection,FORWARD> CassiniForwardProjection; +typedef MapProjection<ossimCylEquAreaProjection,INVERSE> CylEquAreaInverseProjection; +typedef MapProjection<ossimCylEquAreaProjection,FORWARD> CylEquAreaForwardProjection; +typedef Eckert4MapProjection<INVERSE> Eckert4InverseProjection; +typedef Eckert4MapProjection<FORWARD> Eckert4ForwardProjection; +typedef MapProjection<ossimEckert6Projection,INVERSE> Eckert6InverseProjection; +typedef MapProjection<ossimEckert6Projection,FORWARD> Eckert6ForwardProjection; +typedef MapProjection<ossimGnomonicProjection,INVERSE> GnomonicInverseProjection; +typedef MapProjection<ossimGnomonicProjection,FORWARD> GnomonicForwardProjection; +typedef LambertConformalConicMapProjection<INVERSE> LambertConformalConicInverseProjection; +typedef LambertConformalConicMapProjection<FORWARD> LambertConformalConicForwardProjection; +typedef Lambert2EtenduProjection<INVERSE> Lambert2EtenduInverseProjection; +typedef Lambert2EtenduProjection<FORWARD> Lambert2EtenduForwardProjection; +typedef Lambert93Projection<INVERSE> Lambert93InverseProjection; +typedef Lambert93Projection<FORWARD> Lambert93ForwardProjection; +typedef SVY21MapProjection<INVERSE> SVY21InverseProjection; +typedef SVY21MapProjection<FORWARD> SVY21ForwardProjection; +typedef MapProjection<ossimLlxyProjection,INVERSE> LlxyInverseProjection; +typedef MapProjection<ossimLlxyProjection,FORWARD> LlxyForwardProjection; +typedef MapProjection<ossimEquDistCylProjection,INVERSE> EquDistCylInverseProjection; +typedef MapProjection<ossimEquDistCylProjection,FORWARD> EquDistCylForwardProjection; +typedef MapProjection<ossimMercatorProjection,INVERSE> MercatorInverseProjection; +typedef MapProjection<ossimMercatorProjection,FORWARD> MercatorForwardProjection; +typedef MapProjection<ossimMillerProjection,INVERSE> MillerInverseProjection; +typedef MapProjection<ossimMillerProjection,FORWARD> MillerForwardProjection; +typedef MollweidMapProjection<INVERSE> MollweidInverseProjection; +typedef MollweidMapProjection<FORWARD> MollweidForwardProjection; +typedef MapProjection<ossimNewZealandMapGridProjection,INVERSE> NewZealandMapGridInverseProjection; +typedef MapProjection<ossimNewZealandMapGridProjection,FORWARD> NewZealandMapGridForwardProjection; +typedef MapProjection<ossimObliqueMercatorProjection,INVERSE> ObliqueMercatorInverseProjection; +typedef MapProjection<ossimObliqueMercatorProjection,FORWARD> ObliqueMercatorForwardProjection; +typedef MapProjection<ossimOrthoGraphicProjection,INVERSE> OrthoGraphicInverseProjection; +typedef MapProjection<ossimOrthoGraphicProjection,FORWARD> OrthoGraphicForwardProjection; +typedef MapProjection<ossimPolarStereoProjection,INVERSE> PolarStereoInverseProjection; +typedef MapProjection<ossimPolarStereoProjection,FORWARD> PolarStereoForwardProjection; +typedef MapProjection<ossimPolyconicProjection,INVERSE> PolyconicInverseProjection; +typedef MapProjection<ossimPolyconicProjection,FORWARD> PolyconicForwardProjection; +typedef SinusoidalMapProjection<INVERSE> SinusoidalInverseProjection; +typedef SinusoidalMapProjection<FORWARD> SinusoidalForwardProjection; +typedef MapProjection<ossimSpaceObliqueMercatorProjection,INVERSE> SpaceObliqueMercatorInverseProjection; +typedef MapProjection<ossimSpaceObliqueMercatorProjection,FORWARD> SpaceObliqueMercatorForwardProjection; +typedef MapProjection<ossimStereographicProjection,INVERSE> StereographicInverseProjection; +typedef MapProjection<ossimStereographicProjection,FORWARD> StereographicForwardProjection; +typedef MapProjection<ossimTransCylEquAreaProjection,INVERSE> TransCylEquAreaInverseProjection; +typedef MapProjection<ossimTransCylEquAreaProjection,FORWARD> TransCylEquAreaForwardProjection; +typedef TransMercatorMapProjection<INVERSE> TransMercatorInverseProjection; +typedef TransMercatorMapProjection<FORWARD> TransMercatorForwardProjection; +typedef MapProjection<ossimUpsProjection,INVERSE> UpsInverseProjection; +typedef MapProjection<ossimUpsProjection,FORWARD> UpsForwardProjection; +typedef UtmMapProjection<INVERSE> UtmInverseProjection; +typedef UtmMapProjection<FORWARD> UtmForwardProjection; +typedef MapProjection<ossimVanDerGrintenProjection,INVERSE> VanDerGrintenInverseProjection; +typedef MapProjection<ossimVanDerGrintenProjection,FORWARD> VanDerGrintenForwardProjection; }//namespace otb #endif diff --git a/Code/Projections/otbMapToMapProjection.h b/Code/Projections/otbMapToMapProjection.h index 7a39f53221f85b6ea764ec7463bd258f8c261fc7..2f9ac8fab7a22a4819ae0e4aa8e0af3ea201398f 100644 --- a/Code/Projections/otbMapToMapProjection.h +++ b/Code/Projections/otbMapToMapProjection.h @@ -29,61 +29,61 @@ namespace otb { - /** \class MapToMapProjection - - * \brief Class for switching from a Map Projection coordinates to other Map Projection coordinates. - * It converts MapProjection1 coordinates to MapProjection2 coordinates by using MapProjection methods. - * It takes a point in input. - * (X_1, Y_1) -> (lat, lon) -> (X_2, Y_2) - * \ingroup Transform - */ - template <class TInputMapProjection, - class TOutputMapProjection, - class TScalarType=double, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2> - class ITK_EXPORT MapToMapProjection: public itk::Transform<TScalarType, // Data type for scalars - NInputDimensions, // Number of dimensions in the input space - NOutputDimensions> // Number of dimensions in the output space - { - public : - /** Standard class typedefs */ - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef MapToMapProjection Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef TInputMapProjection InputMapProjectionType; - typedef typename InputMapProjectionType::Pointer InputMapProjectionPointerType; - typedef typename InputMapProjectionType::OutputPointType OutputPointOfInputMapProjectionType; - - typedef TOutputMapProjection OutputMapProjectionType; - typedef typename OutputMapProjectionType::Pointer OutputMapProjectionPointerType; - - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( MapToMapProjection, itk::Transform ); - - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int, NInputDimensions*(NInputDimensions+1)); - - /** Set MapProjection1. */ - itkSetObjectMacro(InputMapProjection,InputMapProjectionType); - - /** Set MapProjection2. */ - itkSetObjectMacro(OutputMapProjection,OutputMapProjectionType); - - /** Transform Point from MapProjection1 to MapProjection2 */ - OutputPointType TransformPoint(const InputPointType &point) const; +/** \class MapToMapProjection + +* \brief Class for switching from a Map Projection coordinates to other Map Projection coordinates. +* It converts MapProjection1 coordinates to MapProjection2 coordinates by using MapProjection methods. +* It takes a point in input. +* (X_1, Y_1) -> (lat, lon) -> (X_2, Y_2) +* \ingroup Transform +*/ +template <class TInputMapProjection, +class TOutputMapProjection, +class TScalarType=double, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2> +class ITK_EXPORT MapToMapProjection: public itk::Transform<TScalarType, // Data type for scalars + NInputDimensions, // Number of dimensions in the input space + NOutputDimensions> // Number of dimensions in the output space +{ +public : + /** Standard class typedefs */ + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef MapToMapProjection Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef TInputMapProjection InputMapProjectionType; + typedef typename InputMapProjectionType::Pointer InputMapProjectionPointerType; + typedef typename InputMapProjectionType::OutputPointType OutputPointOfInputMapProjectionType; + + typedef TOutputMapProjection OutputMapProjectionType; + typedef typename OutputMapProjectionType::Pointer OutputMapProjectionPointerType; + + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( MapToMapProjection, itk::Transform ); + + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int, NInputDimensions*(NInputDimensions+1)); + + /** Set MapProjection1. */ + itkSetObjectMacro(InputMapProjection,InputMapProjectionType); + + /** Set MapProjection2. */ + itkSetObjectMacro(OutputMapProjection,OutputMapProjectionType); + + /** Transform Point from MapProjection1 to MapProjection2 */ + OutputPointType TransformPoint(const InputPointType &point) const; // Compute MapProjection1 coordinates to MapProjection2 coordinates. */ // OutputPointType ComputeProjection1ToProjection2(const InputPointType &point1); @@ -91,18 +91,18 @@ namespace otb // Compute MapProjection1 coordinates to MapProjection2 coordinates. */ // InputPointType ComputeProjection2ToProjection1(const OutputPointType &point2); - protected: - MapToMapProjection(); - ~MapToMapProjection(); +protected: + MapToMapProjection(); + ~MapToMapProjection(); - InputMapProjectionPointerType m_InputMapProjection; - OutputMapProjectionPointerType m_OutputMapProjection; + InputMapProjectionPointerType m_InputMapProjection; + OutputMapProjectionPointerType m_OutputMapProjection; - private: - MapToMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + MapToMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; } // namespace otb diff --git a/Code/Projections/otbMapToMapProjection.txx b/Code/Projections/otbMapToMapProjection.txx index 0b785e3f3e49d566978425b05c5a069d20ef9fc0..2335840c4c78dc159a1024d9ba2490b625d0f72a 100644 --- a/Code/Projections/otbMapToMapProjection.txx +++ b/Code/Projections/otbMapToMapProjection.txx @@ -24,35 +24,35 @@ namespace otb { template<class TInputMapProjection, - class TOutputMapProjection, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> +class TOutputMapProjection, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> MapToMapProjection<TInputMapProjection, - TOutputMapProjection, - TScalarType, - NInputDimensions, - NOutputDimensions> +TOutputMapProjection, +TScalarType, +NInputDimensions, +NOutputDimensions> ::MapToMapProjection() - : Superclass(SpaceDimension,ParametersDimension) + : Superclass(SpaceDimension,ParametersDimension) { } template<class TInputMapProjection, - class TOutputMapProjection, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> +class TOutputMapProjection, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> MapToMapProjection<TInputMapProjection, - TOutputMapProjection, - TScalarType, - NInputDimensions, - NOutputDimensions> +TOutputMapProjection, +TScalarType, +NInputDimensions, +NOutputDimensions> ::~MapToMapProjection() { } - ///Pass from projection 1 to projection 2 +///Pass from projection 1 to projection 2 /* template<class TInputMapProjection, class TOutputMapProjection, class TScalarType, @@ -110,33 +110,33 @@ MapToMapProjection<TInputMapProjection, }*/ template<class TInputMapProjection, - class TOutputMapProjection, - class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions> +class TOutputMapProjection, +class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions> typename MapToMapProjection<TInputMapProjection, - TOutputMapProjection, - TScalarType, - NInputDimensions, - NOutputDimensions> +TOutputMapProjection, +TScalarType, +NInputDimensions, +NOutputDimensions> ::OutputPointType MapToMapProjection<TInputMapProjection, - TOutputMapProjection, - TScalarType, - NInputDimensions, - NOutputDimensions>:: +TOutputMapProjection, +TScalarType, +NInputDimensions, +NOutputDimensions>:: TransformPoint(const InputPointType &point) const { - OutputPointOfInputMapProjectionType geopoint; - OutputPointType point2; + OutputPointOfInputMapProjectionType geopoint; + OutputPointType point2; - //(lat,lon) projection - geopoint=m_InputMapProjection->TransformPoint(point); + //(lat,lon) projection + geopoint=m_InputMapProjection->TransformPoint(point); - //map projection - point2=m_OutputMapProjection->TransformPoint(geopoint); + //map projection + point2=m_OutputMapProjection->TransformPoint(geopoint); - return point2; + return point2; } } // namespace otb diff --git a/Code/Projections/otbMollweidMapProjection.h b/Code/Projections/otbMollweidMapProjection.h index 3513ceeb268555ec8c31a8dcdf9ac7acf0fe98d1..9b47715f68e37dd13fa68141a32d65f591b7a711 100644 --- a/Code/Projections/otbMollweidMapProjection.h +++ b/Code/Projections/otbMollweidMapProjection.h @@ -24,45 +24,45 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class MollweidMapProjection - * \brief This class implements the Mollweid map projection. - * It converts coordinates in longitude,latitude (WGS84) to Mollweid map coordinates. - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT MollweidMapProjection : public MapProjection<ossimMollweidProjection, transform> - { - public : - /** Standard class typedefs. */ - typedef MollweidMapProjection Self; - typedef MapProjection<ossimMollweidProjection,transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro( MollweidMapProjection, MapProjection ); - virtual void SetFalseEasting(double falseEasting); - virtual void SetFalseNorthing(double falseNorthing); - virtual double GetFalseNorthing() const; - virtual double GetFalseEasting() const; - virtual void SetParameters(double falseEasting,double falseNorthing); - virtual void SetDefaults(); - - protected: - MollweidMapProjection(); - virtual ~MollweidMapProjection(); - - private : - MollweidMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class MollweidMapProjection + * \brief This class implements the Mollweid map projection. + * It converts coordinates in longitude,latitude (WGS84) to Mollweid map coordinates. + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT MollweidMapProjection : public MapProjection<ossimMollweidProjection, transform> +{ +public : + /** Standard class typedefs. */ + typedef MollweidMapProjection Self; + typedef MapProjection<ossimMollweidProjection,transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro( MollweidMapProjection, MapProjection ); + virtual void SetFalseEasting(double falseEasting); + virtual void SetFalseNorthing(double falseNorthing); + virtual double GetFalseNorthing() const; + virtual double GetFalseEasting() const; + virtual void SetParameters(double falseEasting,double falseNorthing); + virtual void SetDefaults(); + +protected: + MollweidMapProjection(); + virtual ~MollweidMapProjection(); + +private : + MollweidMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // namespace otb diff --git a/Code/Projections/otbMollweidMapProjection.txx b/Code/Projections/otbMollweidMapProjection.txx index 736cf9b258b2504e82b6acd1b6da925959ba106b..fa66bea8477df9d5f209a8c8c3bd3e381c0750ea 100644 --- a/Code/Projections/otbMollweidMapProjection.txx +++ b/Code/Projections/otbMollweidMapProjection.txx @@ -24,68 +24,68 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - MollweidMapProjection<transform> - ::MollweidMapProjection() - { - } - - template <InverseOrForwardTransformationEnum transform> - MollweidMapProjection<transform> - ::~MollweidMapProjection() - { - } - - ///Set the false easting - template <InverseOrForwardTransformationEnum transform> - void MollweidMapProjection<transform> - ::SetFalseEasting(double falseEasting) - { - this->m_MapProjection->setFalseEasting(falseEasting); - } - - ///Set the false Northing - template <InverseOrForwardTransformationEnum transform> - void MollweidMapProjection<transform> - ::SetFalseNorthing(double falseNorthing) - { - this->m_MapProjection->setFalseNorthing(falseNorthing); - } - - ///Set the default parameters - template <InverseOrForwardTransformationEnum transform> - void MollweidMapProjection<transform> - ::SetDefaults() - { - this->m_MapProjection->setDefaults(); - } - - ///\return the false northing (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double MollweidMapProjection<transform> - ::GetFalseNorthing() const - { - double falseNorthing=this->m_MapProjection->getFalseNorthing(); - - return falseNorthing; - } - - ///\return the false easting (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double MollweidMapProjection<transform> - ::GetFalseEasting() const - { - double falseEasting=this->m_MapProjection->getFalseEasting(); - - return falseEasting; - } - - template <InverseOrForwardTransformationEnum transform> - void MollweidMapProjection<transform> - ::SetParameters(double falseEasting,double falseNorthing) - { - this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); - } +template <InverseOrForwardTransformationEnum transform> +MollweidMapProjection<transform> +::MollweidMapProjection() +{ +} + +template <InverseOrForwardTransformationEnum transform> +MollweidMapProjection<transform> +::~MollweidMapProjection() +{ +} + +///Set the false easting +template <InverseOrForwardTransformationEnum transform> +void MollweidMapProjection<transform> +::SetFalseEasting(double falseEasting) +{ + this->m_MapProjection->setFalseEasting(falseEasting); +} + +///Set the false Northing +template <InverseOrForwardTransformationEnum transform> +void MollweidMapProjection<transform> +::SetFalseNorthing(double falseNorthing) +{ + this->m_MapProjection->setFalseNorthing(falseNorthing); +} + +///Set the default parameters +template <InverseOrForwardTransformationEnum transform> +void MollweidMapProjection<transform> +::SetDefaults() +{ + this->m_MapProjection->setDefaults(); +} + +///\return the false northing (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double MollweidMapProjection<transform> +::GetFalseNorthing() const +{ + double falseNorthing=this->m_MapProjection->getFalseNorthing(); + + return falseNorthing; +} + +///\return the false easting (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double MollweidMapProjection<transform> +::GetFalseEasting() const +{ + double falseEasting=this->m_MapProjection->getFalseEasting(); + + return falseEasting; +} + +template <InverseOrForwardTransformationEnum transform> +void MollweidMapProjection<transform> +::SetParameters(double falseEasting,double falseNorthing) +{ + this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); +} } // end namespace otb diff --git a/Code/Projections/otbOrthoRectificationFilter.h b/Code/Projections/otbOrthoRectificationFilter.h index a5944dd0e51f25776e35ad50228fd10119a4a61e..68740e0167ce739e1cdd29a20188a665dfa97b7a 100644 --- a/Code/Projections/otbOrthoRectificationFilter.h +++ b/Code/Projections/otbOrthoRectificationFilter.h @@ -30,24 +30,24 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class OrthoRectificationFilter - * - * \brief Class for Orthorectifying an image - * - * This class is used to apply map projection and sensor model transformation - * to orthorectify an image, with or without DEM. - * - * \ingroup Projection - * - * \example Projections/OrthoRectificationExample.cxx - * - */ +/** \class OrthoRectificationFilter + * + * \brief Class for Orthorectifying an image + * + * This class is used to apply map projection and sensor model transformation + * to orthorectify an image, with or without DEM. + * + * \ingroup Projection + * + * \example Projections/OrthoRectificationExample.cxx + * + */ template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision=double> class ITK_EXPORT OrthoRectificationFilter : -public StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecision> + public StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecision> { - public : +public : /** Standard class typedefs */ typedef StreamingResampleImageFilter<TInputImage, TOutputImage, @@ -83,12 +83,12 @@ public StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrec virtual void SetMapProjection (MapProjectionType* _arg) { if (this->m_MapProjection != _arg) - { - this->m_MapProjection = _arg; - m_CompositeTransform->SetFirstTransform(_arg); - m_IsComputed = false; - this->Modified(); - } + { + this->m_MapProjection = _arg; + m_CompositeTransform->SetFirstTransform(_arg); + m_IsComputed = false; + this->Modified(); + } } itkGetObjectMacro(MapProjection, MapProjectionType); @@ -125,15 +125,15 @@ public StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrec - protected: +protected: OrthoRectificationFilter(); ~OrthoRectificationFilter(); void PrintSelf(std::ostream& os, itk::Indent indent) const; - + virtual void GenerateInputRequestedRegion(); virtual void GenerateOutputInformation( void ); - private: +private: OrthoRectificationFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/Projections/otbOrthoRectificationFilter.txx b/Code/Projections/otbOrthoRectificationFilter.txx index 3b626085afd4ad0bd03f7aef8d9626d3fb417613..016084dadb81c410383f4e5cfda3b002278cd44d 100644 --- a/Code/Projections/otbOrthoRectificationFilter.txx +++ b/Code/Projections/otbOrthoRectificationFilter.txx @@ -24,88 +24,88 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::OrthoRectificationFilter() : StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecision>() - { +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::OrthoRectificationFilter() : StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecision>() +{ - m_SensorModel = SensorModelType::New(); - m_MapProjection = MapProjectionType::New(); - m_CompositeTransform = CompositeTransformType::New(); - m_IsComputed = false; - } + m_SensorModel = SensorModelType::New(); + m_MapProjection = MapProjectionType::New(); + m_CompositeTransform = CompositeTransformType::New(); + m_IsComputed = false; +} - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::~OrthoRectificationFilter() - { - } +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::~OrthoRectificationFilter() +{ +} - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - void OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os, indent); +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +void OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); - os << indent << "OrthoRectification" << "\n"; - } + os << indent << "OrthoRectification" << "\n"; +} - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - void - OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::GenerateInputRequestedRegion() - { - this->ComputeResampleTransformationModel(); +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +void +OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::GenerateInputRequestedRegion() +{ + this->ComputeResampleTransformationModel(); - Superclass::GenerateInputRequestedRegion(); - } + Superclass::GenerateInputRequestedRegion(); +} - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - void - OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::GenerateOutputInformation() - { - // call the superclass' implementation of this method - Superclass::GenerateOutputInformation(); +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +void +OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::GenerateOutputInformation() +{ + // call the superclass' implementation of this method + Superclass::GenerateOutputInformation(); - // fill up the metadata information for ProjectionRef - typename TOutputImage::Pointer output = this->GetOutput(); - itk::MetaDataDictionary & dict = output->GetMetaDataDictionary(); + // fill up the metadata information for ProjectionRef + typename TOutputImage::Pointer output = this->GetOutput(); + itk::MetaDataDictionary & dict = output->GetMetaDataDictionary(); - std::string projectionRef = m_MapProjection->GetWkt(); + std::string projectionRef = m_MapProjection->GetWkt(); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef ); - } +} - template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> - void - OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> - ::ComputeResampleTransformationModel() +template <class TInputImage, class TOutputImage, class TMapProjection, class TInterpolatorPrecision> +void +OrthoRectificationFilter<TInputImage, TOutputImage, TMapProjection, TInterpolatorPrecision> +::ComputeResampleTransformationModel() +{ + if (m_IsComputed == false) { - if (m_IsComputed == false) - { - otbMsgDevMacro(<< "COMPUTE RESAMPLE TRANSFORMATION MODEL"); - - typename TInputImage::ConstPointer input = this->GetInput(); - - // Get OSSIM sensor model from image keywordlist - m_SensorModel->SetImageGeometry(input->GetImageKeywordlist()); - - // Initialize Map Projection if needed -/* PointType geoPoint; - geoPoint[1] = this->GetOutputOrigin()[1] + this->GetSize()[0]*this->GetOutputSpacing()[0]/2; - geoPoint[0] = this->GetOutputOrigin()[0] + this->GetSize()[1]*this->GetOutputSpacing()[1]/2; - m_MapProjection->Initialize(geoPoint); */ - - m_CompositeTransform->SetFirstTransform(m_MapProjection); - m_CompositeTransform->SetSecondTransform(m_SensorModel); - this->SetTransform(m_CompositeTransform); - m_IsComputed = true; - } + otbMsgDevMacro(<< "COMPUTE RESAMPLE TRANSFORMATION MODEL"); + + typename TInputImage::ConstPointer input = this->GetInput(); + + // Get OSSIM sensor model from image keywordlist + m_SensorModel->SetImageGeometry(input->GetImageKeywordlist()); + + // Initialize Map Projection if needed + /* PointType geoPoint; + geoPoint[1] = this->GetOutputOrigin()[1] + this->GetSize()[0]*this->GetOutputSpacing()[0]/2; + geoPoint[0] = this->GetOutputOrigin()[0] + this->GetSize()[1]*this->GetOutputSpacing()[1]/2; + m_MapProjection->Initialize(geoPoint); */ + + m_CompositeTransform->SetFirstTransform(m_MapProjection); + m_CompositeTransform->SetSecondTransform(m_SensorModel); + this->SetTransform(m_CompositeTransform); + m_IsComputed = true; } +} } //namespace otb diff --git a/Code/Projections/otbPlaceNameToLonLat.h b/Code/Projections/otbPlaceNameToLonLat.h index 6251c9dc886792f86658b967dc12a7cd862c4bbf..8d8ff9434d952e8e4b233f60ce670194deef29c4 100644 --- a/Code/Projections/otbPlaceNameToLonLat.h +++ b/Code/Projections/otbPlaceNameToLonLat.h @@ -61,7 +61,7 @@ public: protected: PlaceNameToLonLat(); - ~PlaceNameToLonLat(){}; + ~PlaceNameToLonLat() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; void RetrieveXML(std::ostringstream& urlStream); void ParseXMLYahoo(); diff --git a/Code/Projections/otbPlaceNameToLonLat.txx b/Code/Projections/otbPlaceNameToLonLat.txx index 49bd9fd5032923c1ca72f16cce520cc0ebf780e2..8200e6d5f8cdef527161ff22f089401139618537 100644 --- a/Code/Projections/otbPlaceNameToLonLat.txx +++ b/Code/Projections/otbPlaceNameToLonLat.txx @@ -81,12 +81,12 @@ bool PlaceNameToLonLat::Evaluate() } if ((m_Lat == -1000.0) && (m_Lon == -1000.0)) - { + { std::cout << "Search Error: fallback on the origin" << std::endl; m_Lat = 43.560204; m_Lon = 1.480736; return false; - } + } return true; } @@ -125,7 +125,8 @@ void PlaceNameToLonLat::RetrieveXML(std::ostringstream& urlStream) strcpy(url,urlStream.str().data()); // std::cout << url << std::endl; - if(curl) { + if (curl) + { std::vector<char> chunk; curl_easy_setopt(curl, CURLOPT_URL, url); /* diff --git a/Code/Projections/otbPrepareSRTMDirectory.h b/Code/Projections/otbPrepareSRTMDirectory.h index 60f0a610a1a0292651b441e2bc11aee09c07ea31..a63f67247bbf1ec38a3952c42178e6b37acf354e 100644 --- a/Code/Projections/otbPrepareSRTMDirectory.h +++ b/Code/Projections/otbPrepareSRTMDirectory.h @@ -39,54 +39,54 @@ namespace otb */ - class ITK_EXPORT PrepareSRTMDirectory : public itk::Object - { - public: - /** Standard class typedefs. */ - typedef PrepareSRTMDirectory Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - - typedef itk::Object Superclass; - - itkTypeMacro(PrepareSRTMDirectory, Object); - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - itkGetMacro( ULLon, double ); - itkGetMacro( ULLat, double ); - itkGetMacro( LRLon, double ); - itkGetMacro( LRLat, double ); - itkGetMacro( FullDEMDirectoryPath, string ); - itkGetMacro( DEMDirectoryPath, string ); - - itkSetMacro( ULLon, double ); - itkSetMacro( ULLat, double ); - itkSetMacro( LRLon, double ); - itkSetMacro( LRLat, double ); - itkSetMacro( FullDEMDirectoryPath, string ); - itkSetMacro( DEMDirectoryPath, string ); - - - virtual bool Evaluate(); - - protected: - PrepareSRTMDirectory(); - ~PrepareSRTMDirectory(){}; - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - private: - PrepareSRTMDirectory( const Self& ); //purposely not implemented - void operator=( const Self& ); //purposely not implemented - - double m_ULLon; - double m_ULLat; - double m_LRLon; - double m_LRLat; - string m_FullDEMDirectoryPath; - string m_DEMDirectoryPath; - }; +class ITK_EXPORT PrepareSRTMDirectory : public itk::Object +{ +public: + /** Standard class typedefs. */ + typedef PrepareSRTMDirectory Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + + typedef itk::Object Superclass; + + itkTypeMacro(PrepareSRTMDirectory, Object); + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + itkGetMacro( ULLon, double ); + itkGetMacro( ULLat, double ); + itkGetMacro( LRLon, double ); + itkGetMacro( LRLat, double ); + itkGetMacro( FullDEMDirectoryPath, string ); + itkGetMacro( DEMDirectoryPath, string ); + + itkSetMacro( ULLon, double ); + itkSetMacro( ULLat, double ); + itkSetMacro( LRLon, double ); + itkSetMacro( LRLat, double ); + itkSetMacro( FullDEMDirectoryPath, string ); + itkSetMacro( DEMDirectoryPath, string ); + + + virtual bool Evaluate(); + +protected: + PrepareSRTMDirectory(); + ~PrepareSRTMDirectory() {}; + void PrintSelf(std::ostream& os, itk::Indent indent) const; + +private: + PrepareSRTMDirectory( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + double m_ULLon; + double m_ULLat; + double m_LRLon; + double m_LRLat; + string m_FullDEMDirectoryPath; + string m_DEMDirectoryPath; +}; } // namespace otb diff --git a/Code/Projections/otbPrepareSRTMDirectory.txx b/Code/Projections/otbPrepareSRTMDirectory.txx index 1a49d0114381e617f95db30588643b9a00a2255b..19bb4d4dcfeead349bb3ba72cc4b1b8cb57cc6d8 100644 --- a/Code/Projections/otbPrepareSRTMDirectory.txx +++ b/Code/Projections/otbPrepareSRTMDirectory.txx @@ -28,105 +28,105 @@ namespace otb * Constructor */ - PrepareSRTMDirectory::PrepareSRTMDirectory() - { - m_ULLon = 0.0; - m_ULLat = 0.0; - m_LRLon = 0.0; - m_LRLat = 0.0; - m_FullDEMDirectoryPath = ""; - m_DEMDirectoryPath = ""; - } +PrepareSRTMDirectory::PrepareSRTMDirectory() +{ + m_ULLon = 0.0; + m_ULLat = 0.0; + m_LRLon = 0.0; + m_LRLat = 0.0; + m_FullDEMDirectoryPath = ""; + m_DEMDirectoryPath = ""; +} /** * */ - void - PrepareSRTMDirectory - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - this->Superclass::PrintSelf(os,indent); - os << indent << " m_ULLon " << m_ULLon << std::endl; - os << indent << " m_ULLat " << m_ULLat << std::endl; - os << indent << " m_LRLon " << m_LRLon << std::endl; - os << indent << " m_LRLat " << m_LRLat << std::endl; - os << indent << " m_FullDEMDirectoryPath" << m_FullDEMDirectoryPath << std::endl; - os << indent << " m_DEMDirectoryPath" << m_DEMDirectoryPath << std::endl; - } +void +PrepareSRTMDirectory +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + this->Superclass::PrintSelf(os,indent); + os << indent << " m_ULLon " << m_ULLon << std::endl; + os << indent << " m_ULLat " << m_ULLat << std::endl; + os << indent << " m_LRLon " << m_LRLon << std::endl; + os << indent << " m_LRLat " << m_LRLat << std::endl; + os << indent << " m_FullDEMDirectoryPath" << m_FullDEMDirectoryPath << std::endl; + os << indent << " m_DEMDirectoryPath" << m_DEMDirectoryPath << std::endl; +} - bool PrepareSRTMDirectory::Evaluate() - { +bool PrepareSRTMDirectory::Evaluate() +{ - int startX = static_cast<int>(floor(m_ULLon)); - int endX = static_cast<int>(ceil(m_LRLon)); - int startY = static_cast<int>(floor(m_LRLat)); - int endY = static_cast<int>(ceil(m_ULLat)); + int startX = static_cast<int>(floor(m_ULLon)); + int endX = static_cast<int>(ceil(m_LRLon)); + int startY = static_cast<int>(floor(m_LRLat)); + int endY = static_cast<int>(ceil(m_ULLat)); - std::cout << startX << std::endl; - std::cout << endX << std::endl; - std::cout << startY << std::endl; - std::cout << endY << std::endl; + std::cout << startX << std::endl; + std::cout << endX << std::endl; + std::cout << startY << std::endl; + std::cout << endY << std::endl; - for (int j=startY; j<endY; j++) + for (int j=startY; j<endY; j++) + { + for (int i=startX; i< endX; i++) { - for (int i=startX; i< endX; i++) - { - std::ostringstream inputfilename; - inputfilename << m_FullDEMDirectoryPath; - inputfilename << "/"; - - std::ostringstream outputfilename; - outputfilename << m_DEMDirectoryPath; - outputfilename << "/"; - - if (j >= 0) - { - inputfilename << "N"; - inputfilename << setfill('0') << setw(2) << j; - outputfilename << "N"; - outputfilename << setfill('0') << setw(2) << j; - } - else - { - inputfilename << "S"; - inputfilename << setfill('0') << setw(2) << -j; - outputfilename << "S"; - outputfilename << setfill('0') << setw(2) << -j; - } - if (i >= 0) - { - inputfilename << "E"; - inputfilename << setfill('0') << setw(3) << i; - outputfilename << "E"; - outputfilename << setfill('0') << setw(3) << i; - } - else - { - inputfilename << "W"; - inputfilename << setfill('0') << setw(3) << -i; - outputfilename << "W"; - outputfilename << setfill('0') << setw(3) << -i; - } - - inputfilename << ".hgt"; - outputfilename << ".hgt"; - - std::cout << "Copying " << inputfilename.str() << " to " << outputfilename.str() << std::endl; - - //copy input file to output file - ossimFilename inputFile(inputfilename.str().c_str()); - ossimFilename outputFile(outputfilename.str().c_str()); - inputFile.copyFileTo(outputFile); + std::ostringstream inputfilename; + inputfilename << m_FullDEMDirectoryPath; + inputfilename << "/"; + std::ostringstream outputfilename; + outputfilename << m_DEMDirectoryPath; + outputfilename << "/"; + if (j >= 0) + { + inputfilename << "N"; + inputfilename << setfill('0') << setw(2) << j; + outputfilename << "N"; + outputfilename << setfill('0') << setw(2) << j; + } + else + { + inputfilename << "S"; + inputfilename << setfill('0') << setw(2) << -j; + outputfilename << "S"; + outputfilename << setfill('0') << setw(2) << -j; + } + if (i >= 0) + { + inputfilename << "E"; + inputfilename << setfill('0') << setw(3) << i; + outputfilename << "E"; + outputfilename << setfill('0') << setw(3) << i; + } + else + { + inputfilename << "W"; + inputfilename << setfill('0') << setw(3) << -i; + outputfilename << "W"; + outputfilename << setfill('0') << setw(3) << -i; } - } - return true; + inputfilename << ".hgt"; + outputfilename << ".hgt"; + + std::cout << "Copying " << inputfilename.str() << " to " << outputfilename.str() << std::endl; + + //copy input file to output file + ossimFilename inputFile(inputfilename.str().c_str()); + ossimFilename outputFile(outputfilename.str().c_str()); + inputFile.copyFileTo(outputFile); + + + } } + return true; +} + } // namespace otb #endif diff --git a/Code/Projections/otbSVY21MapProjection.h b/Code/Projections/otbSVY21MapProjection.h index 77f7775a7b0900d4d5842a244d258e1b2c3bd080..f9a9c9e6499bd5ba9248d1fe152f2f396362e66f 100644 --- a/Code/Projections/otbSVY21MapProjection.h +++ b/Code/Projections/otbSVY21MapProjection.h @@ -25,40 +25,40 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SVY21MapProjection - * \brief This class implements the SVY21 map projection (Singapore geodesic system). - * It converts coordinates in longitude,latitude (WGS84) to SVY21 map coordinates. - * - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT SVY21MapProjection : public TransMercatorMapProjection<transform> - { - public : - /** Standard class typedefs. */ - typedef SVY21MapProjection Self; - typedef TransMercatorMapProjection<transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2 > InputPointType; - typedef itk::Point<ScalarType,2 > OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( SVY21MapProjection, TransMercatorMapProjection ); - - - protected: - SVY21MapProjection(); - virtual ~SVY21MapProjection(); - - private : - SVY21MapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +/** \class SVY21MapProjection +* \brief This class implements the SVY21 map projection (Singapore geodesic system). +* It converts coordinates in longitude,latitude (WGS84) to SVY21 map coordinates. +* + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT SVY21MapProjection : public TransMercatorMapProjection<transform> +{ +public : + /** Standard class typedefs. */ + typedef SVY21MapProjection Self; + typedef TransMercatorMapProjection<transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2 > InputPointType; + typedef itk::Point<ScalarType,2 > OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( SVY21MapProjection, TransMercatorMapProjection ); + + +protected: + SVY21MapProjection(); + virtual ~SVY21MapProjection(); + +private : + SVY21MapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbSVY21MapProjection.txx b/Code/Projections/otbSVY21MapProjection.txx index 8be81dfd06abc07067b50afe97a2078161a7d647..a0120be68c9eec0413c300bc444e97988ca88274 100644 --- a/Code/Projections/otbSVY21MapProjection.txx +++ b/Code/Projections/otbSVY21MapProjection.txx @@ -24,34 +24,34 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - SVY21MapProjection<transform> - ::SVY21MapProjection() - { - itk::Point<double,2> origin; - origin[0]=103.83333333333333; - origin[1]=1.3666666666666667; - std::string datum = "WE"; //WGS84 datum - - - double falseEasting=28001.642; - double falseNorthing=38744.572; - double scaleFactor=1.00000; - std::string ellipsoid = "WE"; //GRS-80 ellipsoid - - - //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only - // SetOrigin required (remove SetEllipsoid) - this->SetOrigin(origin, datum); - this->SetEllipsoid(ellipsoid); - this->SetParameters(falseEasting, falseNorthing, scaleFactor); - } - - template <InverseOrForwardTransformationEnum transform> - SVY21MapProjection<transform> - ::~SVY21MapProjection() - { - } +template <InverseOrForwardTransformationEnum transform> +SVY21MapProjection<transform> +::SVY21MapProjection() +{ + itk::Point<double,2> origin; + origin[0]=103.83333333333333; + origin[1]=1.3666666666666667; + std::string datum = "WE"; //WGS84 datum + + + double falseEasting=28001.642; + double falseNorthing=38744.572; + double scaleFactor=1.00000; + std::string ellipsoid = "WE"; //GRS-80 ellipsoid + + + //TODO: 29-02-2008 Emmanuel: when ossim version > 1.7.2 only + // SetOrigin required (remove SetEllipsoid) + this->SetOrigin(origin, datum); + this->SetEllipsoid(ellipsoid); + this->SetParameters(falseEasting, falseNorthing, scaleFactor); +} + +template <InverseOrForwardTransformationEnum transform> +SVY21MapProjection<transform> +::~SVY21MapProjection() +{ +} } // namespace otb diff --git a/Code/Projections/otbSensorModelBase.h b/Code/Projections/otbSensorModelBase.h index d7c8e446bc304f50d20834a106c7b7afebfc96ef..88e089587b3ca7422b108421fcc1457dacdc930f 100644 --- a/Code/Projections/otbSensorModelBase.h +++ b/Code/Projections/otbSensorModelBase.h @@ -32,135 +32,135 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SensorModelBase - * \brief Base class for the sensor model projection classes. - * This class allows to transform a geographic point in (lat,long) to a point in the sensor geometry. - * (lat,lon) -> (i,j) ou (lat,lon,h) -> (i,j) - * - * \ingroup Projection - * - */ - template <class TScalarType, - unsigned int NInputDimensions=3, - unsigned int NOutputDimensions=2, - unsigned int NParametersDimensions=3> - class ITK_EXPORT SensorModelBase : public itk::Transform<TScalarType, +/** \class SensorModelBase + * \brief Base class for the sensor model projection classes. + * This class allows to transform a geographic point in (lat,long) to a point in the sensor geometry. + * (lat,lon) -> (i,j) ou (lat,lon,h) -> (i,j) + * + * \ingroup Projection + * + */ +template <class TScalarType, +unsigned int NInputDimensions=3, +unsigned int NOutputDimensions=2, +unsigned int NParametersDimensions=3> +class ITK_EXPORT SensorModelBase : public itk::Transform<TScalarType, NInputDimensions, NOutputDimensions> - { +{ - public : +public : - /** Standard class typedefs. */ - typedef SensorModelBase Self; - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; + /** Standard class typedefs. */ + typedef SensorModelBase Self; + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::Point<TScalarType, NInputDimensions > InputPointType; - typedef itk::Point<TScalarType, NOutputDimensions > OutputPointType; + typedef itk::Point<TScalarType, NInputDimensions > InputPointType; + typedef itk::Point<TScalarType, NOutputDimensions > OutputPointType; - typedef DEMHandler DEMHandlerType; - typedef typename DEMHandlerType::Pointer DEMHandlerPointerType; + typedef DEMHandler DEMHandlerType; + typedef typename DEMHandlerType::Pointer DEMHandlerPointerType; - /** Method for creation through the object factory. */ - itkNewMacro( Self ); + /** Method for creation through the object factory. */ + itkNewMacro( Self ); - /** Run-time type information (and related methods). */ - itkTypeMacro( SensorModelBase, Transform ); + /** Run-time type information (and related methods). */ + itkTypeMacro( SensorModelBase, Transform ); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int, NParametersDimensions); //A voir!! - /* Get the ImageKeywordlist */ - ImageKeywordlist GetImageGeometryKeywordlist(void) const; - /* Get an ossimKeywordlist */ - ossimKeywordlist GetOssimKeywordlist(void); - /* Get an ossimModel */ - ossimProjection* GetOssimModel(void); + /* Get the ImageKeywordlist */ + ImageKeywordlist GetImageGeometryKeywordlist(void) const; + /* Get an ossimKeywordlist */ + ossimKeywordlist GetOssimKeywordlist(void); + /* Get an ossimModel */ + ossimProjection* GetOssimModel(void); - /* Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ - virtual void SetImageGeometry(const ImageKeywordlist image_kwl); + /* Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ + virtual void SetImageGeometry(const ImageKeywordlist image_kwl); - /* Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ - virtual void SetImageGeometry(const ossimKeywordlist &geom_kwl); + /* Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ + virtual void SetImageGeometry(const ossimKeywordlist &geom_kwl); // itkGetObjectMacro(DEMHandler, DEMHandlerType); -/* virtual void SetDEMHandler(DEMHandlerType* _arg) - { - if (this->m_DEMHandler != _arg) - { - this->m_DEMHandler = _arg; - this->Modified(); - this->UseDEM(true); - } - }*/ - - /** Set/Get the average elevation if the DEM is not used*/ - itkSetMacro(AverageElevation, TScalarType); - itkGetMacro(AverageElevation, TScalarType); - - virtual void SetDEMDirectory(const std::string& directory) - { - m_DEMHandler->OpenDEMDirectory(directory.c_str()); - m_DEMIsLoaded=true; - this->EnableDEM(); - } - - virtual void DisableDEM() - { - m_UseDEM = false; + /* virtual void SetDEMHandler(DEMHandlerType* _arg) + { + if (this->m_DEMHandler != _arg) + { + this->m_DEMHandler = _arg; this->Modified(); - } + this->UseDEM(true); + } + }*/ - virtual void EnableDEM() - { - if (m_DEMIsLoaded) - m_UseDEM = true; - this->Modified(); - } + /** Set/Get the average elevation if the DEM is not used*/ + itkSetMacro(AverageElevation, TScalarType); + itkGetMacro(AverageElevation, TScalarType); + + virtual void SetDEMDirectory(const std::string& directory) + { + m_DEMHandler->OpenDEMDirectory(directory.c_str()); + m_DEMIsLoaded=true; + this->EnableDEM(); + } + + virtual void DisableDEM() + { + m_UseDEM = false; + this->Modified(); + } + + virtual void EnableDEM() + { + if (m_DEMIsLoaded) + m_UseDEM = true; + this->Modified(); + } - protected: - SensorModelBase(); - virtual ~SensorModelBase(); +protected: + SensorModelBase(); + virtual ~SensorModelBase(); - /** Create the projection ( m_Model). Called by the SetImageGeometry methods */ - void CreateProjection(const ImageKeywordlist & image_kwl); + /** Create the projection ( m_Model). Called by the SetImageGeometry methods */ + void CreateProjection(const ImageKeywordlist & image_kwl); - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** ImageKeywordlist */ - ImageKeywordlist m_ImageKeywordlist; - /** Pointer on an ossim projection (created with the keywordlist) */ - ossimProjection * m_Model; + /** ImageKeywordlist */ + ImageKeywordlist m_ImageKeywordlist; + /** Pointer on an ossim projection (created with the keywordlist) */ + ossimProjection * m_Model; - /** Specify if DEM is used in Point Transformation */ - bool m_UseDEM; + /** Specify if DEM is used in Point Transformation */ + bool m_UseDEM; - /** Object that read and use DEM */ - DEMHandlerPointerType m_DEMHandler; + /** Object that read and use DEM */ + DEMHandlerPointerType m_DEMHandler; - /** Specify an average elevation to use */ - TScalarType m_AverageElevation; + /** Specify an average elevation to use */ + TScalarType m_AverageElevation; - /** Specify if DEM is loaded */ - bool m_DEMIsLoaded; + /** Specify if DEM is loaded */ + bool m_DEMIsLoaded; - private : - SensorModelBase(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private : + SensorModelBase(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - }; +}; } // namespace otb diff --git a/Code/Projections/otbSensorModelBase.txx b/Code/Projections/otbSensorModelBase.txx index 6e09c72cbdb908d09d8bf2d1af5c45ed8386ba74..02f4662e268d5e9dbe37e1d778507ac7bf6da022 100644 --- a/Code/Projections/otbSensorModelBase.txx +++ b/Code/Projections/otbSensorModelBase.txx @@ -32,141 +32,141 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::SensorModelBase(): Superclass(OutputSpaceDimension, ParametersDimension) - { - m_Model = NULL; - m_DEMHandler = DEMHandlerType::New(); - m_UseDEM = false; - m_DEMIsLoaded = false; - m_AverageElevation = -10000; - - } - - - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::~SensorModelBase() - { - if( m_Model != NULL) - { - delete m_Model; - m_Model = NULL; - } - } - - - /// Get the Geometry Keyword list - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - ImageKeywordlist - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::GetImageGeometryKeywordlist(void)const - { - return m_ImageKeywordlist; - } - - /// Get the Geometry Keyword list - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - ossimKeywordlist - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::GetOssimKeywordlist(void) - { - ossimKeywordlist geom; - m_ImageKeywordlist.convertToOSSIMKeywordlist(geom); - - return geom; - } - - /// Get the ossim model - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - ossimProjection* - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::GetOssimModel(void) - { +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::SensorModelBase(): Superclass(OutputSpaceDimension, ParametersDimension) +{ + m_Model = NULL; + m_DEMHandler = DEMHandlerType::New(); + m_UseDEM = false; + m_DEMIsLoaded = false; + m_AverageElevation = -10000; - return m_Model; - } +} - /** Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::SetImageGeometry(const ImageKeywordlist image_kwl) - { - m_ImageKeywordlist = image_kwl; - CreateProjection(m_ImageKeywordlist); - } - /** Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::SetImageGeometry(const ossimKeywordlist & geom_kwl) +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::~SensorModelBase() +{ + if ( m_Model != NULL) { - m_ImageKeywordlist.Clear(); - m_ImageKeywordlist.SetKeywordlist(geom_kwl); - CreateProjection(m_ImageKeywordlist); + delete m_Model; + m_Model = NULL; } +} - /** Instatiate the sensor model from metadata. */ - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::CreateProjection(const ImageKeywordlist & image_kwl) - { - ossimKeywordlist geom; +/// Get the Geometry Keyword list +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +ImageKeywordlist +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::GetImageGeometryKeywordlist(void)const +{ + return m_ImageKeywordlist; +} + +/// Get the Geometry Keyword list +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +ossimKeywordlist +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::GetOssimKeywordlist(void) +{ + ossimKeywordlist geom; + m_ImageKeywordlist.convertToOSSIMKeywordlist(geom); + + return geom; +} + +/// Get the ossim model +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +ossimProjection* +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::GetOssimModel(void) +{ - image_kwl.convertToOSSIMKeywordlist(geom); - otbMsgDevMacro(<< "CreateProjection(): ossimKeywordlist: " << geom); + return m_Model; +} + +/** Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::SetImageGeometry(const ImageKeywordlist image_kwl) +{ + m_ImageKeywordlist = image_kwl; + CreateProjection(m_ImageKeywordlist); +} + +/** Set the Imagekeywordlist and affect the ossim projection ( m_Model) */ +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::SetImageGeometry(const ossimKeywordlist & geom_kwl) +{ + m_ImageKeywordlist.Clear(); + m_ImageKeywordlist.SetKeywordlist(geom_kwl); + CreateProjection(m_ImageKeywordlist); +} + + +/** Instatiate the sensor model from metadata. */ +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::CreateProjection(const ImageKeywordlist & image_kwl) +{ + ossimKeywordlist geom; - m_Model = ossimProjectionFactoryRegistry::instance()->createProjection(geom); - if( m_Model == NULL) - { - itkExceptionMacro(<< "Invalid Model pointer m_Model == NULL !\n The ossim keywordlist is bad!"); - } - } + image_kwl.convertToOSSIMKeywordlist(geom); + otbMsgDevMacro(<< "CreateProjection(): ossimKeywordlist: " << geom); - /** - * PrintSelf method - */ - template < class TScalarType, - unsigned int NInputDimensions, - unsigned int NOutputDimensions, - unsigned int NParametersDimensions > - void - SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + m_Model = ossimProjectionFactoryRegistry::instance()->createProjection(geom); + if ( m_Model == NULL) { - Superclass::PrintSelf(os,indent); - os << indent << "Model: " << m_Model << std::endl; - os << indent << "Keywordlist: " << m_ImageKeywordlist << std::endl; + itkExceptionMacro(<< "Invalid Model pointer m_Model == NULL !\n The ossim keywordlist is bad!"); } +} + +/** + * PrintSelf method + */ +template < class TScalarType, +unsigned int NInputDimensions, +unsigned int NOutputDimensions, +unsigned int NParametersDimensions > +void +SensorModelBase< TScalarType,NInputDimensions,NOutputDimensions,NParametersDimensions> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Model: " << m_Model << std::endl; + os << indent << "Keywordlist: " << m_ImageKeywordlist << std::endl; +} } // namespace otb diff --git a/Code/Projections/otbSinusoidalMapProjection.h b/Code/Projections/otbSinusoidalMapProjection.h index 3ba05db2c2ee1d723d67cc4a510d3bcc13eacab8..18274847eacad43e4bdd6a79073792ff3c201282 100644 --- a/Code/Projections/otbSinusoidalMapProjection.h +++ b/Code/Projections/otbSinusoidalMapProjection.h @@ -25,47 +25,47 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class SinusoidalMapProjection - * \brief This class implements the Sinusoidal map projection. - * It converts coordinates in longitude,latitude (WGS84) to Sinusoidal map coordinates. - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT SinusoidalMapProjection : public MapProjection<ossimSinusoidalProjection, transform> - { - public : - - /** Standard class typedefs. */ - typedef SinusoidalMapProjection Self; - typedef MapProjection<ossimSinusoidalProjection, transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2> InputPointType; - typedef itk::Point<ScalarType,2> OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( SinusoidalMapProjection, MapProjection ); - - virtual void SetFalseEasting(double falseEasting); - virtual void SetFalseNorthing(double falseNorthing); - virtual double GetFalseNorthing() const; - virtual double GetFalseEasting() const; - virtual void SetParameters(double falseEasting,double falseNorthing); - virtual void SetDefaults(); - - protected: - SinusoidalMapProjection(); - virtual ~SinusoidalMapProjection(); - - private : - SinusoidalMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class SinusoidalMapProjection + * \brief This class implements the Sinusoidal map projection. + * It converts coordinates in longitude,latitude (WGS84) to Sinusoidal map coordinates. + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT SinusoidalMapProjection : public MapProjection<ossimSinusoidalProjection, transform> +{ +public : + + /** Standard class typedefs. */ + typedef SinusoidalMapProjection Self; + typedef MapProjection<ossimSinusoidalProjection, transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2> InputPointType; + typedef itk::Point<ScalarType,2> OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( SinusoidalMapProjection, MapProjection ); + + virtual void SetFalseEasting(double falseEasting); + virtual void SetFalseNorthing(double falseNorthing); + virtual double GetFalseNorthing() const; + virtual double GetFalseEasting() const; + virtual void SetParameters(double falseEasting,double falseNorthing); + virtual void SetDefaults(); + +protected: + SinusoidalMapProjection(); + virtual ~SinusoidalMapProjection(); + +private : + SinusoidalMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // namespace otb diff --git a/Code/Projections/otbSinusoidalMapProjection.txx b/Code/Projections/otbSinusoidalMapProjection.txx index 90522c3c08f736ef3c17213cae0ca63154796adf..38596926645b0877132af201f2ea19006b096e8d 100644 --- a/Code/Projections/otbSinusoidalMapProjection.txx +++ b/Code/Projections/otbSinusoidalMapProjection.txx @@ -24,69 +24,69 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - SinusoidalMapProjection<transform> - ::SinusoidalMapProjection() - { - } - - - template <InverseOrForwardTransformationEnum transform> - SinusoidalMapProjection<transform> - ::~SinusoidalMapProjection() - { - } - - ///Set the false Easting - template <InverseOrForwardTransformationEnum transform> - void SinusoidalMapProjection<transform> - ::SetFalseEasting(double falseEasting) - { - this->m_MapProjection->setFalseEasting(falseEasting); - } - - ///Set the False Northing - template <InverseOrForwardTransformationEnum transform> - void SinusoidalMapProjection<transform> - ::SetFalseNorthing(double falseNorthing) - { - this->m_MapProjection->setFalseNorthing(falseNorthing); - } - - ///Set the default parameter - template <InverseOrForwardTransformationEnum transform> - void SinusoidalMapProjection<transform> - ::SetDefaults() - { - this->m_MapProjection->setDefaults(); - } - - ///\return the False Northing (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double SinusoidalMapProjection<transform> - ::GetFalseNorthing() const - { - double falseNorthing=this->m_MapProjection->getFalseNorthing(); - - return falseNorthing; - } - - ///\return the False Easting (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double SinusoidalMapProjection<transform> - ::GetFalseEasting() const - { - double falseEasting=this->m_MapProjection->getFalseEasting(); - - return falseEasting; - } - - template <InverseOrForwardTransformationEnum transform> - void SinusoidalMapProjection<transform> - ::SetParameters(double falseEasting,double falseNorthing) - { - this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); - } +template <InverseOrForwardTransformationEnum transform> +SinusoidalMapProjection<transform> +::SinusoidalMapProjection() +{ +} + + +template <InverseOrForwardTransformationEnum transform> +SinusoidalMapProjection<transform> +::~SinusoidalMapProjection() +{ +} + +///Set the false Easting +template <InverseOrForwardTransformationEnum transform> +void SinusoidalMapProjection<transform> +::SetFalseEasting(double falseEasting) +{ + this->m_MapProjection->setFalseEasting(falseEasting); +} + +///Set the False Northing +template <InverseOrForwardTransformationEnum transform> +void SinusoidalMapProjection<transform> +::SetFalseNorthing(double falseNorthing) +{ + this->m_MapProjection->setFalseNorthing(falseNorthing); +} + +///Set the default parameter +template <InverseOrForwardTransformationEnum transform> +void SinusoidalMapProjection<transform> +::SetDefaults() +{ + this->m_MapProjection->setDefaults(); +} + +///\return the False Northing (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double SinusoidalMapProjection<transform> +::GetFalseNorthing() const +{ + double falseNorthing=this->m_MapProjection->getFalseNorthing(); + + return falseNorthing; +} + +///\return the False Easting (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double SinusoidalMapProjection<transform> +::GetFalseEasting() const +{ + double falseEasting=this->m_MapProjection->getFalseEasting(); + + return falseEasting; +} + +template <InverseOrForwardTransformationEnum transform> +void SinusoidalMapProjection<transform> +::SetParameters(double falseEasting,double falseNorthing) +{ + this->m_MapProjection->setFalseEastingNorthing(falseEasting,falseNorthing); +} } diff --git a/Code/Projections/otbTileMapTransform.h b/Code/Projections/otbTileMapTransform.h index 37b9e535a5c9bf9cb1efaf32904c666a84c53a1a..28199181cb11f73f1c5a0b4201ea25de940aeaaf 100644 --- a/Code/Projections/otbTileMapTransform.h +++ b/Code/Projections/otbTileMapTransform.h @@ -37,56 +37,56 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class TileMapTransform - * \brief to do - **/ +/** \class TileMapTransform + * \brief to do + **/ - template <InverseOrForwardTransformationEnum transform, - class TScalarType = double, - unsigned int NInputDimensions=2, - unsigned int NOutputDimensions=2> - class ITK_EXPORT TileMapTransform: public itk::Transform<TScalarType, // Data type for scalars +template <InverseOrForwardTransformationEnum transform, +class TScalarType = double, +unsigned int NInputDimensions=2, +unsigned int NOutputDimensions=2> +class ITK_EXPORT TileMapTransform: public itk::Transform<TScalarType, // Data type for scalars NInputDimensions, // Number of dimensions in the input space NOutputDimensions> // Number of dimensions in the output space - { - public : - /** Standard class typedefs. */ - typedef itk::Transform< TScalarType, - NInputDimensions, - NOutputDimensions > Superclass; - typedef TileMapTransform Self; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +{ +public : + /** Standard class typedefs. */ + typedef itk::Transform< TScalarType, + NInputDimensions, + NOutputDimensions > Superclass; + typedef TileMapTransform Self; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::ScalarType ScalarType; - typedef ossimTileMapModel OssimTileMapTransformType; - typedef itk::Point<ScalarType,NInputDimensions > InputPointType; - typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; + typedef typename Superclass::ScalarType ScalarType; + typedef ossimTileMapModel OssimTileMapTransformType; + typedef itk::Point<ScalarType,NInputDimensions > InputPointType; + typedef itk::Point<ScalarType,NOutputDimensions > OutputPointType; - /** Method for creation through the object factory. */ - itkNewMacro( Self ); + /** Method for creation through the object factory. */ + itkNewMacro( Self ); - /** Run-time type information (and related methods). */ - itkTypeMacro( TileMapTransform, Transform ); + /** Run-time type information (and related methods). */ + itkTypeMacro( TileMapTransform, Transform ); - typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; + typedef InverseOrForwardTransformationEnum DirectionOfMappingEnumType; - itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,transform); - itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); - itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); - itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); + itkStaticConstMacro(DirectionOfMapping,DirectionOfMappingEnumType,transform); + itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions); + itkStaticConstMacro(SpaceDimension, unsigned int, NInputDimensions); + itkStaticConstMacro(ParametersDimension, unsigned int,NInputDimensions*(NInputDimensions+1)); - void SetLevel(unsigned char level); + void SetLevel(unsigned char level); // virtual void SetEllipsoid (); // void SetEllipsoid (const ossimEllipsoid &ellipsoid); // void SetEllipsoid(std::string code); // void SetEllipsoid(const double &major_axis, const double &minor_axis); - OutputPointType TransformPoint(const InputPointType &point) const; - virtual InputPointType Origin(); + OutputPointType TransformPoint(const InputPointType &point) const; + virtual InputPointType Origin(); // virtual double GetFalseNorthing() const; // virtual double GetFalseEasting() const; // virtual double GetStandardParallel1() const; @@ -108,17 +108,17 @@ namespace otb // //virtual void SetMatrix(double rotation, const OutputPointType &scale, const OutputPointType &translation); // void SetFalseEasting(double falseEasting); - virtual void PrintMap() const; + virtual void PrintMap() const; - protected: - TileMapTransform(); - virtual ~TileMapTransform(); - OssimTileMapTransformType* m_TileMapTransform; +protected: + TileMapTransform(); + virtual ~TileMapTransform(); + OssimTileMapTransformType* m_TileMapTransform; - private : - TileMapTransform(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +private : + TileMapTransform(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbTileMapTransform.txx b/Code/Projections/otbTileMapTransform.txx index 5e8694932d8c477292dea0142fe7f84bec76e5e7..fea203b721b77981d7709bfe7eb77c37614c7a63 100644 --- a/Code/Projections/otbTileMapTransform.txx +++ b/Code/Projections/otbTileMapTransform.txx @@ -24,112 +24,112 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::TileMapTransform() : Superclass(SpaceDimension,ParametersDimension) - { - m_TileMapTransform = new OssimTileMapTransformType(); - } +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::TileMapTransform() : Superclass(SpaceDimension,ParametersDimension) +{ + m_TileMapTransform = new OssimTileMapTransformType(); +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::~TileMapTransform() - { - delete m_TileMapTransform; - } +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::~TileMapTransform() +{ + delete m_TileMapTransform; +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType - TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::TransformPoint(const InputPointType & point) const - { - OutputPointType outputPoint; +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType +TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::TransformPoint(const InputPointType & point) const +{ + OutputPointType outputPoint; - switch(DirectionOfMapping) - { - case INVERSE: - { + switch (DirectionOfMapping) + { + case INVERSE: + { // otbMsgDevMacro(<< "Cartographic coordinates: (" << point[0] << "," << point[1] << ")"); //from "itk::point" to "ossim::ossimDpt" - ossimDpt ossimDPoint(point[0], point[1]); + ossimDpt ossimDPoint(point[0], point[1]); //map projection - ossimGpt ossimGPoint; + ossimGpt ossimGPoint; // ossimGPoint=m_TileMapTransform->inverse(ossimDPoint); - m_TileMapTransform->lineSampleToWorld(ossimDPoint, ossimGPoint); + m_TileMapTransform->lineSampleToWorld(ossimDPoint, ossimGPoint); // otbGenericMsgDebugMacro(<< "Inverse : " << std::endl << m_TileMapTransform->print(std::cout)); - outputPoint[0]=ossimGPoint.lon; - outputPoint[1]=ossimGPoint.lat; + outputPoint[0]=ossimGPoint.lon; + outputPoint[1]=ossimGPoint.lat; // otbMsgDevMacro(<< "Geographic coordinates (long/lat) : (" << outputPoint[0] << "," << outputPoint[1] << ")"); - break; - } - case FORWARD: - { + break; + } + case FORWARD: + { // otbMsgDevMacro(<< "Geographic coordinates (long/lat) : (" << point[1] << "," << point[0] << ")"); //from "itk::point" to "ossim::ossimGpt" - ossimGpt ossimGPoint(point[1], point[0]); + ossimGpt ossimGPoint(point[1], point[0]); //map projection - ossimDpt ossimDPoint; + ossimDpt ossimDPoint; // ossimDPoint=m_TileMapTransform->forward(ossimGPoint); - m_TileMapTransform->worldToLineSample(ossimGPoint, ossimDPoint); + m_TileMapTransform->worldToLineSample(ossimGPoint, ossimDPoint); // otbGenericMsgDebugMacro(<< "Forward : ========================= " << std::endl << m_TileMapTransform->print(std::cout)); - outputPoint[0]=ossimDPoint.x; - outputPoint[1]=ossimDPoint.y; + outputPoint[0]=ossimDPoint.x; + outputPoint[1]=ossimDPoint.y; // otbMsgDevMacro(<< "Cartographic coordinates: (" << outputPoint[0] << "," << outputPoint[1] << ")"); - break; - } - default: - { - itkExceptionMacro(<<"Model is INVERSE or FORWARD only !!"); - break; - } - } - - return outputPoint; + break; + } + default: + { + itkExceptionMacro(<<"Model is INVERSE or FORWARD only !!"); + break; + } } + return outputPoint; +} - ///\return The geographic point corresponding to (0,0) - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - typename TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions>::InputPointType - TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::Origin() - { - ossimGpt ossimOrigin=m_TileMapTransform->origin(); - InputPointType otbOrigin; - otbOrigin[0]= ossimOrigin.lat; - otbOrigin[1]= ossimOrigin.lon; - return otbOrigin; - } +///\return The geographic point corresponding to (0,0) +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +typename TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions>::InputPointType +TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::Origin() +{ + ossimGpt ossimOrigin=m_TileMapTransform->origin(); + InputPointType otbOrigin; + otbOrigin[0]= ossimOrigin.lat; + otbOrigin[1]= ossimOrigin.lon; + return otbOrigin; +} - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void - TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::PrintMap() const - { - std::cout << m_TileMapTransform->print(std::cout); - } - template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> - void TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> - ::SetLevel(unsigned char level) - { - m_TileMapTransform->setDepth(level); - } +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void +TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::PrintMap() const +{ + std::cout << m_TileMapTransform->print(std::cout); +} + +template<InverseOrForwardTransformationEnum Transform, class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> +void TileMapTransform<Transform, TScalarType, NInputDimensions, NOutputDimensions> +::SetLevel(unsigned char level) +{ + m_TileMapTransform->setDepth(level); +} } // namespace otb diff --git a/Code/Projections/otbTransMercatorMapProjection.h b/Code/Projections/otbTransMercatorMapProjection.h index 67c1d97c4054923893e457a0a511823619630235..b828670c556eaa209630ebee1ba29242197ce64f 100644 --- a/Code/Projections/otbTransMercatorMapProjection.h +++ b/Code/Projections/otbTransMercatorMapProjection.h @@ -24,49 +24,49 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class TransMercatorMapProjection - * \brief This class implements the TransMercator map projection. - * It converts coordinates in longitude,latitude (WGS84) to TransMercator map coordinates. - * - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT TransMercatorMapProjection : public MapProjection<ossimTransMercatorProjection,transform> - { - public : - - /** Standard class typedefs. */ - typedef TransMercatorMapProjection Self; - typedef MapProjection<ossimTransMercatorProjection, transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2> InputPointType; - typedef itk::Point<ScalarType,2> OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( TransMercatorMapProjection, MapProjection ); - virtual void SetFalseEasting(double falseEasting); - virtual void SetFalseNorthing(double falseNorthing); - virtual void SetScaleFactor(double scaleFactor); - virtual void SetParameters(double falseEasting,double falseNorthing, double scaleFactor); - virtual void SetDefaults(); - virtual double GetFalseNorthing() const; - virtual double GetFalseEasting() const; - virtual double GetScaleFactor() const; - - protected: - TransMercatorMapProjection(); - virtual ~TransMercatorMapProjection(); - - private : - TransMercatorMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - }; +/** \class TransMercatorMapProjection + * \brief This class implements the TransMercator map projection. + * It converts coordinates in longitude,latitude (WGS84) to TransMercator map coordinates. + * + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT TransMercatorMapProjection : public MapProjection<ossimTransMercatorProjection,transform> +{ +public : + + /** Standard class typedefs. */ + typedef TransMercatorMapProjection Self; + typedef MapProjection<ossimTransMercatorProjection, transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2> InputPointType; + typedef itk::Point<ScalarType,2> OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( TransMercatorMapProjection, MapProjection ); + virtual void SetFalseEasting(double falseEasting); + virtual void SetFalseNorthing(double falseNorthing); + virtual void SetScaleFactor(double scaleFactor); + virtual void SetParameters(double falseEasting,double falseNorthing, double scaleFactor); + virtual void SetDefaults(); + virtual double GetFalseNorthing() const; + virtual double GetFalseEasting() const; + virtual double GetScaleFactor() const; + +protected: + TransMercatorMapProjection(); + virtual ~TransMercatorMapProjection(); + +private : + TransMercatorMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; } // namespace otb diff --git a/Code/Projections/otbTransMercatorMapProjection.txx b/Code/Projections/otbTransMercatorMapProjection.txx index 816bf7a0e733e269b741abe79380fed17d7a2dea..430779d981abe08df29bf3ecac01550ca7c622e0 100644 --- a/Code/Projections/otbTransMercatorMapProjection.txx +++ b/Code/Projections/otbTransMercatorMapProjection.txx @@ -23,94 +23,94 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - TransMercatorMapProjection<transform> - ::TransMercatorMapProjection() - { - ossimEllipsoid ellipsoid= *(ossimEllipsoidFactory::instance()->create("WE")); - ossimGpt origin(49.83,6.16); //TODO check where this is coming from - this->m_MapProjection->setEllipsoid(ellipsoid); - this->m_MapProjection->setOrigin(origin); - } - - /// Desctructor - template <InverseOrForwardTransformationEnum transform> - TransMercatorMapProjection<transform> - ::~TransMercatorMapProjection() - { - } - - - ///Set the false Easting - template <InverseOrForwardTransformationEnum transform> - void TransMercatorMapProjection<transform> - ::SetFalseEasting(double falseEasting) - { - this->m_MapProjection->setFalseEasting(falseEasting); - } - - ///Set the False Northing - template <InverseOrForwardTransformationEnum transform> - void TransMercatorMapProjection<transform> - ::SetFalseNorthing(double falseNorthing) - { - this->m_MapProjection->setFalseNorthing(falseNorthing); - } - - ///Set the scale factor - template <InverseOrForwardTransformationEnum transform> - void TransMercatorMapProjection<transform> - ::SetScaleFactor(double scaleFactor) - { - this->m_MapProjection->setScaleFactor(scaleFactor); - } - - ///Set the parameters - template <InverseOrForwardTransformationEnum transform> - void TransMercatorMapProjection<transform> - ::SetParameters(double falseEasting,double falseNorthing,double scaleFactor) - { - this->m_MapProjection->setParameters(falseEasting, falseNorthing, scaleFactor); - } - - ///Set the default parameters - template <InverseOrForwardTransformationEnum transform> - void TransMercatorMapProjection<transform> - ::SetDefaults() - { - this->m_MapProjection->setDefaults(); - } - - ///\return the scale factor - template <InverseOrForwardTransformationEnum transform> - double TransMercatorMapProjection<transform> - ::GetScaleFactor() const - { - double scaleFactor; - scaleFactor=this->m_MapProjection->getScaleFactor(); - - return scaleFactor; - } - - ///\return the false northing (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double TransMercatorMapProjection<transform> - ::GetFalseNorthing() const - { - double falseNorthing=this->m_MapProjection->getFalseNorthing(); - - return falseNorthing; - } - - ///\return the false easting (avoid negative coordinates) - template <InverseOrForwardTransformationEnum transform> - double TransMercatorMapProjection<transform> - ::GetFalseEasting() const - { - double falseEasting=this->m_MapProjection->getFalseEasting(); - - return falseEasting; - } +template <InverseOrForwardTransformationEnum transform> +TransMercatorMapProjection<transform> +::TransMercatorMapProjection() +{ + ossimEllipsoid ellipsoid= *(ossimEllipsoidFactory::instance()->create("WE")); + ossimGpt origin(49.83,6.16); //TODO check where this is coming from + this->m_MapProjection->setEllipsoid(ellipsoid); + this->m_MapProjection->setOrigin(origin); +} + +/// Desctructor +template <InverseOrForwardTransformationEnum transform> +TransMercatorMapProjection<transform> +::~TransMercatorMapProjection() +{ +} + + +///Set the false Easting +template <InverseOrForwardTransformationEnum transform> +void TransMercatorMapProjection<transform> +::SetFalseEasting(double falseEasting) +{ + this->m_MapProjection->setFalseEasting(falseEasting); +} + +///Set the False Northing +template <InverseOrForwardTransformationEnum transform> +void TransMercatorMapProjection<transform> +::SetFalseNorthing(double falseNorthing) +{ + this->m_MapProjection->setFalseNorthing(falseNorthing); +} + +///Set the scale factor +template <InverseOrForwardTransformationEnum transform> +void TransMercatorMapProjection<transform> +::SetScaleFactor(double scaleFactor) +{ + this->m_MapProjection->setScaleFactor(scaleFactor); +} + +///Set the parameters +template <InverseOrForwardTransformationEnum transform> +void TransMercatorMapProjection<transform> +::SetParameters(double falseEasting,double falseNorthing,double scaleFactor) +{ + this->m_MapProjection->setParameters(falseEasting, falseNorthing, scaleFactor); +} + +///Set the default parameters +template <InverseOrForwardTransformationEnum transform> +void TransMercatorMapProjection<transform> +::SetDefaults() +{ + this->m_MapProjection->setDefaults(); +} + +///\return the scale factor +template <InverseOrForwardTransformationEnum transform> +double TransMercatorMapProjection<transform> +::GetScaleFactor() const +{ + double scaleFactor; + scaleFactor=this->m_MapProjection->getScaleFactor(); + + return scaleFactor; +} + +///\return the false northing (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double TransMercatorMapProjection<transform> +::GetFalseNorthing() const +{ + double falseNorthing=this->m_MapProjection->getFalseNorthing(); + + return falseNorthing; +} + +///\return the false easting (avoid negative coordinates) +template <InverseOrForwardTransformationEnum transform> +double TransMercatorMapProjection<transform> +::GetFalseEasting() const +{ + double falseEasting=this->m_MapProjection->getFalseEasting(); + + return falseEasting; +} } #endif diff --git a/Code/Projections/otbUtmMapProjection.h b/Code/Projections/otbUtmMapProjection.h index 22038d4b554c620f0f37a4953d5c0d0e83b797fa..5e06b2dc7f83cb61079a523de2f2cc729d6f5f97 100644 --- a/Code/Projections/otbUtmMapProjection.h +++ b/Code/Projections/otbUtmMapProjection.h @@ -24,52 +24,52 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class UtmMapProjection - * \brief This class implements the UTM map projection. - * It converts coordinates in longitude,latitude (WGS84) to UTM map coordinates. - */ - template <InverseOrForwardTransformationEnum transform> - class ITK_EXPORT UtmMapProjection : public MapProjection<ossimUtmProjection,transform> - { - public : - - /** Standard class typedefs. */ - typedef UtmMapProjection Self; - typedef MapProjection<ossimUtmProjection,transform> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - typedef typename Superclass::ScalarType ScalarType; - typedef itk::Point<ScalarType,2> InputPointType; - typedef itk::Point<ScalarType,2> OutputPointType; - - /** Method for creation through the object factory. */ - itkNewMacro( Self ); - - /** Run-time type information (and related methods). */ - itkTypeMacro( UtmMapProjection, MapProjection ); - - virtual void SetZone(long zone); - virtual void SetZone(const InputPointType &ground); - virtual void SetHemisphere(char hemisphere); - virtual long GetZone(); - virtual const char GetHemisphere() const; - - virtual void SetZoneAndHemisphereFromGeoPoint(const InputPointType &geoPoint); +/** \class UtmMapProjection + * \brief This class implements the UTM map projection. + * It converts coordinates in longitude,latitude (WGS84) to UTM map coordinates. + */ +template <InverseOrForwardTransformationEnum transform> +class ITK_EXPORT UtmMapProjection : public MapProjection<ossimUtmProjection,transform> +{ +public : + + /** Standard class typedefs. */ + typedef UtmMapProjection Self; + typedef MapProjection<ossimUtmProjection,transform> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::ScalarType ScalarType; + typedef itk::Point<ScalarType,2> InputPointType; + typedef itk::Point<ScalarType,2> OutputPointType; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( UtmMapProjection, MapProjection ); + + virtual void SetZone(long zone); + virtual void SetZone(const InputPointType &ground); + virtual void SetHemisphere(char hemisphere); + virtual long GetZone(); + virtual const char GetHemisphere() const; + + virtual void SetZoneAndHemisphereFromGeoPoint(const InputPointType &geoPoint); // virtual void SetZoneAndHemisphereFromCartoPoint(const OutputPointType &cartoPoint); - virtual int GetZoneFromGeoPoint(const InputPointType& geoPoint); + virtual int GetZoneFromGeoPoint(const InputPointType& geoPoint); // virtual void Initialize(const InputPointType& middlePoint); - protected: - UtmMapProjection(); - virtual ~UtmMapProjection(); +protected: + UtmMapProjection(); + virtual ~UtmMapProjection(); - private: - UtmMapProjection(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - }; +private: + UtmMapProjection(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; } // namespace otb diff --git a/Code/Projections/otbUtmMapProjection.txx b/Code/Projections/otbUtmMapProjection.txx index b76a04f50217a4015325a2058e5d9a41f2adb87b..3f29755122ba384c7abae113188eb1c95fd31073 100644 --- a/Code/Projections/otbUtmMapProjection.txx +++ b/Code/Projections/otbUtmMapProjection.txx @@ -25,116 +25,116 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - template <InverseOrForwardTransformationEnum transform> - UtmMapProjection<transform> - ::UtmMapProjection() - { - } +template <InverseOrForwardTransformationEnum transform> +UtmMapProjection<transform> +::UtmMapProjection() +{ +} - template <InverseOrForwardTransformationEnum transform> - UtmMapProjection<transform> - ::~UtmMapProjection() - { - } +template <InverseOrForwardTransformationEnum transform> +UtmMapProjection<transform> +::~UtmMapProjection() +{ +} - ///Set the zone - template <InverseOrForwardTransformationEnum transform> - void UtmMapProjection<transform> - ::SetZone(long zone) - { - this->m_MapProjection->setZone(zone); - this->Modified(); - } - - ///Set the zone - template <InverseOrForwardTransformationEnum transform> - void UtmMapProjection<transform> - ::SetZone(const InputPointType &ground) - { - ossimGpt ossimGround; - ossimGround.lon=ground[0]; - ossimGround.lat=ground[1]; - this->m_MapProjection->setZone(ossimGround); - this->Modified(); - } - - ///Set the hemisphere - template <InverseOrForwardTransformationEnum transform> - void UtmMapProjection<transform> - ::SetHemisphere(char hemisphere) - { - this->m_MapProjection->setHemisphere(hemisphere); - this->Modified(); - } +///Set the zone +template <InverseOrForwardTransformationEnum transform> +void UtmMapProjection<transform> +::SetZone(long zone) +{ + this->m_MapProjection->setZone(zone); + this->Modified(); +} - template <InverseOrForwardTransformationEnum transform> - void UtmMapProjection<transform> - ::SetZoneAndHemisphereFromGeoPoint(const InputPointType &geoPoint) - { - double latitude = geoPoint[1]; - char hemisphere; - int zone; +///Set the zone +template <InverseOrForwardTransformationEnum transform> +void UtmMapProjection<transform> +::SetZone(const InputPointType &ground) +{ + ossimGpt ossimGround; + ossimGround.lon=ground[0]; + ossimGround.lat=ground[1]; + this->m_MapProjection->setZone(ossimGround); + this->Modified(); +} - if (latitude > 0.) - hemisphere = 'N'; - else - hemisphere = 'S'; - this->SetHemisphere(hemisphere); +///Set the hemisphere +template <InverseOrForwardTransformationEnum transform> +void UtmMapProjection<transform> +::SetHemisphere(char hemisphere) +{ + this->m_MapProjection->setHemisphere(hemisphere); + this->Modified(); +} - zone = this->GetZoneFromGeoPoint(geoPoint); - this->SetZone(zone); - } +template <InverseOrForwardTransformationEnum transform> +void UtmMapProjection<transform> +::SetZoneAndHemisphereFromGeoPoint(const InputPointType &geoPoint) +{ + double latitude = geoPoint[1]; + char hemisphere; + int zone; + + if (latitude > 0.) + hemisphere = 'N'; + else + hemisphere = 'S'; + this->SetHemisphere(hemisphere); + + zone = this->GetZoneFromGeoPoint(geoPoint); + this->SetZone(zone); +} - /*template <InverseOrForwardTransformationEnum transform> - void UtmMapProjection<transform> - ::SetZoneAndHemisphereFromCartoPoint(const OutputPointType &cartoPoint) - { - InputPointType geoPoint; +/*template <InverseOrForwardTransformationEnum transform> +void UtmMapProjection<transform> +::SetZoneAndHemisphereFromCartoPoint(const OutputPointType &cartoPoint) +{ +InputPointType geoPoint; - // TODO : Tester que la projection est bien inverse !!! - geoPoint = this->TransformPoint(cartoPoint); - this->SetZoneAndHemisphereFromGeoPoint(geoPoint); + // TODO : Tester que la projection est bien inverse !!! +geoPoint = this->TransformPoint(cartoPoint); +this->SetZoneAndHemisphereFromGeoPoint(geoPoint); } */ - ///\return the zone - template <InverseOrForwardTransformationEnum transform> - long UtmMapProjection<transform> - ::GetZone() - { - long zone; - zone=this->m_MapProjection->getZone(); +///\return the zone +template <InverseOrForwardTransformationEnum transform> +long UtmMapProjection<transform> +::GetZone() +{ + long zone; + zone=this->m_MapProjection->getZone(); - return zone; - } + return zone; +} - ///\return the hemisphere - template <InverseOrForwardTransformationEnum transform> - const char UtmMapProjection<transform> - ::GetHemisphere() const - { - char hemisphere=0; - hemisphere=this->m_MapProjection->getHemisphere(); +///\return the hemisphere +template <InverseOrForwardTransformationEnum transform> +const char UtmMapProjection<transform> +::GetHemisphere() const +{ + char hemisphere=0; + hemisphere=this->m_MapProjection->getHemisphere(); - return hemisphere; - } + return hemisphere; +} - template <InverseOrForwardTransformationEnum transform> - int UtmMapProjection<transform> - ::GetZoneFromGeoPoint(const InputPointType& geoPoint) - { - double longitude = geoPoint[0]; - //double latitude = geoPoint[1]; - int zone; +template <InverseOrForwardTransformationEnum transform> +int UtmMapProjection<transform> +::GetZoneFromGeoPoint(const InputPointType& geoPoint) +{ + double longitude = geoPoint[0]; + //double latitude = geoPoint[1]; + int zone; - // Each UTM zone is a narrow zone of 6 degrees in width - // Zone 31 is between 0 and 6 degrees (lon) - // There is 60 zones in each hemisphere - zone = ((static_cast<int>(floor(longitude/6))+30)%60+60)%60+1; + // Each UTM zone is a narrow zone of 6 degrees in width + // Zone 31 is between 0 and 6 degrees (lon) + // There is 60 zones in each hemisphere + zone = ((static_cast<int>(floor(longitude/6))+30)%60+60)%60+1; - return zone; - } + return zone; +} /* template <InverseOrForwardTransformationEnum transform> void UtmMapProjection<transform> diff --git a/Code/Projections/otbVectorDataProjectionFilter.h b/Code/Projections/otbVectorDataProjectionFilter.h index 713f7c98fe68cbcc82f75de559b59ecb08c0e081..5a2e234accd50320e301222c8870e42964a747db 100644 --- a/Code/Projections/otbVectorDataProjectionFilter.h +++ b/Code/Projections/otbVectorDataProjectionFilter.h @@ -60,152 +60,152 @@ namespace otb * */ - template <class TInputVectorData, class TOutputVectorData> - class ITK_EXPORT VectorDataProjectionFilter : - public otb::VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> - { +template <class TInputVectorData, class TOutputVectorData> +class ITK_EXPORT VectorDataProjectionFilter : + public otb::VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> +{ - public: - /** Standard class typedefs. */ - typedef VectorDataProjectionFilter Self; - typedef otb::VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +public: + /** Standard class typedefs. */ + typedef VectorDataProjectionFilter Self; + typedef otb::VectorDataToVectorDataFilter<TInputVectorData,TOutputVectorData> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - typedef TInputVectorData InputVectorDataType; - typedef TOutputVectorData OutputVectorDataType; - typedef typename TInputVectorData::ConstPointer InputVectorDataPointer; - typedef typename TOutputVectorData::Pointer OutputVectorDataPointer; + typedef TInputVectorData InputVectorDataType; + typedef TOutputVectorData OutputVectorDataType; + typedef typename TInputVectorData::ConstPointer InputVectorDataPointer; + typedef typename TOutputVectorData::Pointer OutputVectorDataPointer; - /** Some typedefs. */ - typedef itk::Transform<double, 2, 2> GenericTransformType; - typedef typename GenericTransformType::Pointer GenericTransformPointerType; - typedef otb::CompositeTransform<GenericTransformType, GenericTransformType, double, 2, 2> InternalTransformType; - typedef typename InternalTransformType::Pointer InternalTransformPointerType; + /** Some typedefs. */ + typedef itk::Transform<double, 2, 2> GenericTransformType; + typedef typename GenericTransformType::Pointer GenericTransformPointerType; + typedef otb::CompositeTransform<GenericTransformType, GenericTransformType, double, 2, 2> InternalTransformType; + typedef typename InternalTransformType::Pointer InternalTransformPointerType; - typedef itk::Vector<double, 2> SpacingType; - typedef itk::Point<double, 2> OriginType; + typedef itk::Vector<double, 2> SpacingType; + typedef itk::Point<double, 2> OriginType; - typedef itk::PreOrderTreeIterator<typename InputVectorDataType::DataTreeType> InputTreeIteratorType; - typedef typename InputVectorDataType::DataNodePointerType InputDataNodePointerType; - typedef typename OutputVectorDataType::DataNodeType OutputDataNodeType; - typedef typename OutputVectorDataType::DataNodePointerType OutputDataNodePointerType; - typedef typename OutputVectorDataType::DataTreePointerType OutputDataTreePointerType; + typedef itk::PreOrderTreeIterator<typename InputVectorDataType::DataTreeType> InputTreeIteratorType; + typedef typename InputVectorDataType::DataNodePointerType InputDataNodePointerType; + typedef typename OutputVectorDataType::DataNodeType OutputDataNodeType; + typedef typename OutputVectorDataType::DataNodePointerType OutputDataNodePointerType; + typedef typename OutputVectorDataType::DataTreePointerType OutputDataTreePointerType; - typedef typename OutputDataNodeType::PointType PointType; + typedef typename OutputDataNodeType::PointType PointType; - typedef typename OutputDataNodeType::LineType LineType; - typedef typename OutputDataNodeType::LineConstPointerType LineConstPointerType; - typedef typename OutputDataNodeType::LinePointerType LinePointerType; + typedef typename OutputDataNodeType::LineType LineType; + typedef typename OutputDataNodeType::LineConstPointerType LineConstPointerType; + typedef typename OutputDataNodeType::LinePointerType LinePointerType; - typedef typename OutputDataNodeType::PolygonType PolygonType; - typedef typename OutputDataNodeType::PolygonConstPointerType PolygonConstPointerType; - typedef typename OutputDataNodeType::PolygonPointerType PolygonPointerType; + typedef typename OutputDataNodeType::PolygonType PolygonType; + typedef typename OutputDataNodeType::PolygonConstPointerType PolygonConstPointerType; + typedef typename OutputDataNodeType::PolygonPointerType PolygonPointerType; - typedef typename OutputDataNodeType::PolygonListType PolygonListType; - typedef typename OutputDataNodeType::PolygonListConstPointerType PolygonListConstPointerType; - typedef typename OutputDataNodeType::PolygonListPointerType PolygonListPointerType; + typedef typename OutputDataNodeType::PolygonListType PolygonListType; + typedef typename OutputDataNodeType::PolygonListConstPointerType PolygonListConstPointerType; + typedef typename OutputDataNodeType::PolygonListPointerType PolygonListPointerType; - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Method for creation through the object factory. */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(VectorDataProjectionFilter, VectorDataToVectorDataFilter); + /** Run-time type information (and related methods). */ + itkTypeMacro(VectorDataProjectionFilter, VectorDataToVectorDataFilter); - /** Set/Get for input and output projections. */ - itkSetStringMacro(InputProjectionRef); - itkGetStringMacro(InputProjectionRef); + /** Set/Get for input and output projections. */ + itkSetStringMacro(InputProjectionRef); + itkGetStringMacro(InputProjectionRef); - itkSetStringMacro(OutputProjectionRef); - itkGetStringMacro(OutputProjectionRef); + itkSetStringMacro(OutputProjectionRef); + itkGetStringMacro(OutputProjectionRef); - itkSetStringMacro(DEMDirectory); - itkGetStringMacro(DEMDirectory); + itkSetStringMacro(DEMDirectory); + itkGetStringMacro(DEMDirectory); - itkGetMacro(InputKeywordList,ImageKeywordlist); - void SetInputKeywordList(ImageKeywordlist kwl) - { - this->m_InputKeywordList = kwl; - this->Modified(); - } + itkGetMacro(InputKeywordList,ImageKeywordlist); + void SetInputKeywordList(ImageKeywordlist kwl) + { + this->m_InputKeywordList = kwl; + this->Modified(); + } - itkGetMacro(OutputKeywordList,ImageKeywordlist); - void SetOutputKeywordList(ImageKeywordlist kwl) - { - this->m_OutputKeywordList = kwl; - this->Modified(); - } + itkGetMacro(OutputKeywordList,ImageKeywordlist); + void SetOutputKeywordList(ImageKeywordlist kwl) + { + this->m_OutputKeywordList = kwl; + this->Modified(); + } - /** Set the origin of the vector data. - * \sa GetOrigin() */ - itkSetMacro(InputOrigin, OriginType); - virtual void SetInputOrigin( const double origin[2] ); - virtual void SetInputOrigin( const float origin[2] ); + /** Set the origin of the vector data. + * \sa GetOrigin() */ + itkSetMacro(InputOrigin, OriginType); + virtual void SetInputOrigin( const double origin[2] ); + virtual void SetInputOrigin( const float origin[2] ); - itkGetConstReferenceMacro(InputOrigin, OriginType); + itkGetConstReferenceMacro(InputOrigin, OriginType); - /** Set the spacing (size of a pixel) of the vector data. - * \sa GetSpacing() */ - virtual void SetInputSpacing (const SpacingType & spacing); - virtual void SetInputSpacing (const double spacing[2]); - virtual void SetInputSpacing (const float spacing[2]); + /** Set the spacing (size of a pixel) of the vector data. + * \sa GetSpacing() */ + virtual void SetInputSpacing (const SpacingType & spacing); + virtual void SetInputSpacing (const double spacing[2]); + virtual void SetInputSpacing (const float spacing[2]); - itkGetConstReferenceMacro(InputSpacing, SpacingType); + itkGetConstReferenceMacro(InputSpacing, SpacingType); - /** Set the origin of the vector data. - * \sa GetOrigin() */ - itkSetMacro(OutputOrigin, OriginType); - virtual void SetOutputOrigin( const double origin[2] ); - virtual void SetOutputOrigin( const float origin[2] ); + /** Set the origin of the vector data. + * \sa GetOrigin() */ + itkSetMacro(OutputOrigin, OriginType); + virtual void SetOutputOrigin( const double origin[2] ); + virtual void SetOutputOrigin( const float origin[2] ); - itkGetConstReferenceMacro(OutputOrigin, OriginType); + itkGetConstReferenceMacro(OutputOrigin, OriginType); - /** Set the spacing (size of a pixel) of the vector data. - * \sa GetSpacing() */ - virtual void SetOutputSpacing (const SpacingType & spacing); - virtual void SetOutputSpacing (const double spacing[2]); - virtual void SetOutputSpacing (const float spacing[2]); + /** Set the spacing (size of a pixel) of the vector data. + * \sa GetSpacing() */ + virtual void SetOutputSpacing (const SpacingType & spacing); + virtual void SetOutputSpacing (const double spacing[2]); + virtual void SetOutputSpacing (const float spacing[2]); - itkGetConstReferenceMacro(OutputSpacing, SpacingType); + itkGetConstReferenceMacro(OutputSpacing, SpacingType); - protected: - VectorDataProjectionFilter(); - virtual ~VectorDataProjectionFilter() {}; +protected: + VectorDataProjectionFilter(); + virtual ~VectorDataProjectionFilter() {}; - PointType ReprojectPoint(PointType point) const; - LinePointerType ReprojectLine(LinePointerType line) const; - PolygonPointerType ReprojectPolygon(PolygonPointerType polygon) const; - PolygonListPointerType ReprojectPolygonList(PolygonListPointerType polygonList) const; + PointType ReprojectPoint(PointType point) const; + LinePointerType ReprojectLine(LinePointerType line) const; + PolygonPointerType ReprojectPolygon(PolygonPointerType polygon) const; + PolygonListPointerType ReprojectPolygonList(PolygonListPointerType polygonList) const; - void InstanciateTransform(void); + void InstanciateTransform(void); - void GenerateOutputInformation(void); - void GenerateData(void); + void GenerateOutputInformation(void); + void GenerateData(void); - private: - VectorDataProjectionFilter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented +private: + VectorDataProjectionFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - InternalTransformPointerType m_Transform; - GenericTransformPointerType m_InputTransform; - GenericTransformPointerType m_OutputTransform; - std::string m_InputProjectionRef; - std::string m_OutputProjectionRef; - ImageKeywordlist m_InputKeywordList; - ImageKeywordlist m_OutputKeywordList; - std::string m_DEMDirectory; + InternalTransformPointerType m_Transform; + GenericTransformPointerType m_InputTransform; + GenericTransformPointerType m_OutputTransform; + std::string m_InputProjectionRef; + std::string m_OutputProjectionRef; + ImageKeywordlist m_InputKeywordList; + ImageKeywordlist m_OutputKeywordList; + std::string m_DEMDirectory; - SpacingType m_InputSpacing; - OriginType m_InputOrigin; - SpacingType m_OutputSpacing; - OriginType m_OutputOrigin; - }; + SpacingType m_InputSpacing; + OriginType m_InputOrigin; + SpacingType m_OutputSpacing; + OriginType m_OutputOrigin; +}; } // end namespace otb diff --git a/Code/Projections/otbVectorDataProjectionFilter.txx b/Code/Projections/otbVectorDataProjectionFilter.txx index 6754101f7016d4e0a4dd4165740b6d7ed47bd8f1..765d7836d19fd1b00beb5cd8a91e9e5017f88e31 100644 --- a/Code/Projections/otbVectorDataProjectionFilter.txx +++ b/Code/Projections/otbVectorDataProjectionFilter.txx @@ -34,504 +34,504 @@ namespace otb /** * Constructor */ - template <class TInputVectorData, class TOutputVectorData > - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::VectorDataProjectionFilter() - { - m_InputProjectionRef.clear(); - m_OutputProjectionRef.clear(); - m_InputKeywordList.Clear(); - m_OutputKeywordList.Clear(); - m_InputSpacing.Fill(1); - m_InputOrigin.Fill(0); - m_OutputSpacing.Fill(1); - m_OutputOrigin.Fill(0); - } +template <class TInputVectorData, class TOutputVectorData > +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::VectorDataProjectionFilter() +{ + m_InputProjectionRef.clear(); + m_OutputProjectionRef.clear(); + m_InputKeywordList.Clear(); + m_OutputKeywordList.Clear(); + m_InputSpacing.Fill(1); + m_InputOrigin.Fill(0); + m_OutputSpacing.Fill(1); + m_OutputOrigin.Fill(0); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetInputSpacing(const SpacingType & spacing ) +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetInputSpacing(const SpacingType & spacing ) +{ + itkDebugMacro("setting Spacing to " << spacing); + if ( this->m_InputSpacing != spacing ) { - itkDebugMacro("setting Spacing to " << spacing); - if( this->m_InputSpacing != spacing ) - { - this->m_InputSpacing = spacing; - this->Modified(); - } + this->m_InputSpacing = spacing; + this->Modified(); } +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetInputSpacing(const double spacing[2] ) - { - SpacingType s(spacing); - this->SetInputSpacing(s); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetInputSpacing(const double spacing[2] ) +{ + SpacingType s(spacing); + this->SetInputSpacing(s); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetInputSpacing(const float spacing[2] ) - { - itk::Vector<float, 2> sf(spacing); - SpacingType s; - s.CastFrom( sf ); - this->SetInputSpacing(s); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetInputSpacing(const float spacing[2] ) +{ + itk::Vector<float, 2> sf(spacing); + SpacingType s; + s.CastFrom( sf ); + this->SetInputSpacing(s); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetInputOrigin(const double origin[2] ) - { - OriginType p(origin); - this->SetInputOrigin( p ); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetInputOrigin(const double origin[2] ) +{ + OriginType p(origin); + this->SetInputOrigin( p ); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetInputOrigin(const float origin[2] ) - { - itk::Point<float, 2> of(origin); - OriginType p; - p.CastFrom( of ); - this->SetInputOrigin( p ); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetInputOrigin(const float origin[2] ) +{ + itk::Point<float, 2> of(origin); + OriginType p; + p.CastFrom( of ); + this->SetInputOrigin( p ); +} - //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetOutputSpacing(const SpacingType & spacing ) +//---------------------------------------------------------------------------- +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetOutputSpacing(const SpacingType & spacing ) +{ + itkDebugMacro("setting Spacing to " << spacing); + if ( this->m_OutputSpacing != spacing ) { - itkDebugMacro("setting Spacing to " << spacing); - if( this->m_OutputSpacing != spacing ) - { - this->m_OutputSpacing = spacing; - this->Modified(); - } + this->m_OutputSpacing = spacing; + this->Modified(); } +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetOutputSpacing(const double spacing[2] ) - { - SpacingType s(spacing); - this->SetOutputSpacing(s); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetOutputSpacing(const double spacing[2] ) +{ + SpacingType s(spacing); + this->SetOutputSpacing(s); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetOutputSpacing(const float spacing[2] ) - { - itk::Vector<float, 2> sf(spacing); - SpacingType s; - s.CastFrom( sf ); - this->SetOutputSpacing(s); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetOutputSpacing(const float spacing[2] ) +{ + itk::Vector<float, 2> sf(spacing); + SpacingType s; + s.CastFrom( sf ); + this->SetOutputSpacing(s); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetOutputOrigin(const double origin[2] ) - { - OriginType p(origin); - this->SetOutputOrigin( p ); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetOutputOrigin(const double origin[2] ) +{ + OriginType p(origin); + this->SetOutputOrigin( p ); +} //---------------------------------------------------------------------------- - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::SetOutputOrigin(const float origin[2] ) - { - itk::Point<float, 2> of(origin); - OriginType p; - p.CastFrom( of ); - this->SetOutputOrigin( p ); - } +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::SetOutputOrigin(const float origin[2] ) +{ + itk::Point<float, 2> of(origin); + OriginType p; + p.CastFrom( of ); + this->SetOutputOrigin( p ); +} - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::GenerateOutputInformation(void) - { - Superclass::GenerateOutputInformation(); +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::GenerateOutputInformation(void) +{ + Superclass::GenerateOutputInformation(); - OutputVectorDataPointer output = this->GetOutput(); - itk::MetaDataDictionary & dict = output->GetMetaDataDictionary(); + OutputVectorDataPointer output = this->GetOutput(); + itk::MetaDataDictionary & dict = output->GetMetaDataDictionary(); - itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, m_OutputProjectionRef ); + itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, m_OutputProjectionRef ); - } +} - /** - * Convert point - */ - template <class TInputVectorData, class TOutputVectorData > - typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PointType - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::ReprojectPoint(PointType pointCoord) const - { +/** +* Convert point + */ +template <class TInputVectorData, class TOutputVectorData > +typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PointType +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::ReprojectPoint(PointType pointCoord) const +{ - itk::Point<double,2> point; + itk::Point<double,2> point; + + pointCoord[0] = pointCoord[0] * m_InputSpacing[0] + m_InputOrigin[0]; + pointCoord[1] = pointCoord[1] * m_InputSpacing[1] + m_InputOrigin[1]; + point = m_Transform->TransformPoint(pointCoord); + point[0] = (point[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; + point[1] = (point[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; + + return point; +} + +/** + * Convert line + */ +template <class TInputVectorData, class TOutputVectorData > +typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::LinePointerType +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::ReprojectLine(LinePointerType line) const +{ + typedef typename LineType::VertexListType::ConstPointer VertexListConstPointerType; + typedef typename LineType::VertexListConstIteratorType VertexListConstIteratorType; + VertexListConstPointerType vertexList = line->GetVertexList(); + VertexListConstIteratorType it = vertexList->Begin(); + typename LineType::Pointer newLine = LineType::New(); + while ( it != vertexList->End()) + { + itk::Point<double,2> point; + itk::ContinuousIndex<double,2> index; + typename LineType::VertexType pointCoord = it.Value(); pointCoord[0] = pointCoord[0] * m_InputSpacing[0] + m_InputOrigin[0]; pointCoord[1] = pointCoord[1] * m_InputSpacing[1] + m_InputOrigin[1]; point = m_Transform->TransformPoint(pointCoord); point[0] = (point[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; point[1] = (point[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; - - return point; + index[0]=point[0]; + index[1]=point[1]; +// otbMsgDevMacro(<< "Converting: " << it.Value() << " -> " << pointCoord << " -> " << point << " -> " << index); + newLine->AddVertex(index); + it++; } + return newLine; +} - /** - * Convert line - */ - template <class TInputVectorData, class TOutputVectorData > - typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::LinePointerType - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::ReprojectLine(LinePointerType line) const +/** + * Convert polygon + */ +template <class TInputVectorData, class TOutputVectorData > +typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PolygonPointerType +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::ReprojectPolygon(PolygonPointerType polygon) const +{ + typedef typename PolygonType::VertexListType::ConstPointer VertexListConstPointerType; + typedef typename PolygonType::VertexListConstIteratorType VertexListConstIteratorType; + VertexListConstPointerType vertexList = polygon->GetVertexList(); + VertexListConstIteratorType it = vertexList->Begin(); + typename PolygonType::Pointer newPolygon = PolygonType::New(); + while ( it != vertexList->End()) { - typedef typename LineType::VertexListType::ConstPointer VertexListConstPointerType; - typedef typename LineType::VertexListConstIteratorType VertexListConstIteratorType; - VertexListConstPointerType vertexList = line->GetVertexList(); - VertexListConstIteratorType it = vertexList->Begin(); - typename LineType::Pointer newLine = LineType::New(); - while ( it != vertexList->End()) - { - itk::Point<double,2> point; - itk::ContinuousIndex<double,2> index; - typename LineType::VertexType pointCoord = it.Value(); - pointCoord[0] = pointCoord[0] * m_InputSpacing[0] + m_InputOrigin[0]; - pointCoord[1] = pointCoord[1] * m_InputSpacing[1] + m_InputOrigin[1]; - point = m_Transform->TransformPoint(pointCoord); - point[0] = (point[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; - point[1] = (point[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; - index[0]=point[0]; - index[1]=point[1]; + itk::Point<double,2> point; + itk::ContinuousIndex<double,2> index; + typename PolygonType::VertexType pointCoord = it.Value(); + pointCoord[0] = pointCoord[0] * m_InputSpacing[0] + m_InputOrigin[0]; + pointCoord[1] = pointCoord[1] * m_InputSpacing[1] + m_InputOrigin[1]; + point = m_Transform->TransformPoint(pointCoord); + point[0] = (point[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; + point[1] = (point[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; + index[0]=point[0]; + index[1]=point[1]; // otbMsgDevMacro(<< "Converting: " << it.Value() << " -> " << pointCoord << " -> " << point << " -> " << index); - newLine->AddVertex(index); - it++; - } - - return newLine; + newPolygon->AddVertex(index); + it++; } + return newPolygon; +} - /** - * Convert polygon - */ - template <class TInputVectorData, class TOutputVectorData > - typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PolygonPointerType - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::ReprojectPolygon(PolygonPointerType polygon) const - { - typedef typename PolygonType::VertexListType::ConstPointer VertexListConstPointerType; - typedef typename PolygonType::VertexListConstIteratorType VertexListConstIteratorType; - VertexListConstPointerType vertexList = polygon->GetVertexList(); - VertexListConstIteratorType it = vertexList->Begin(); - typename PolygonType::Pointer newPolygon = PolygonType::New(); - while ( it != vertexList->End()) - { - itk::Point<double,2> point; - itk::ContinuousIndex<double,2> index; - typename PolygonType::VertexType pointCoord = it.Value(); - pointCoord[0] = pointCoord[0] * m_InputSpacing[0] + m_InputOrigin[0]; - pointCoord[1] = pointCoord[1] * m_InputSpacing[1] + m_InputOrigin[1]; - point = m_Transform->TransformPoint(pointCoord); - point[0] = (point[0] - m_OutputOrigin[0]) / m_OutputSpacing[0]; - point[1] = (point[1] - m_OutputOrigin[1]) / m_OutputSpacing[1]; - index[0]=point[0]; - index[1]=point[1]; -// otbMsgDevMacro(<< "Converting: " << it.Value() << " -> " << pointCoord << " -> " << point << " -> " << index); - newPolygon->AddVertex(index); - it++; - } - return newPolygon; - } +/** +* Convert polygon list + */ +template <class TInputVectorData, class TOutputVectorData > +typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PolygonListPointerType +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::ReprojectPolygonList(PolygonListPointerType polygonList) const +{ - /** - * Convert polygon list - */ - template <class TInputVectorData, class TOutputVectorData > - typename VectorDataProjectionFilter<TInputVectorData,TOutputVectorData>::PolygonListPointerType - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::ReprojectPolygonList(PolygonListPointerType polygonList) const + PolygonListPointerType newPolygonList = PolygonListType::New(); + for (typename PolygonListType::ConstIterator it = polygonList->Begin(); + it != polygonList->End(); ++it) { - - PolygonListPointerType newPolygonList = PolygonListType::New(); - for(typename PolygonListType::ConstIterator it = polygonList->Begin(); - it != polygonList->End(); ++it) - { - newPolygonList->PushBack(this->ReprojectPolygon(it.Get())); - } - return newPolygonList; + newPolygonList->PushBack(this->ReprojectPolygon(it.Get())); } + return newPolygonList; +} - /** - * Instanciate the transformation according to informations - */ - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::InstanciateTransform(void) - { +/** + * Instanciate the transformation according to informations + */ +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::InstanciateTransform(void) +{ - m_Transform = InternalTransformType::New(); + m_Transform = InternalTransformType::New(); - //If the information was not specified by the user, it is filled from the metadata - InputVectorDataPointer input = this->GetInput(); - const itk::MetaDataDictionary & inputDict = input->GetMetaDataDictionary(); + //If the information was not specified by the user, it is filled from the metadata + InputVectorDataPointer input = this->GetInput(); + const itk::MetaDataDictionary & inputDict = input->GetMetaDataDictionary(); - if (m_InputKeywordList.GetSize() == 0) - { - ossimKeywordlist kwl; - itk::ExposeMetaData<ossimKeywordlist>(inputDict, MetaDataKey::OSSIMKeywordlistKey, kwl ); - m_InputKeywordList.SetKeywordlist(kwl); - } - if (m_InputProjectionRef.empty()) - { - itk::ExposeMetaData<std::string>(inputDict, MetaDataKey::ProjectionRefKey, m_InputProjectionRef ); - } + if (m_InputKeywordList.GetSize() == 0) + { + ossimKeywordlist kwl; + itk::ExposeMetaData<ossimKeywordlist>(inputDict, MetaDataKey::OSSIMKeywordlistKey, kwl ); + m_InputKeywordList.SetKeywordlist(kwl); + } + if (m_InputProjectionRef.empty()) + { + itk::ExposeMetaData<std::string>(inputDict, MetaDataKey::ProjectionRefKey, m_InputProjectionRef ); + } - otbMsgDevMacro(<< "Information to instanciate transform: "); - otbMsgDevMacro(<< " - Input Origin: " << m_InputOrigin); - otbMsgDevMacro(<< " - Input Spacing: " << m_InputSpacing); - otbMsgDevMacro(<< " - Input keyword list: " << m_InputKeywordList); - otbMsgDevMacro(<< " - Input projection: " << m_InputProjectionRef); - otbMsgDevMacro(<< " - Output keyword list: " << m_OutputKeywordList); - otbMsgDevMacro(<< " - Output projection: " << m_OutputProjectionRef); - otbMsgDevMacro(<< " - Output Origin: " << m_OutputOrigin); - otbMsgDevMacro(<< " - Output Spacing: " << m_OutputSpacing); + otbMsgDevMacro(<< "Information to instanciate transform: "); + otbMsgDevMacro(<< " - Input Origin: " << m_InputOrigin); + otbMsgDevMacro(<< " - Input Spacing: " << m_InputSpacing); + otbMsgDevMacro(<< " - Input keyword list: " << m_InputKeywordList); + otbMsgDevMacro(<< " - Input projection: " << m_InputProjectionRef); + otbMsgDevMacro(<< " - Output keyword list: " << m_OutputKeywordList); + otbMsgDevMacro(<< " - Output projection: " << m_OutputProjectionRef); + otbMsgDevMacro(<< " - Output Origin: " << m_OutputOrigin); + otbMsgDevMacro(<< " - Output Spacing: " << m_OutputSpacing); - bool firstTransformGiveGeo = true; + bool firstTransformGiveGeo = true; - //***************************** - //Set the input transformation - //***************************** - if (m_InputKeywordList.GetSize() > 0) + //***************************** + //Set the input transformation + //***************************** + if (m_InputKeywordList.GetSize() > 0) + { + typedef otb::ForwardSensorModel<double> ForwardSensorModelType; + ForwardSensorModelType::Pointer sensorModel = ForwardSensorModelType::New(); + sensorModel->SetImageGeometry(m_InputKeywordList); + if ( !m_DEMDirectory.empty()) { - typedef otb::ForwardSensorModel<double> ForwardSensorModelType; - ForwardSensorModelType::Pointer sensorModel = ForwardSensorModelType::New(); - sensorModel->SetImageGeometry(m_InputKeywordList); - if ( !m_DEMDirectory.empty()) - { - sensorModel->SetDEMDirectory(m_DEMDirectory); - } - m_InputTransform = sensorModel.GetPointer(); - otbMsgDevMacro(<< "Input projection set to sensor model"); + sensorModel->SetDEMDirectory(m_DEMDirectory); } + m_InputTransform = sensorModel.GetPointer(); + otbMsgDevMacro(<< "Input projection set to sensor model"); + } - if ((m_InputTransform.IsNull()) && ( !m_InputProjectionRef.empty() ))//map projection + if ((m_InputTransform.IsNull()) && ( !m_InputProjectionRef.empty() ))//map projection + { + typedef otb::GenericMapProjection<otb::INVERSE> InverseMapProjectionType; + InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New(); + mapTransform->SetWkt(m_InputProjectionRef); + if (mapTransform->GetMapProjection() != NULL) { - typedef otb::GenericMapProjection<otb::INVERSE> InverseMapProjectionType; - InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New(); - mapTransform->SetWkt(m_InputProjectionRef); - if (mapTransform->GetMapProjection() != NULL) - { - m_InputTransform = mapTransform.GetPointer(); - otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform); - } - + m_InputTransform = mapTransform.GetPointer(); + otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform); } - if(m_InputTransform.IsNull())//default if we didn't manage to instantiate it before - { - m_InputTransform = itk::IdentityTransform< double, 2 >::New(); - firstTransformGiveGeo = false; - otbMsgDevMacro(<< "Input projection set to identity") - } + } + + if (m_InputTransform.IsNull())//default if we didn't manage to instantiate it before + { + m_InputTransform = itk::IdentityTransform< double, 2 >::New(); + firstTransformGiveGeo = false; + otbMsgDevMacro(<< "Input projection set to identity") + } - //***************************** - //Set the output transformation - //***************************** - if (m_OutputKeywordList.GetSize() > 0) + //***************************** + //Set the output transformation + //***************************** + if (m_OutputKeywordList.GetSize() > 0) + { + typedef otb::InverseSensorModel<double> InverseSensorModelType; + InverseSensorModelType::Pointer sensorModel = InverseSensorModelType::New(); + sensorModel->SetImageGeometry(m_OutputKeywordList); + if ( !m_DEMDirectory.empty()) { - typedef otb::InverseSensorModel<double> InverseSensorModelType; - InverseSensorModelType::Pointer sensorModel = InverseSensorModelType::New(); - sensorModel->SetImageGeometry(m_OutputKeywordList); - if ( !m_DEMDirectory.empty()) - { - sensorModel->SetDEMDirectory(m_DEMDirectory); - } - m_OutputTransform = sensorModel.GetPointer(); - otbMsgDevMacro(<< "Output projection set to sensor model"); + sensorModel->SetDEMDirectory(m_DEMDirectory); } + m_OutputTransform = sensorModel.GetPointer(); + otbMsgDevMacro(<< "Output projection set to sensor model"); + } - if ((m_OutputTransform.IsNull()) && ( !m_OutputProjectionRef.empty() ))//map projection + if ((m_OutputTransform.IsNull()) && ( !m_OutputProjectionRef.empty() ))//map projection + { + typedef otb::GenericMapProjection<otb::FORWARD> ForwardMapProjectionType; + ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New(); + mapTransform->SetWkt(m_OutputProjectionRef); + if (mapTransform->GetMapProjection() != NULL) { - typedef otb::GenericMapProjection<otb::FORWARD> ForwardMapProjectionType; - ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New(); - mapTransform->SetWkt(m_OutputProjectionRef); - if (mapTransform->GetMapProjection() != NULL) - { - m_OutputTransform = mapTransform.GetPointer(); - otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform); - } - + m_OutputTransform = mapTransform.GetPointer(); + otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform); } - if(m_OutputTransform.IsNull())//default if we didn't manage to instantiate it before + } + + if (m_OutputTransform.IsNull())//default if we didn't manage to instantiate it before + { + m_OutputTransform = itk::IdentityTransform< double, 2 >::New(); + if (firstTransformGiveGeo) { - m_OutputTransform = itk::IdentityTransform< double, 2 >::New(); - if (firstTransformGiveGeo) - { - m_OutputProjectionRef = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]"; - } - otbMsgDevMacro(<< "Output projection set to identity"); + m_OutputProjectionRef = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]"; } + otbMsgDevMacro(<< "Output projection set to identity"); + } - //If the projection information for the output is provided, propagate it - OutputVectorDataPointer output = this->GetOutput(); - itk::MetaDataDictionary & outputDict = output->GetMetaDataDictionary(); + //If the projection information for the output is provided, propagate it + OutputVectorDataPointer output = this->GetOutput(); + itk::MetaDataDictionary & outputDict = output->GetMetaDataDictionary(); - if (m_OutputKeywordList.GetSize() != 0) - { - ossimKeywordlist kwl; - m_OutputKeywordList.convertToOSSIMKeywordlist (kwl); - itk::EncapsulateMetaData<ossimKeywordlist>(outputDict, MetaDataKey::OSSIMKeywordlistKey, kwl ); - } - if ( !m_OutputProjectionRef.empty()) - { - itk::EncapsulateMetaData<std::string>(outputDict, MetaDataKey::ProjectionRefKey, m_OutputProjectionRef ); - } + if (m_OutputKeywordList.GetSize() != 0) + { + ossimKeywordlist kwl; + m_OutputKeywordList.convertToOSSIMKeywordlist (kwl); + itk::EncapsulateMetaData<ossimKeywordlist>(outputDict, MetaDataKey::OSSIMKeywordlistKey, kwl ); + } + if ( !m_OutputProjectionRef.empty()) + { + itk::EncapsulateMetaData<std::string>(outputDict, MetaDataKey::ProjectionRefKey, m_OutputProjectionRef ); + } - m_Transform->SetFirstTransform(m_InputTransform); - m_Transform->SetSecondTransform(m_OutputTransform); + m_Transform->SetFirstTransform(m_InputTransform); + m_Transform->SetSecondTransform(m_OutputTransform); - } +} /** * GenerateData Performs the coordinate convertion for each element in the tree */ - template <class TInputVectorData, class TOutputVectorData > - void - VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> - ::GenerateData(void) - { - this->AllocateOutputs(); - InputVectorDataPointer inputPtr = this->GetInput(); - OutputVectorDataPointer outputPtr = this->GetOutput(); +template <class TInputVectorData, class TOutputVectorData > +void +VectorDataProjectionFilter<TInputVectorData,TOutputVectorData> +::GenerateData(void) +{ + this->AllocateOutputs(); + InputVectorDataPointer inputPtr = this->GetInput(); + OutputVectorDataPointer outputPtr = this->GetOutput(); - //Instanciate the transform - this->InstanciateTransform(); + //Instanciate the transform + this->InstanciateTransform(); - itk::ProgressReporter progress(this, 0, inputPtr->Size()); + itk::ProgressReporter progress(this, 0, inputPtr->Size()); - InputTreeIteratorType it(inputPtr->GetDataTree()); - OutputDataTreePointerType tree = outputPtr->GetDataTree(); + InputTreeIteratorType it(inputPtr->GetDataTree()); + OutputDataTreePointerType tree = outputPtr->GetDataTree(); - OutputDataNodePointerType currentContainer; + OutputDataNodePointerType currentContainer; - while(!it.IsAtEnd())//FIXME this VectorData tree processing would better be in a generic class + while (!it.IsAtEnd())//FIXME this VectorData tree processing would better be in a generic class + { + InputDataNodePointerType dataNode = it.Get(); + OutputDataNodePointerType newDataNode = OutputDataNodeType::New(); + newDataNode->SetNodeType(dataNode->GetNodeType()); + newDataNode->SetNodeId(dataNode->GetNodeId()); + switch (dataNode->GetNodeType()) + { + case ROOT: { - InputDataNodePointerType dataNode = it.Get(); - OutputDataNodePointerType newDataNode = OutputDataNodeType::New(); - newDataNode->SetNodeType(dataNode->GetNodeType()); - newDataNode->SetNodeId(dataNode->GetNodeId()); - switch(dataNode->GetNodeType()) - { - case ROOT: - { - tree->SetRoot(newDataNode); - currentContainer = newDataNode; - break; - } - case DOCUMENT: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - case FOLDER: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - case FEATURE_POINT: - { - newDataNode->SetPoint(this->ReprojectPoint(dataNode->GetPoint())); - tree->Add(newDataNode,currentContainer); - break; - } - case FEATURE_LINE: - { - newDataNode->SetLine(this->ReprojectLine(dataNode->GetLine())); - tree->Add(newDataNode,currentContainer); - break; - } - case FEATURE_POLYGON: - { - newDataNode->SetPolygonExteriorRing(this->ReprojectPolygon(dataNode->GetPolygonExteriorRing())); - newDataNode->SetPolygonInteriorRings(this->ReprojectPolygonList(dataNode->GetPolygonInteriorRings())); - tree->Add(newDataNode,currentContainer); - break; - } - case FEATURE_MULTIPOINT: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - case FEATURE_MULTILINE: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - case FEATURE_MULTIPOLYGON: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - case FEATURE_COLLECTION: - { - tree->Add(newDataNode,currentContainer); - currentContainer = newDataNode; - break; - } - } - progress.CompletedPixel(); - ++it; + tree->SetRoot(newDataNode); + currentContainer = newDataNode; + break; } - + case DOCUMENT: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + case FOLDER: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + case FEATURE_POINT: + { + newDataNode->SetPoint(this->ReprojectPoint(dataNode->GetPoint())); + tree->Add(newDataNode,currentContainer); + break; + } + case FEATURE_LINE: + { + newDataNode->SetLine(this->ReprojectLine(dataNode->GetLine())); + tree->Add(newDataNode,currentContainer); + break; + } + case FEATURE_POLYGON: + { + newDataNode->SetPolygonExteriorRing(this->ReprojectPolygon(dataNode->GetPolygonExteriorRing())); + newDataNode->SetPolygonInteriorRings(this->ReprojectPolygonList(dataNode->GetPolygonInteriorRings())); + tree->Add(newDataNode,currentContainer); + break; + } + case FEATURE_MULTIPOINT: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + case FEATURE_MULTILINE: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + case FEATURE_MULTIPOLYGON: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + case FEATURE_COLLECTION: + { + tree->Add(newDataNode,currentContainer); + currentContainer = newDataNode; + break; + } + } + progress.CompletedPixel(); + ++it; } +} + } // end namespace otb #endif diff --git a/Code/Radiometry/otbAtmosphericCorrectionParameters.cxx b/Code/Radiometry/otbAtmosphericCorrectionParameters.cxx index 23144a83072d7304cecc5e0fd4ec560387045d42..7c7c182efb5835ae19af81a7ff3f14e88232665f 100644 --- a/Code/Radiometry/otbAtmosphericCorrectionParameters.cxx +++ b/Code/Radiometry/otbAtmosphericCorrectionParameters.cxx @@ -20,73 +20,73 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /*********************** FilterFunctionValues **************************/ - FilterFunctionValues - ::FilterFunctionValues() +/*********************** FilterFunctionValues **************************/ +FilterFunctionValues +::FilterFunctionValues() +{ + m_MinSpectralValue = 0; + m_MaxSpectralValue = 0; + m_FilterFunctionValues.clear(); +} + +/**PrintSelf method */ +void +FilterFunctionValues +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Minimum spectral value: " << m_MinSpectralValue << std::endl; + os << indent << "Maximum spectral value: " << m_MaxSpectralValue << std::endl; + os << indent << "User Step between each wavelenght spectral band values: " << m_UserStep << std::endl; + os << indent << "Filter function Vector Values: " << std::endl; + for (unsigned int i=0; i<m_FilterFunctionValues.size(); i++) { - m_MinSpectralValue = 0; - m_MaxSpectralValue = 0; - m_FilterFunctionValues.clear(); + os << indent << m_FilterFunctionValues[i] <<std::endl; } - - /**PrintSelf method */ - void - FilterFunctionValues - ::PrintSelf(std::ostream& os, itk::Indent indent) const + os << indent << "Filter function Vector Values 6S: " << std::endl; + for (unsigned int i=0; i<m_FilterFunctionValues6S.size(); i++) { - Superclass::PrintSelf(os,indent); - os << indent << "Minimum spectral value: " << m_MinSpectralValue << std::endl; - os << indent << "Maximum spectral value: " << m_MaxSpectralValue << std::endl; - os << indent << "User Step between each wavelenght spectral band values: " << m_UserStep << std::endl; - os << indent << "Filter function Vector Values: " << std::endl; - for (unsigned int i=0; i<m_FilterFunctionValues.size(); i++) - { - os << indent << m_FilterFunctionValues[i] <<std::endl; - } - os << indent << "Filter function Vector Values 6S: " << std::endl; - for (unsigned int i=0; i<m_FilterFunctionValues6S.size(); i++) - { - os << indent << m_FilterFunctionValues6S[i] <<std::endl; - } + os << indent << m_FilterFunctionValues6S[i] <<std::endl; } +} - /*********************** AtmosphericCorrectionParameters **************************/ - /** - * Constructor - */ +/*********************** AtmosphericCorrectionParameters **************************/ +/** + * Constructor + */ - AtmosphericCorrectionParameters - ::AtmosphericCorrectionParameters() - { - m_AerosolModel = CONTINENTAL; - } +AtmosphericCorrectionParameters +::AtmosphericCorrectionParameters() +{ + m_AerosolModel = CONTINENTAL; +} - /**PrintSelf method */ - void - AtmosphericCorrectionParameters - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "Solar zenithal angle: " << m_SolarZenithalAngle << std::endl; - os << indent << "Solar azimutal angle: " << m_SolarAzimutalAngle << std::endl; - os << indent << "Viewing zenithal angle: " << m_ViewingZenithalAngle << std::endl; - os << indent << "Viewing azimutal angle: " << m_ViewingAzimutalAngle << std::endl; - os << indent << "Month: " << m_Month << std::endl; - os << indent << "Day: " << m_Day << std::endl; - os << indent << "Atmospheric pressure: " << m_AtmosphericPressure << std::endl; - os << indent << "Water vapor amount: " << m_WaterVaporAmount << std::endl; - os << indent << "Ozone amount: " << m_OzoneAmount << std::endl; - os << indent << "Aerosol model: " << m_AerosolModel << std::endl; - os << indent << "Aerosol optical : " << m_AerosolOptical << std::endl; +/**PrintSelf method */ +void +AtmosphericCorrectionParameters +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Solar zenithal angle: " << m_SolarZenithalAngle << std::endl; + os << indent << "Solar azimutal angle: " << m_SolarAzimutalAngle << std::endl; + os << indent << "Viewing zenithal angle: " << m_ViewingZenithalAngle << std::endl; + os << indent << "Viewing azimutal angle: " << m_ViewingAzimutalAngle << std::endl; + os << indent << "Month: " << m_Month << std::endl; + os << indent << "Day: " << m_Day << std::endl; + os << indent << "Atmospheric pressure: " << m_AtmosphericPressure << std::endl; + os << indent << "Water vapor amount: " << m_WaterVaporAmount << std::endl; + os << indent << "Ozone amount: " << m_OzoneAmount << std::endl; + os << indent << "Aerosol model: " << m_AerosolModel << std::endl; + os << indent << "Aerosol optical : " << m_AerosolOptical << std::endl; - // Function values print : - os << indent << "Filter function Values: " << std::endl; - for (unsigned int i=0; i<m_WavelenghtSpectralBand.size(); i++) - { - os << indent << "Channel : "<< i+1 <<" : " << std::endl; - os << indent << m_WavelenghtSpectralBand[i]<< std::endl; - } - } + // Function values print : + os << indent << "Filter function Values: " << std::endl; + for (unsigned int i=0; i<m_WavelenghtSpectralBand.size(); i++) + { + os << indent << "Channel : "<< i+1 <<" : " << std::endl; + os << indent << m_WavelenghtSpectralBand[i]<< std::endl; + } +} } // end namespace otb diff --git a/Code/Radiometry/otbAtmosphericCorrectionParameters.h b/Code/Radiometry/otbAtmosphericCorrectionParameters.h index e40a8318bd21d457e79ea895bd3641551995e207..8e3aa22e9fff6bf8a9935f56d1a2cb0fe10993e1 100644 --- a/Code/Radiometry/otbAtmosphericCorrectionParameters.h +++ b/Code/Radiometry/otbAtmosphericCorrectionParameters.h @@ -28,87 +28,93 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class FilterFunctionValues - * \brief This class contains the values of the filter function for the processed spectral band. - * - * The step between 2 values is 0.0025µm. The class contains the min and the max value.Those value can be directly read from the image metadatas. - */ - class ITK_EXPORT FilterFunctionValues : public itk::DataObject - { - public: - /** Standard typedefs */ - typedef FilterFunctionValues Self; - typedef itk::DataObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; +/** \class FilterFunctionValues + * \brief This class contains the values of the filter function for the processed spectral band. + * + * The step between 2 values is 0.0025µm. The class contains the min and the max value.Those value can be directly read from the image metadatas. + */ +class ITK_EXPORT FilterFunctionValues : public itk::DataObject +{ +public: + /** Standard typedefs */ + typedef FilterFunctionValues Self; + typedef itk::DataObject Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; - /** Type macro */ - itkTypeMacro(FilterFunctionValues,DataObject); + /** Type macro */ + itkTypeMacro(FilterFunctionValues,DataObject); - /** Creation through object factory macro */ - itkNewMacro(Self); + /** Creation through object factory macro */ + itkNewMacro(Self); - typedef double WavelenghtSpectralBandType; - typedef std::vector<WavelenghtSpectralBandType> ValuesVectorType; + typedef double WavelenghtSpectralBandType; + typedef std::vector<WavelenghtSpectralBandType> ValuesVectorType; - /** Set vector that contains the filter function value. */ - void SetFilterFunctionValues(const ValuesVectorType & vect) + /** Set vector that contains the filter function value. */ + void SetFilterFunctionValues(const ValuesVectorType & vect) { m_FilterFunctionValues = vect; this->Modified(); }; - /** Get vector that contains the filter function value. */ - const ValuesVectorType & GetFilterFunctionValues() const { return m_FilterFunctionValues; }; - /** Get vector that contains the filter function value 6S. */ - void SetFilterFunctionValues6S(const ValuesVectorType & vect) - { - m_FilterFunctionValues6S = vect; + /** Get vector that contains the filter function value. */ + const ValuesVectorType & GetFilterFunctionValues() const + { + return m_FilterFunctionValues; + }; + /** Get vector that contains the filter function value 6S. */ + void SetFilterFunctionValues6S(const ValuesVectorType & vect) + { + m_FilterFunctionValues6S = vect; this->Modified(); - }; - /** Get vector that contains the filter function value 6S. */ - const ValuesVectorType & GetFilterFunctionValues6S() const { return m_FilterFunctionValues6S; }; - - /** Set minimum spectral value. */ - itkSetMacro(MinSpectralValue,WavelenghtSpectralBandType); - /** Get minimum spectral value. */ - itkGetMacro(MinSpectralValue,WavelenghtSpectralBandType); - /** Set maximum spectral value. This value is automatically computed.*/ - itkSetMacro(MaxSpectralValue,WavelenghtSpectralBandType); - /** Get maximum spectral value. This value is automatically computed.*/ - itkGetMacro(MaxSpectralValue,WavelenghtSpectralBandType); - /** Set user step between each wavelenght spectral band values. */ - itkSetMacro(UserStep,WavelenghtSpectralBandType); - /** Get user step between each wavelenght spectral band values. */ - itkGetMacro(UserStep,WavelenghtSpectralBandType); - - protected: - /** Constructor */ - FilterFunctionValues(); - /** Destructor */ - ~FilterFunctionValues(){}; - - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - - private: - FilterFunctionValues(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - - /** Vector that contains the filter function value. */ - ValuesVectorType m_FilterFunctionValues; - /** Vector that contains the filter function value in 6S format (step of 0.0025µm). - * There values a computed by 6S. If the UserStep is 0.0025µm, then m_FilterFunctionValues is identical as m_FilterFunctionValues6S - */ - ValuesVectorType m_FilterFunctionValues6S; - /** Minimum spectral value (in µm). */ - WavelenghtSpectralBandType m_MinSpectralValue; - /** Maximum spectral value (in µm). */ - WavelenghtSpectralBandType m_MaxSpectralValue; - /** User step between each wavelenght spectral band values. (in µm) */ - WavelenghtSpectralBandType m_UserStep; - }; + }; + /** Get vector that contains the filter function value 6S. */ + const ValuesVectorType & GetFilterFunctionValues6S() const + { + return m_FilterFunctionValues6S; + }; + + /** Set minimum spectral value. */ + itkSetMacro(MinSpectralValue,WavelenghtSpectralBandType); + /** Get minimum spectral value. */ + itkGetMacro(MinSpectralValue,WavelenghtSpectralBandType); + /** Set maximum spectral value. This value is automatically computed.*/ + itkSetMacro(MaxSpectralValue,WavelenghtSpectralBandType); + /** Get maximum spectral value. This value is automatically computed.*/ + itkGetMacro(MaxSpectralValue,WavelenghtSpectralBandType); + /** Set user step between each wavelenght spectral band values. */ + itkSetMacro(UserStep,WavelenghtSpectralBandType); + /** Get user step between each wavelenght spectral band values. */ + itkGetMacro(UserStep,WavelenghtSpectralBandType); + +protected: + /** Constructor */ + FilterFunctionValues(); + /** Destructor */ + ~FilterFunctionValues() {}; + + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + +private: + FilterFunctionValues(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + + /** Vector that contains the filter function value. */ + ValuesVectorType m_FilterFunctionValues; + /** Vector that contains the filter function value in 6S format (step of 0.0025µm). + * There values a computed by 6S. If the UserStep is 0.0025µm, then m_FilterFunctionValues is identical as m_FilterFunctionValues6S + */ + ValuesVectorType m_FilterFunctionValues6S; + /** Minimum spectral value (in µm). */ + WavelenghtSpectralBandType m_MinSpectralValue; + /** Maximum spectral value (in µm). */ + WavelenghtSpectralBandType m_MaxSpectralValue; + /** User step between each wavelenght spectral band values. (in µm) */ + WavelenghtSpectralBandType m_UserStep; +}; @@ -205,26 +211,35 @@ public: /** * Set/Get the wavelenght spectral band. */ - void SetWavelenghtSpectralBand( const WavelenghtSpectralBandVectorType & waveband){ m_WavelenghtSpectralBand = waveband; }; + void SetWavelenghtSpectralBand( const WavelenghtSpectralBandVectorType & waveband) + { + m_WavelenghtSpectralBand = waveband; + }; void SetWavelenghtSpectralBandWithIndex( unsigned int id, const FilterFunctionValues::Pointer & function) - { - if (m_WavelenghtSpectralBand.size() < id+1) { - for(unsigned int j=0; j<(id+1-m_WavelenghtSpectralBand.size());j++) + if (m_WavelenghtSpectralBand.size() < id+1) + { + for (unsigned int j=0; j<(id+1-m_WavelenghtSpectralBand.size());j++) { FilterFunctionValues::Pointer temp; m_WavelenghtSpectralBand.push_back(temp); } - } - m_WavelenghtSpectralBand[id] = function; - }; - WavelenghtSpectralBandVectorType GetWavelenghtSpectralBand(){ return m_WavelenghtSpectralBand; }; - WavelenghtSpectralBandVectorType * GetWavelenghtSpectralBandRef(){ return &m_WavelenghtSpectralBand; }; + } + m_WavelenghtSpectralBand[id] = function; + }; + WavelenghtSpectralBandVectorType GetWavelenghtSpectralBand() + { + return m_WavelenghtSpectralBand; + }; + WavelenghtSpectralBandVectorType * GetWavelenghtSpectralBandRef() + { + return &m_WavelenghtSpectralBand; + }; /** Constructor */ AtmosphericCorrectionParameters(); /** Destructor */ - ~AtmosphericCorrectionParameters(){}; + ~AtmosphericCorrectionParameters() {}; protected: diff --git a/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.cxx b/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.cxx index 7ed73558e09d23c5f23b9943cc0fb11a742e3d64..fe179f10385a95f6095d0e5de9ae4460a765dd18 100644 --- a/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.cxx +++ b/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.cxx @@ -32,7 +32,7 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputPointSet AtmosphericRadiativeTermsPointer output - = static_cast<AtmosphericRadiativeTermsType*>(this->MakeOutput(0).GetPointer()); + = static_cast<AtmosphericRadiativeTermsType*>(this->MakeOutput(0).GetPointer()); this->ProcessObject::SetNthOutput( 0, output.GetPointer() ); @@ -66,15 +66,15 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms ::GraftNthOutput(unsigned int idx, itk::DataObject *graft) { if ( idx >= this->GetNumberOfOutputs() ) - { + { itkExceptionMacro(<<"Requested to graft output " << idx << - " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); - } + " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); + } if ( !graft ) - { + { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); - } + } itk::DataObject * output = this->GetOutput( idx ); @@ -91,10 +91,10 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms::AtmosphericRadiati AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms ::GetOutput(void) { - if(this->GetNumberOfOutputs()<1) - { - return 0; - } + if (this->GetNumberOfOutputs()<1) + { + return 0; + } return static_cast<AtmosphericRadiativeTermsType *> (this->ProcessObject::GetOutput(0)); } @@ -106,7 +106,7 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms ::GetOutput(unsigned int idx) { return static_cast<AtmosphericRadiativeTermsType*> - (this->itk::ProcessObject::GetOutput(idx)); + (this->itk::ProcessObject::GetOutput(idx)); } @@ -124,13 +124,13 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms { // If there is no input if (this->GetNumberOfInputs()!=1) - { + { // exit return 0; - } + } // else return the first input return static_cast<AtmosphericCorrectionParametersType * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } @@ -156,53 +156,53 @@ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms double upwardDiffuseTransmittanceForRayleigh(0.); double upwardDiffuseTransmittanceForAerosol(0.); - for(unsigned int i=0; i<NbBand; i++) - { - atmosphericReflectance = 0.; - atmosphericSphericalAlbedo = 0.; - totalGaseousTransmission = 0.; - downwardTransmittance = 0.; - upwardTransmittance = 0.; - upwardDiffuseTransmittance = 0.; - upwardDirectTransmittance = 0.; - upwardDiffuseTransmittanceForRayleigh = 0.; - upwardDiffuseTransmittanceForAerosol = 0.; - SIXSTraits::ComputeAtmosphericParameters( - input->GetSolarZenithalAngle(), /** The Solar zenithal angle */ - input->GetSolarAzimutalAngle(), /** The Solar azimutal angle */ - input->GetViewingZenithalAngle(), /** The Viewing zenithal angle */ - input->GetViewingAzimutalAngle(), /** The Viewing azimutal angle */ - input->GetMonth(), /** The Month */ - input->GetDay(), /** The Day (in the month) */ - input->GetAtmosphericPressure(), /** The Atmospheric pressure */ - input->GetWaterVaporAmount(), /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ - input->GetOzoneAmount(), /** The Ozone amount (Stratospheric ozone layer content) */ - input->GetAerosolModel(), /** The Aerosol model */ - input->GetAerosolOptical(), /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ - input->GetWavelenghtSpectralBand()[i], /** Wavelenght for the spectral band definition */ - /** Note : The Max wavelenght spectral band value must be updated ! */ - atmosphericReflectance, /** Atmospheric reflectance */ - atmosphericSphericalAlbedo, /** atmospheric spherical albedo */ - totalGaseousTransmission, /** Total gaseous transmission */ - downwardTransmittance, /** downward transmittance */ - upwardTransmittance, /** upward transmittance */ - upwardDiffuseTransmittance, /** Upward diffuse transmittance */ - upwardDirectTransmittance, /** Upward direct transmittance */ - upwardDiffuseTransmittanceForRayleigh, /** Upward diffuse transmittance for rayleigh */ - upwardDiffuseTransmittanceForAerosol /** Upward diffuse transmittance for aerosols */ - ); - - output->SetIntrinsicAtmosphericReflectance(i, atmosphericReflectance); - output->SetSphericalAlbedo(i, atmosphericSphericalAlbedo); - output->SetTotalGaseousTransmission(i, totalGaseousTransmission); - output->SetDownwardTransmittance(i, downwardTransmittance); - output->SetUpwardTransmittance(i, upwardTransmittance); - output->SetUpwardDiffuseTransmittance(i, upwardDiffuseTransmittance ); - output->SetUpwardDirectTransmittance(i, upwardDirectTransmittance); - output->SetUpwardDiffuseTransmittanceForRayleigh(i,upwardDiffuseTransmittanceForRayleigh ); - output->SetUpwardDiffuseTransmittanceForAerosol(i, upwardDiffuseTransmittanceForAerosol); - - } + for (unsigned int i=0; i<NbBand; i++) + { + atmosphericReflectance = 0.; + atmosphericSphericalAlbedo = 0.; + totalGaseousTransmission = 0.; + downwardTransmittance = 0.; + upwardTransmittance = 0.; + upwardDiffuseTransmittance = 0.; + upwardDirectTransmittance = 0.; + upwardDiffuseTransmittanceForRayleigh = 0.; + upwardDiffuseTransmittanceForAerosol = 0.; + SIXSTraits::ComputeAtmosphericParameters( + input->GetSolarZenithalAngle(), /** The Solar zenithal angle */ + input->GetSolarAzimutalAngle(), /** The Solar azimutal angle */ + input->GetViewingZenithalAngle(), /** The Viewing zenithal angle */ + input->GetViewingAzimutalAngle(), /** The Viewing azimutal angle */ + input->GetMonth(), /** The Month */ + input->GetDay(), /** The Day (in the month) */ + input->GetAtmosphericPressure(), /** The Atmospheric pressure */ + input->GetWaterVaporAmount(), /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ + input->GetOzoneAmount(), /** The Ozone amount (Stratospheric ozone layer content) */ + input->GetAerosolModel(), /** The Aerosol model */ + input->GetAerosolOptical(), /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ + input->GetWavelenghtSpectralBand()[i], /** Wavelenght for the spectral band definition */ + /** Note : The Max wavelenght spectral band value must be updated ! */ + atmosphericReflectance, /** Atmospheric reflectance */ + atmosphericSphericalAlbedo, /** atmospheric spherical albedo */ + totalGaseousTransmission, /** Total gaseous transmission */ + downwardTransmittance, /** downward transmittance */ + upwardTransmittance, /** upward transmittance */ + upwardDiffuseTransmittance, /** Upward diffuse transmittance */ + upwardDirectTransmittance, /** Upward direct transmittance */ + upwardDiffuseTransmittanceForRayleigh, /** Upward diffuse transmittance for rayleigh */ + upwardDiffuseTransmittanceForAerosol /** Upward diffuse transmittance for aerosols */ + ); + + output->SetIntrinsicAtmosphericReflectance(i, atmosphericReflectance); + output->SetSphericalAlbedo(i, atmosphericSphericalAlbedo); + output->SetTotalGaseousTransmission(i, totalGaseousTransmission); + output->SetDownwardTransmittance(i, downwardTransmittance); + output->SetUpwardTransmittance(i, upwardTransmittance); + output->SetUpwardDiffuseTransmittance(i, upwardDiffuseTransmittance ); + output->SetUpwardDirectTransmittance(i, upwardDirectTransmittance); + output->SetUpwardDiffuseTransmittanceForRayleigh(i,upwardDiffuseTransmittanceForRayleigh ); + output->SetUpwardDiffuseTransmittanceForAerosol(i, upwardDiffuseTransmittanceForAerosol); + + } } /** diff --git a/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.h b/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.h index 6f2c2a8f34a6531b9bc8db146717343b02cea5b3..79242e81bd9d51414967c01ecc10d6606b8ff44f 100644 --- a/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.h +++ b/Code/Radiometry/otbAtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms.h @@ -25,15 +25,15 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * \class AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms - * \brief This class computes the atmospheric radiative terms with 6S. - * \ingroup DataSources - */ +/** + * \class AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms + * \brief This class computes the atmospheric radiative terms with 6S. + * \ingroup DataSources + */ class ITK_EXPORT AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms - : public itk::ProcessObject + : public itk::ProcessObject { - public: +public: /** Standard typedefs */ typedef AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms Self; typedef itk::ProcessObject Superclass; @@ -44,7 +44,7 @@ class ITK_EXPORT AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms /** Runtime information */ itkTypeMacro(AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms,itk::ProcessObject); - /** Creation througth the object factory */ + /** Creation througth the object factory */ itkNewMacro(Self); /** Template parameters typedefs */ typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType; @@ -70,7 +70,7 @@ class ITK_EXPORT AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms /** Generate the output.*/ virtual void GenerateData(); - protected: +protected: /** Constructor */ AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms(); /** Destructor */ diff --git a/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx b/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx index 0ec9a59c503fd635239fdce7d0377ad03b473e7f..5239612649be5bbaaf57be6e98a33035962a02bf 100644 --- a/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx +++ b/Code/Radiometry/otbAtmosphericRadiativeTerms.cxx @@ -56,9 +56,9 @@ AtmosphericRadiativeTerms { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); for (unsigned int j=0; j<nbChannel; j++) - { - m_Values.push_back(temp); - } + { + m_Values.push_back(temp); + } m_IsInitialized = true; } @@ -68,40 +68,40 @@ AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectances(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); + { + this->ValuesInitialization(vect.size()); - } + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetIntrinsicAtmosphericReflectance(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetIntrinsicAtmosphericReflectance(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetSphericalAlbedos(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetSphericalAlbedo(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetSphericalAlbedo(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetTotalGaseousTransmissions(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetTotalGaseousTransmission(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetTotalGaseousTransmission(vect[nbChannel]); + } } void @@ -109,78 +109,78 @@ AtmosphericRadiativeTerms ::SetDownwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetDownwardTransmittance(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetDownwardTransmittance(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetUpwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetUpwardTransmittance(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetUpwardTransmittance(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetUpwardDiffuseTransmittance(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetUpwardDiffuseTransmittance(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetUpwardDirectTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetUpwardDirectTransmittance(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetUpwardDirectTransmittance(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittancesForRayleigh(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetUpwardDiffuseTransmittanceForRayleigh(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetUpwardDiffuseTransmittanceForRayleigh(vect[nbChannel]); + } } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittancesForAerosol(const DataVectorType & vect) { if ( !m_IsInitialized) - { - this->ValuesInitialization(vect.size()); - } + { + this->ValuesInitialization(vect.size()); + } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) - { - m_Values[nbChannel]->SetUpwardDiffuseTransmittanceForAerosol(vect[nbChannel]); - } + { + m_Values[nbChannel]->SetUpwardDiffuseTransmittanceForAerosol(vect[nbChannel]); + } } /** SET ACCESSORS WITH INDEX. */ @@ -189,34 +189,34 @@ AtmosphericRadiativeTerms ::SetValueByIndex(unsigned int id, const ValueType & val) { if ( m_IsInitialized ) - { - if ( m_Values.size()<id+1 ) { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) + { + for (unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } - } - m_Values[id] = val; } + m_Values[id] = val; + } else - { - itkExceptionMacro(<< "Can't insert value before iniatilizing vector value..."<<std::endl); - } + { + itkExceptionMacro(<< "Can't insert value before iniatilizing vector value..."<<std::endl); + } } void AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectance(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetIntrinsicAtmosphericReflectance(val); } void @@ -224,13 +224,13 @@ AtmosphericRadiativeTerms ::SetSphericalAlbedo(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetSphericalAlbedo(val); } void @@ -238,97 +238,97 @@ AtmosphericRadiativeTerms ::SetTotalGaseousTransmission(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetTotalGaseousTransmission(val); } void AtmosphericRadiativeTerms ::SetDownwardTransmittance(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetDownwardTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardTransmittance(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetUpwardTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittance(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetUpwardDiffuseTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardDirectTransmittance(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetUpwardDirectTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittanceForRayleigh(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetUpwardDiffuseTransmittanceForRayleigh(val); } void AtmosphericRadiativeTerms ::SetUpwardDiffuseTransmittanceForAerosol(unsigned int id, const double & val ) { - if ( m_Values.size()<id+1 ) - { - for(unsigned int j=0; j<(id+1-m_Values.size());j++) + if ( m_Values.size()<id+1 ) { - ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); - m_Values.push_back(temp); - } + for (unsigned int j=0; j<(id+1-m_Values.size());j++) + { + ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); + m_Values.push_back(temp); } + } m_Values[id]->SetUpwardDiffuseTransmittanceForAerosol(val); } @@ -339,9 +339,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -350,9 +350,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetSphericalAlbedo(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetSphericalAlbedo(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -361,9 +361,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetTotalGaseousTransmission(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetTotalGaseousTransmission(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -372,9 +372,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetDownwardTransmittance(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetDownwardTransmittance(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -383,9 +383,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetUpwardTransmittance(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetUpwardTransmittance(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -394,9 +394,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittance(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittance(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -405,9 +405,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetUpwardDirectTransmittance(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetUpwardDirectTransmittance(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -416,9 +416,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittanceForRayleigh(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittanceForRayleigh(); + } return vect; } AtmosphericRadiativeTerms::DataVectorType @@ -427,9 +427,9 @@ AtmosphericRadiativeTerms { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) - { - vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittanceForAerosol(); - } + { + vect[nbChannel] = m_Values[nbChannel]->GetUpwardDiffuseTransmittanceForAerosol(); + } return vect; } @@ -502,10 +502,10 @@ AtmosphericRadiativeTerms ::PrintSelf(std::ostream& os, itk::Indent indent) const { for (unsigned int i=0; i<m_Values.size(); i++) - { - os << indent << "Channel "<< i << " : "<< std::endl; - //ValueType::(os,indent); - } + { + os << indent << "Channel "<< i << " : "<< std::endl; + //ValueType::(os,indent); + } } diff --git a/Code/Radiometry/otbAtmosphericRadiativeTerms.h b/Code/Radiometry/otbAtmosphericRadiativeTerms.h index 444f00403cb1c2511fefed4b68513cc4f5b026d4..0c725de5d64a4739571807214d41efab28c10ce4 100644 --- a/Code/Radiometry/otbAtmosphericRadiativeTerms.h +++ b/Code/Radiometry/otbAtmosphericRadiativeTerms.h @@ -67,9 +67,9 @@ public: itkSetMacro(TotalGaseousTransmission,double); itkGetMacro(TotalGaseousTransmission,double); - /** - * Set/Get the downward transmittance of the atmosphere. - */ + /** + * Set/Get the downward transmittance of the atmosphere. + */ itkSetMacro(DownwardTransmittance,double); itkGetMacro(DownwardTransmittance,double); @@ -105,9 +105,9 @@ public: protected: /** Constructor */ - AtmosphericRadiativeTermsSingleChannel(){}; + AtmosphericRadiativeTermsSingleChannel() {}; /** Destructor */ - ~AtmosphericRadiativeTermsSingleChannel(){}; + ~AtmosphericRadiativeTermsSingleChannel() {}; /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; @@ -128,19 +128,19 @@ private: /** The downward transmittance. */ double m_DownwardTransmittance; - /** The upward transmittance. */ + /** The upward transmittance. */ double m_UpwardTransmittance; - /** The upward diffuse transmittance. */ + /** The upward diffuse transmittance. */ double m_UpwardDiffuseTransmittance; - /** The upward direct transmittance. */ + /** The upward direct transmittance. */ double m_UpwardDirectTransmittance; - /** The upward diffuse transmittance for rayleigh. */ + /** The upward diffuse transmittance for rayleigh. */ double m_UpwardDiffuseTransmittanceForRayleigh; - /** The upward diffuse transmittance for aerosols. */ + /** The upward diffuse transmittance for aerosols. */ double m_UpwardDiffuseTransmittanceForAerosol; }; @@ -176,12 +176,18 @@ public: * Set/Get the values. */ void SetValues( const VectorValueType & val) - { - m_Values = val; - this->Modified(); - }; - VectorValueType & GetValues() { return m_Values; }; - const VectorValueType & GetValues() const { return m_Values; }; + { + m_Values = val; + this->Modified(); + }; + VectorValueType & GetValues() + { + return m_Values; + }; + const VectorValueType & GetValues() const + { + return m_Values; + }; /** Set/Get the data classified by channel. */ /** Set methods with vectors. */ @@ -221,7 +227,7 @@ public: DataVectorType GetUpwardDiffuseTransmittancesForRayleigh(); DataVectorType GetUpwardDiffuseTransmittancesForAerosol(); - /** Get methods with index. */ + /** Get methods with index. */ double GetIntrinsicAtmosphericReflectance(unsigned int id); double GetSphericalAlbedo(unsigned int id); double GetTotalGaseousTransmission(unsigned int id); @@ -241,7 +247,7 @@ protected: /** Constructor */ AtmosphericRadiativeTerms(); /** Destructor */ - ~AtmosphericRadiativeTerms(){}; + ~AtmosphericRadiativeTerms() {}; /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; diff --git a/Code/Radiometry/otbDEMCaracteristicsExtractor.h b/Code/Radiometry/otbDEMCaracteristicsExtractor.h index e8ac2ca9be2713ff117a62b256d82f2fccf4987c..2c32f88a03d482d331c86cbe4c0d2e2664a1f55d 100644 --- a/Code/Radiometry/otbDEMCaracteristicsExtractor.h +++ b/Code/Radiometry/otbDEMCaracteristicsExtractor.h @@ -44,122 +44,122 @@ namespace otb { - /** \class DEMCaracteristicsExtractor - * \brief Calculates the slope, the orientation incidence and exitance radius values for each pixel. - * - * To note that azimuth value are projection over North-South direction and angles have to be given in degres. - * - * \ingroup DEMHanler - * \ingroup DEMToImageGenerator - */ - template <class TInputImage, class TOutputImage > - class ITK_EXPORT DEMCaracteristicsExtractor : - public itk::ImageToImageFilter<TInputImage, TOutputImage> - { - public: - /** Extract input and output images dimensions.*/ - itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); - itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); - - /** "typedef" to simplify the variables definition and the declaration. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - - /** "typedef" for standard classes. */ - typedef DEMCaracteristicsExtractor Self; - typedef itk::ImageToImageFilter< TInputImage, OutputImageType > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** object factory method. */ - itkNewMacro(Self); - - /** return class name. */ - itkTypeMacro(DEMCaracteristicsExtractor, ImageToImageFilter); - - /** Supported images definition. */ - typedef typename InputImageType::PixelType InputPixelType; - typedef typename InputImageType::InternalPixelType InputInternalPixelType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename OutputImageType::InternalPixelType OutputInternalPixelType; - typedef itk::CovariantVector< InputInternalPixelType, 2 > VectorPixelType; - typedef Image< VectorPixelType, 2 > VectorGradientImageType; - - /** Filter definition */ - typedef itk::GradientMagnitudeImageFilter<InputImageType, OutputImageType> GradientMagnitudeFilterType; - typedef itk::GradientImageFilter<InputImageType, InputInternalPixelType, InputInternalPixelType> GradientRecursiveGaussianImageFilterType; - typedef typename GradientRecursiveGaussianImageFilterType::OutputImageType tutuType; - typedef itk::NthElementImageAdaptor<tutuType, InputInternalPixelType> AdaptorType; - typedef itk::Atan2ImageFilter<AdaptorType, AdaptorType, OutputImageType> Atan2FilterType; - typedef itk::AtanImageFilter<OutputImageType, OutputImageType> AtanFilterType; - - /** Operation Filters*/ - typedef MultiplyByScalarImageFilter<OutputImageType, OutputImageType> MultiplyByScalarImageFilterType; - typedef itk::MultiplyImageFilter<OutputImageType, OutputImageType, OutputImageType> MultiplyImageFilterType; - typedef itk::AcosImageFilter<OutputImageType, OutputImageType> AcosImageFilterType; - typedef itk::CosImageFilter<OutputImageType, OutputImageType> CosImageFilterType; - typedef itk::SinImageFilter<OutputImageType, OutputImageType> SinImageFilterType; - typedef itk::ShiftScaleImageFilter<OutputImageType, OutputImageType> ShiftScaleImageFilterType; - typedef itk::AddImageFilter<OutputImageType, OutputImageType, OutputImageType> AddImageFilterType; - - /** Get the slop output image */ - OutputImageType* GetSlopOutput() +/** \class DEMCaracteristicsExtractor + * \brief Calculates the slope, the orientation incidence and exitance radius values for each pixel. + * + * To note that azimuth value are projection over North-South direction and angles have to be given in degres. + * + * \ingroup DEMHanler + * \ingroup DEMToImageGenerator + */ +template <class TInputImage, class TOutputImage > +class ITK_EXPORT DEMCaracteristicsExtractor : + public itk::ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Extract input and output images dimensions.*/ + itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** "typedef" to simplify the variables definition and the declaration. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + + /** "typedef" for standard classes. */ + typedef DEMCaracteristicsExtractor Self; + typedef itk::ImageToImageFilter< TInputImage, OutputImageType > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** object factory method. */ + itkNewMacro(Self); + + /** return class name. */ + itkTypeMacro(DEMCaracteristicsExtractor, ImageToImageFilter); + + /** Supported images definition. */ + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::InternalPixelType InputInternalPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::InternalPixelType OutputInternalPixelType; + typedef itk::CovariantVector< InputInternalPixelType, 2 > VectorPixelType; + typedef Image< VectorPixelType, 2 > VectorGradientImageType; + + /** Filter definition */ + typedef itk::GradientMagnitudeImageFilter<InputImageType, OutputImageType> GradientMagnitudeFilterType; + typedef itk::GradientImageFilter<InputImageType, InputInternalPixelType, InputInternalPixelType> GradientRecursiveGaussianImageFilterType; + typedef typename GradientRecursiveGaussianImageFilterType::OutputImageType tutuType; + typedef itk::NthElementImageAdaptor<tutuType, InputInternalPixelType> AdaptorType; + typedef itk::Atan2ImageFilter<AdaptorType, AdaptorType, OutputImageType> Atan2FilterType; + typedef itk::AtanImageFilter<OutputImageType, OutputImageType> AtanFilterType; + + /** Operation Filters*/ + typedef MultiplyByScalarImageFilter<OutputImageType, OutputImageType> MultiplyByScalarImageFilterType; + typedef itk::MultiplyImageFilter<OutputImageType, OutputImageType, OutputImageType> MultiplyImageFilterType; + typedef itk::AcosImageFilter<OutputImageType, OutputImageType> AcosImageFilterType; + typedef itk::CosImageFilter<OutputImageType, OutputImageType> CosImageFilterType; + typedef itk::SinImageFilter<OutputImageType, OutputImageType> SinImageFilterType; + typedef itk::ShiftScaleImageFilter<OutputImageType, OutputImageType> ShiftScaleImageFilterType; + typedef itk::AddImageFilter<OutputImageType, OutputImageType, OutputImageType> AddImageFilterType; + + /** Get the slop output image */ + OutputImageType* GetSlopOutput() { return static_cast<OutputImageType*>( this->itk::ProcessObject::GetOutput(0) ); }; - /** Get the aspect output image */ - OutputImageType* GetAspectOutput() + /** Get the aspect output image */ + OutputImageType* GetAspectOutput() { return static_cast<OutputImageType*>( this->itk::ProcessObject::GetOutput(1) ); }; - /** Get the incidence output image */ - OutputImageType* GetIncidenceOutput() + /** Get the incidence output image */ + OutputImageType* GetIncidenceOutput() { return static_cast<OutputImageType*>( this->itk::ProcessObject::GetOutput(2) ); }; - /** Get the exitance output image */ - OutputImageType* GetExitanceOutput() + /** Get the exitance output image */ + OutputImageType* GetExitanceOutput() { return static_cast<OutputImageType*>( this->itk::ProcessObject::GetOutput(3) ); }; - /** Angle parameters*/ - /** Set/Get Solar Angle */ - itkSetMacro(SolarAngle, double); - itkGetConstMacro(SolarAngle, double); - /** Set/Get Solar Solar */ - itkSetMacro(SolarAzimut, double); - itkGetConstMacro(SolarAzimut, double); - /** Set/Get View Angle */ - itkSetMacro(ViewAngle, double); - itkGetConstMacro(ViewAngle, double); - /** Set/Get View Solar */ - itkSetMacro(ViewAzimut, double); - itkGetConstMacro(ViewAzimut, double); - - protected: - DEMCaracteristicsExtractor(); - virtual ~DEMCaracteristicsExtractor(); - /**PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - - void GenerateData(); - - - private: - /** Angle parameters*/ - /** Solar Angle */ - double m_SolarAngle; - /** Solar Solar */ - double m_SolarAzimut; - /** View Angle */ - double m_ViewAngle; - /** View Solar */ - double m_ViewAzimut; - }; + /** Angle parameters*/ + /** Set/Get Solar Angle */ + itkSetMacro(SolarAngle, double); + itkGetConstMacro(SolarAngle, double); + /** Set/Get Solar Solar */ + itkSetMacro(SolarAzimut, double); + itkGetConstMacro(SolarAzimut, double); + /** Set/Get View Angle */ + itkSetMacro(ViewAngle, double); + itkGetConstMacro(ViewAngle, double); + /** Set/Get View Solar */ + itkSetMacro(ViewAzimut, double); + itkGetConstMacro(ViewAzimut, double); + +protected: + DEMCaracteristicsExtractor(); + virtual ~DEMCaracteristicsExtractor(); + /**PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + + void GenerateData(); + + +private: + /** Angle parameters*/ + /** Solar Angle */ + double m_SolarAngle; + /** Solar Solar */ + double m_SolarAzimut; + /** View Angle */ + double m_ViewAngle; + /** View Solar */ + double m_ViewAzimut; +}; } // end namespace otb diff --git a/Code/Radiometry/otbDEMCaracteristicsExtractor.txx b/Code/Radiometry/otbDEMCaracteristicsExtractor.txx index db2ce030e044514f0c5ecfb9412526888f98e577..1cc388ee184e902949abf31f2711301eeb1f58ca 100644 --- a/Code/Radiometry/otbDEMCaracteristicsExtractor.txx +++ b/Code/Radiometry/otbDEMCaracteristicsExtractor.txx @@ -29,199 +29,199 @@ namespace otb { - template <class TInputImage, class TOutputImage> - DEMCaracteristicsExtractor<TInputImage, TOutputImage> - ::DEMCaracteristicsExtractor() - { - this->SetNumberOfInputs(1); - this->SetNumberOfOutputs(3); - - this->SetNthOutput(0,OutputImageType::New()); - this->SetNthOutput(1,OutputImageType::New()); - this->SetNthOutput(2,OutputImageType::New()); - this->SetNthOutput(3,OutputImageType::New()); - - m_SolarAngle = 0; - m_SolarAzimut = 0; - m_ViewAngle = 0; - m_ViewAzimut = 0; - } - - - template <class TInputImage, class TOutputImage> - DEMCaracteristicsExtractor<TInputImage, TOutputImage> - ::~DEMCaracteristicsExtractor() - { - } - - - /** - * ThreadedGenerateData Performs the pixel-wise addition - */ - template <class TInputImage, class TOutputImage> - void - DEMCaracteristicsExtractor<TInputImage,TOutputImage> - ::GenerateData() - { - // Input and output pointer definition - typename InputImageType::Pointer inputPtr = const_cast<InputImageType *>(this->GetInput()); - typename OutputImageType::Pointer SlopOutputPtr = this->GetSlopOutput(); - typename OutputImageType::Pointer AspectOutputPtr = this->GetAspectOutput(); - typename OutputImageType::Pointer IncidenceOutputPtr = this->GetIncidenceOutput(); - typename OutputImageType::Pointer ExitanceOutputPtr = this->GetExitanceOutput(); - - // Gradient Magnitude Image Filter used to compute the slope. - typename GradientMagnitudeFilterType::Pointer GradientMagnitudeFilter = GradientMagnitudeFilterType::New(); - // Gradient Recursive Gaussian Image Filter used to compute the aspect. - typename GradientRecursiveGaussianImageFilterType::Pointer GradientRecursiveGaussianFilter= GradientRecursiveGaussianImageFilterType::New(); - // Atan used to compute the slop - typename AtanFilterType::Pointer AtanFilter = AtanFilterType::New(); - // Atan2 Image Filter used to compute the aspect. - typename Atan2FilterType::Pointer AspectFilter = Atan2FilterType::New(); - // Inverse cosinus Image filter used to compute the incidence image - typename AcosImageFilterType::Pointer IncidenceFilter = AcosImageFilterType::New(); - // Inverse cosinus Image filter used to compute the exitance image - typename AcosImageFilterType::Pointer ExitanceFilter = AcosImageFilterType::New(); - - // Degrees To Radian _-> Radian To Degree coefficient - double rad2degCoef; - rad2degCoef = 180/M_PI; - - // Slop calculation - GradientMagnitudeFilter->SetInput(inputPtr); - AtanFilter->SetInput( GradientMagnitudeFilter->GetOutput() ); - // Transform values from radian to degrees. - typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter = MultiplyByScalarImageFilterType::New(); - //rad2DegFilter->SetInput( GradientMagnitudeFilter->GetOutput() ); - rad2DegFilter->SetInput( AtanFilter->GetOutput() ); - rad2DegFilter->SetCoef( rad2degCoef ); - rad2DegFilter->GraftOutput( SlopOutputPtr ); - rad2DegFilter->Update(); - this->GraftNthOutput( 0, rad2DegFilter->GetOutput() ); - - // Aspect calcultation - GradientRecursiveGaussianFilter->SetInput(inputPtr); - GradientRecursiveGaussianFilter->Update(); - - // // Extract the X and the Y gradient - typename AdaptorType::Pointer XAdaptator = AdaptorType::New(); - typename AdaptorType::Pointer YAdaptator = AdaptorType::New(); - XAdaptator->SetImage(GradientRecursiveGaussianFilter->GetOutput()); - YAdaptator->SetImage(GradientRecursiveGaussianFilter->GetOutput()); - XAdaptator->SelectNthElement(0); - YAdaptator->SelectNthElement(1); - // // Compute Arctan - AspectFilter->SetInput1(XAdaptator); - AspectFilter->SetInput2(YAdaptator); - // // Transform values from radian to degres. - typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter1 = MultiplyByScalarImageFilterType::New(); - rad2DegFilter1->SetInput( AspectFilter->GetOutput() ); - rad2DegFilter1->SetCoef( rad2degCoef ); - rad2DegFilter1->GraftOutput( AspectOutputPtr ); - rad2DegFilter1->Update(); - this->GraftNthOutput( 1, rad2DegFilter1->GetOutput() ); - - - // Angle calculation : - // sin(slop) - typename SinImageFilterType::Pointer sinS = SinImageFilterType::New(); - sinS->SetInput( GradientMagnitudeFilter->GetOutput() ); - // cos (slop) - typename CosImageFilterType::Pointer cosS = CosImageFilterType::New(); - cosS->SetInput( GradientMagnitudeFilter->GetOutput() ); - // -aspect - typename MultiplyByScalarImageFilterType::Pointer oppositeFilter = MultiplyByScalarImageFilterType::New(); - oppositeFilter->SetInput( AspectFilter->GetOutput() ); - oppositeFilter->SetCoef( -1 ); - - // Incidence calculation - typename ShiftScaleImageFilterType::Pointer addAzimut = ShiftScaleImageFilterType::New(); - addAzimut->SetScale(1.); - addAzimut->SetShift( m_SolarAzimut/rad2degCoef ); - addAzimut->SetInput( oppositeFilter->GetOutput() ); - - typename CosImageFilterType::Pointer cosAAzimut = CosImageFilterType::New(); - cosAAzimut->SetInput( addAzimut->GetOutput() ); - - typename MultiplyByScalarImageFilterType::Pointer sinSsinSolarAngleFilter = MultiplyByScalarImageFilterType::New(); - sinSsinSolarAngleFilter->SetCoef( vcl_sin(m_SolarAngle/rad2degCoef )); - sinSsinSolarAngleFilter->SetInput( sinS->GetOutput() ); - - typename MultiplyImageFilterType::Pointer cosAAzimuthsinSsinAngle = MultiplyImageFilterType::New(); - cosAAzimuthsinSsinAngle->SetInput1( sinSsinSolarAngleFilter->GetOutput() ); - cosAAzimuthsinSsinAngle->SetInput2( cosAAzimut->GetOutput() ); - - typename MultiplyByScalarImageFilterType::Pointer cosScosSolarAngleFilter = MultiplyByScalarImageFilterType::New(); - cosScosSolarAngleFilter->SetCoef( vcl_cos(m_SolarAngle/rad2degCoef) ); - cosScosSolarAngleFilter->SetInput( cosS->GetOutput() ); - - typename AddImageFilterType::Pointer cosIncidence = AddImageFilterType::New(); - cosIncidence->SetInput1( cosAAzimuthsinSsinAngle->GetOutput() ); - cosIncidence->SetInput2( cosScosSolarAngleFilter->GetOutput() ); - - IncidenceFilter->SetInput( cosIncidence->GetOutput() ); - - // // Change radians in degres - typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter2 = MultiplyByScalarImageFilterType::New(); - rad2DegFilter2->SetInput( IncidenceFilter->GetOutput() ); - rad2DegFilter2->SetCoef( rad2degCoef ); - // // Link to the output - rad2DegFilter2->GraftOutput( IncidenceOutputPtr ); - rad2DegFilter2->Update(); - this->GraftNthOutput( 2, rad2DegFilter2->GetOutput() ); - - - // Exitance calculation - typename ShiftScaleImageFilterType::Pointer addAzimut2 = ShiftScaleImageFilterType::New(); - addAzimut2->SetScale(1.); - addAzimut2->SetShift( m_ViewAzimut/rad2degCoef ); - addAzimut2->SetInput( oppositeFilter->GetOutput() ); - - typename CosImageFilterType::Pointer cosAAzimut2 = CosImageFilterType::New(); - cosAAzimut2->SetInput( addAzimut2->GetOutput() ); - - typename MultiplyByScalarImageFilterType::Pointer sinSsinSolarAngleFilter2 = MultiplyByScalarImageFilterType::New(); - sinSsinSolarAngleFilter2->SetCoef( vcl_sin(m_ViewAngle/rad2degCoef) ); - sinSsinSolarAngleFilter2->SetInput( sinS->GetOutput() ); - - typename MultiplyImageFilterType::Pointer cosAAzimuthsinSsinAngle2 = MultiplyImageFilterType::New(); - cosAAzimuthsinSsinAngle2->SetInput1( sinSsinSolarAngleFilter2->GetOutput() ); - cosAAzimuthsinSsinAngle2->SetInput2( cosAAzimut2->GetOutput() ); - - - typename MultiplyByScalarImageFilterType::Pointer cosScosSolarAngleFilter2 = MultiplyByScalarImageFilterType::New(); - cosScosSolarAngleFilter2->SetCoef( vcl_cos(m_ViewAngle/rad2degCoef) ); - cosScosSolarAngleFilter2->SetInput( cosS->GetOutput() ); - - typename AddImageFilterType::Pointer cosIncidence2 = AddImageFilterType::New(); - cosIncidence2->SetInput1( cosAAzimuthsinSsinAngle2->GetOutput() ); - cosIncidence2->SetInput2( cosScosSolarAngleFilter2->GetOutput() ); - - ExitanceFilter->SetInput( cosIncidence2->GetOutput() ); - - // // Change radians in degres - typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter3 = MultiplyByScalarImageFilterType::New(); - rad2DegFilter3->SetInput( ExitanceFilter->GetOutput() ); - rad2DegFilter3->SetCoef( rad2degCoef ); - // // Link to the output - rad2DegFilter3->GraftOutput( ExitanceOutputPtr ); - rad2DegFilter3->Update(); - this->GraftNthOutput( 3, rad2DegFilter3->GetOutput() ); - - } - - /**PrintSelf method */ - template <class TInputImage, class TOutputImage> - void - DEMCaracteristicsExtractor<TInputImage,TOutputImage> - ::PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os << indent << "Solar Angle: " << m_SolarAngle << std::endl; - os << indent << "Solar Azimut: " << m_SolarAzimut << std::endl; - os << indent << "View Angle: " << m_ViewAngle << std::endl; - os << indent << "View Azimut: " << m_ViewAzimut << std::endl; - } +template <class TInputImage, class TOutputImage> +DEMCaracteristicsExtractor<TInputImage, TOutputImage> +::DEMCaracteristicsExtractor() +{ + this->SetNumberOfInputs(1); + this->SetNumberOfOutputs(3); + + this->SetNthOutput(0,OutputImageType::New()); + this->SetNthOutput(1,OutputImageType::New()); + this->SetNthOutput(2,OutputImageType::New()); + this->SetNthOutput(3,OutputImageType::New()); + + m_SolarAngle = 0; + m_SolarAzimut = 0; + m_ViewAngle = 0; + m_ViewAzimut = 0; +} + + +template <class TInputImage, class TOutputImage> +DEMCaracteristicsExtractor<TInputImage, TOutputImage> +::~DEMCaracteristicsExtractor() +{ +} + + +/** + * ThreadedGenerateData Performs the pixel-wise addition + */ +template <class TInputImage, class TOutputImage> +void +DEMCaracteristicsExtractor<TInputImage,TOutputImage> +::GenerateData() +{ + // Input and output pointer definition + typename InputImageType::Pointer inputPtr = const_cast<InputImageType *>(this->GetInput()); + typename OutputImageType::Pointer SlopOutputPtr = this->GetSlopOutput(); + typename OutputImageType::Pointer AspectOutputPtr = this->GetAspectOutput(); + typename OutputImageType::Pointer IncidenceOutputPtr = this->GetIncidenceOutput(); + typename OutputImageType::Pointer ExitanceOutputPtr = this->GetExitanceOutput(); + + // Gradient Magnitude Image Filter used to compute the slope. + typename GradientMagnitudeFilterType::Pointer GradientMagnitudeFilter = GradientMagnitudeFilterType::New(); + // Gradient Recursive Gaussian Image Filter used to compute the aspect. + typename GradientRecursiveGaussianImageFilterType::Pointer GradientRecursiveGaussianFilter= GradientRecursiveGaussianImageFilterType::New(); + // Atan used to compute the slop + typename AtanFilterType::Pointer AtanFilter = AtanFilterType::New(); + // Atan2 Image Filter used to compute the aspect. + typename Atan2FilterType::Pointer AspectFilter = Atan2FilterType::New(); + // Inverse cosinus Image filter used to compute the incidence image + typename AcosImageFilterType::Pointer IncidenceFilter = AcosImageFilterType::New(); + // Inverse cosinus Image filter used to compute the exitance image + typename AcosImageFilterType::Pointer ExitanceFilter = AcosImageFilterType::New(); + + // Degrees To Radian _-> Radian To Degree coefficient + double rad2degCoef; + rad2degCoef = 180/M_PI; + + // Slop calculation + GradientMagnitudeFilter->SetInput(inputPtr); + AtanFilter->SetInput( GradientMagnitudeFilter->GetOutput() ); + // Transform values from radian to degrees. + typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter = MultiplyByScalarImageFilterType::New(); + //rad2DegFilter->SetInput( GradientMagnitudeFilter->GetOutput() ); + rad2DegFilter->SetInput( AtanFilter->GetOutput() ); + rad2DegFilter->SetCoef( rad2degCoef ); + rad2DegFilter->GraftOutput( SlopOutputPtr ); + rad2DegFilter->Update(); + this->GraftNthOutput( 0, rad2DegFilter->GetOutput() ); + + // Aspect calcultation + GradientRecursiveGaussianFilter->SetInput(inputPtr); + GradientRecursiveGaussianFilter->Update(); + + // // Extract the X and the Y gradient + typename AdaptorType::Pointer XAdaptator = AdaptorType::New(); + typename AdaptorType::Pointer YAdaptator = AdaptorType::New(); + XAdaptator->SetImage(GradientRecursiveGaussianFilter->GetOutput()); + YAdaptator->SetImage(GradientRecursiveGaussianFilter->GetOutput()); + XAdaptator->SelectNthElement(0); + YAdaptator->SelectNthElement(1); + // // Compute Arctan + AspectFilter->SetInput1(XAdaptator); + AspectFilter->SetInput2(YAdaptator); + // // Transform values from radian to degres. + typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter1 = MultiplyByScalarImageFilterType::New(); + rad2DegFilter1->SetInput( AspectFilter->GetOutput() ); + rad2DegFilter1->SetCoef( rad2degCoef ); + rad2DegFilter1->GraftOutput( AspectOutputPtr ); + rad2DegFilter1->Update(); + this->GraftNthOutput( 1, rad2DegFilter1->GetOutput() ); + + + // Angle calculation : + // sin(slop) + typename SinImageFilterType::Pointer sinS = SinImageFilterType::New(); + sinS->SetInput( GradientMagnitudeFilter->GetOutput() ); + // cos (slop) + typename CosImageFilterType::Pointer cosS = CosImageFilterType::New(); + cosS->SetInput( GradientMagnitudeFilter->GetOutput() ); + // -aspect + typename MultiplyByScalarImageFilterType::Pointer oppositeFilter = MultiplyByScalarImageFilterType::New(); + oppositeFilter->SetInput( AspectFilter->GetOutput() ); + oppositeFilter->SetCoef( -1 ); + + // Incidence calculation + typename ShiftScaleImageFilterType::Pointer addAzimut = ShiftScaleImageFilterType::New(); + addAzimut->SetScale(1.); + addAzimut->SetShift( m_SolarAzimut/rad2degCoef ); + addAzimut->SetInput( oppositeFilter->GetOutput() ); + + typename CosImageFilterType::Pointer cosAAzimut = CosImageFilterType::New(); + cosAAzimut->SetInput( addAzimut->GetOutput() ); + + typename MultiplyByScalarImageFilterType::Pointer sinSsinSolarAngleFilter = MultiplyByScalarImageFilterType::New(); + sinSsinSolarAngleFilter->SetCoef( vcl_sin(m_SolarAngle/rad2degCoef )); + sinSsinSolarAngleFilter->SetInput( sinS->GetOutput() ); + + typename MultiplyImageFilterType::Pointer cosAAzimuthsinSsinAngle = MultiplyImageFilterType::New(); + cosAAzimuthsinSsinAngle->SetInput1( sinSsinSolarAngleFilter->GetOutput() ); + cosAAzimuthsinSsinAngle->SetInput2( cosAAzimut->GetOutput() ); + + typename MultiplyByScalarImageFilterType::Pointer cosScosSolarAngleFilter = MultiplyByScalarImageFilterType::New(); + cosScosSolarAngleFilter->SetCoef( vcl_cos(m_SolarAngle/rad2degCoef) ); + cosScosSolarAngleFilter->SetInput( cosS->GetOutput() ); + + typename AddImageFilterType::Pointer cosIncidence = AddImageFilterType::New(); + cosIncidence->SetInput1( cosAAzimuthsinSsinAngle->GetOutput() ); + cosIncidence->SetInput2( cosScosSolarAngleFilter->GetOutput() ); + + IncidenceFilter->SetInput( cosIncidence->GetOutput() ); + + // // Change radians in degres + typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter2 = MultiplyByScalarImageFilterType::New(); + rad2DegFilter2->SetInput( IncidenceFilter->GetOutput() ); + rad2DegFilter2->SetCoef( rad2degCoef ); + // // Link to the output + rad2DegFilter2->GraftOutput( IncidenceOutputPtr ); + rad2DegFilter2->Update(); + this->GraftNthOutput( 2, rad2DegFilter2->GetOutput() ); + + + // Exitance calculation + typename ShiftScaleImageFilterType::Pointer addAzimut2 = ShiftScaleImageFilterType::New(); + addAzimut2->SetScale(1.); + addAzimut2->SetShift( m_ViewAzimut/rad2degCoef ); + addAzimut2->SetInput( oppositeFilter->GetOutput() ); + + typename CosImageFilterType::Pointer cosAAzimut2 = CosImageFilterType::New(); + cosAAzimut2->SetInput( addAzimut2->GetOutput() ); + + typename MultiplyByScalarImageFilterType::Pointer sinSsinSolarAngleFilter2 = MultiplyByScalarImageFilterType::New(); + sinSsinSolarAngleFilter2->SetCoef( vcl_sin(m_ViewAngle/rad2degCoef) ); + sinSsinSolarAngleFilter2->SetInput( sinS->GetOutput() ); + + typename MultiplyImageFilterType::Pointer cosAAzimuthsinSsinAngle2 = MultiplyImageFilterType::New(); + cosAAzimuthsinSsinAngle2->SetInput1( sinSsinSolarAngleFilter2->GetOutput() ); + cosAAzimuthsinSsinAngle2->SetInput2( cosAAzimut2->GetOutput() ); + + + typename MultiplyByScalarImageFilterType::Pointer cosScosSolarAngleFilter2 = MultiplyByScalarImageFilterType::New(); + cosScosSolarAngleFilter2->SetCoef( vcl_cos(m_ViewAngle/rad2degCoef) ); + cosScosSolarAngleFilter2->SetInput( cosS->GetOutput() ); + + typename AddImageFilterType::Pointer cosIncidence2 = AddImageFilterType::New(); + cosIncidence2->SetInput1( cosAAzimuthsinSsinAngle2->GetOutput() ); + cosIncidence2->SetInput2( cosScosSolarAngleFilter2->GetOutput() ); + + ExitanceFilter->SetInput( cosIncidence2->GetOutput() ); + + // // Change radians in degres + typename MultiplyByScalarImageFilterType::Pointer rad2DegFilter3 = MultiplyByScalarImageFilterType::New(); + rad2DegFilter3->SetInput( ExitanceFilter->GetOutput() ); + rad2DegFilter3->SetCoef( rad2degCoef ); + // // Link to the output + rad2DegFilter3->GraftOutput( ExitanceOutputPtr ); + rad2DegFilter3->Update(); + this->GraftNthOutput( 3, rad2DegFilter3->GetOutput() ); + +} + +/**PrintSelf method */ +template <class TInputImage, class TOutputImage> +void +DEMCaracteristicsExtractor<TInputImage,TOutputImage> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Solar Angle: " << m_SolarAngle << std::endl; + os << indent << "Solar Azimut: " << m_SolarAzimut << std::endl; + os << indent << "View Angle: " << m_ViewAngle << std::endl; + os << indent << "View Azimut: " << m_ViewAzimut << std::endl; +} } // end namespace otb diff --git a/Code/Radiometry/otbImageToLuminanceImageFilter.h b/Code/Radiometry/otbImageToLuminanceImageFilter.h index c801a44f1ee33e776f5c5936409f5ac3de1e40ba..4a637ea9058d2ab3036a8ad16c23225938a7cf16 100644 --- a/Code/Radiometry/otbImageToLuminanceImageFilter.h +++ b/Code/Radiometry/otbImageToLuminanceImageFilter.h @@ -32,57 +32,69 @@ namespace otb { - namespace Functor - { - /** Functor::ImageToLuminanceImageFunctor - * Add beta to the quotient Input over alpha. - * - * \ingroup Functor - */ - - template <class TInput, class TOutput> - class ImageToLuminanceImageFunctor +namespace Functor +{ +/** Functor::ImageToLuminanceImageFunctor + * Add beta to the quotient Input over alpha. + * + * \ingroup Functor + */ + +template <class TInput, class TOutput> +class ImageToLuminanceImageFunctor +{ +public: + ImageToLuminanceImageFunctor() { - public: - ImageToLuminanceImageFunctor() - { - m_Alpha = 1.; - m_Beta = 0.; - }; - ~ImageToLuminanceImageFunctor() {}; - - void SetAlpha(double alpha){ m_Alpha = alpha;}; - void SetBeta(double beta){ m_Beta = beta;}; - double GetAlpha(){ return m_Alpha;}; - double GetBeta(){ return m_Beta;}; - - - inline TOutput operator() (const TInput & inPixel) - { - TOutput outPixel; - double temp; - temp = static_cast<double>(inPixel)/m_Alpha + m_Beta; - outPixel = static_cast<TOutput>(temp); - return outPixel; - } - - private: - double m_Alpha; - double m_Beta; + m_Alpha = 1.; + m_Beta = 0.; }; - } + ~ImageToLuminanceImageFunctor() {}; - /** \class ImageToLuminanceImageFilter - * \brief Transform a classical image into the luminance image. For this it uses the functor ImageToLuminanceImageFunctor calling for each component of each pixel. - * - * \ingroup ImageToLuminanceImageFunctor - */ + void SetAlpha(double alpha) + { + m_Alpha = alpha; + }; + void SetBeta(double beta) + { + m_Beta = beta; + }; + double GetAlpha() + { + return m_Alpha; + }; + double GetBeta() + { + return m_Beta; + }; + + + inline TOutput operator() (const TInput & inPixel) + { + TOutput outPixel; + double temp; + temp = static_cast<double>(inPixel)/m_Alpha + m_Beta; + outPixel = static_cast<TOutput>(temp); + return outPixel; + } + +private: + double m_Alpha; + double m_Beta; +}; +} + +/** \class ImageToLuminanceImageFilter + * \brief Transform a classical image into the luminance image. For this it uses the functor ImageToLuminanceImageFunctor calling for each component of each pixel. + * + * \ingroup ImageToLuminanceImageFunctor + */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageToLuminanceImageFilter : -public UnaryImageFunctorWithVectorImageFilter< TInputImage, - TOutputImage, - ITK_TYPENAME Functor::ImageToLuminanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, - ITK_TYPENAME TOutputImage::InternalPixelType > > + public UnaryImageFunctorWithVectorImageFilter< TInputImage, + TOutputImage, + ITK_TYPENAME Functor::ImageToLuminanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, + ITK_TYPENAME TOutputImage::InternalPixelType > > { public: /** Extract input and output images dimensions.*/ @@ -93,7 +105,7 @@ public: typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; typedef typename Functor::ImageToLuminanceImageFunctor<ITK_TYPENAME InputImageType::InternalPixelType, - ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; + ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; /** "typedef" for standard classes. */ @@ -122,7 +134,7 @@ public: /** Image size "typedef" definition. */ typedef typename InputImageType::SizeType SizeType; - /** Set the absolute calibration gains. */ + /** Set the absolute calibration gains. */ itkSetMacro(Alpha, VectorType); /** Give the absolute calibration gains. */ itkGetConstReferenceMacro(Alpha, VectorType); @@ -133,7 +145,7 @@ public: itkGetConstReferenceMacro(Beta, VectorType); - protected: +protected: ImageToLuminanceImageFilter() { @@ -142,19 +154,19 @@ public: m_Alpha.Fill(1); m_Beta.Fill(0); }; - virtual ~ImageToLuminanceImageFilter(){}; + virtual ~ImageToLuminanceImageFilter() {}; virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctorVector().clear(); - for(unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) { - FunctorType functor; - functor.SetAlpha(m_Alpha[i]); - functor.SetBeta(m_Beta[i]); - this->GetFunctorVector().push_back(functor); - } + this->GetFunctorVector().clear(); + for (unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) + { + FunctorType functor; + functor.SetAlpha(m_Alpha[i]); + functor.SetBeta(m_Beta[i]); + this->GetFunctorVector().push_back(functor); } + } private: diff --git a/Code/Radiometry/otbImageToReflectanceImageFilter.h b/Code/Radiometry/otbImageToReflectanceImageFilter.h index 058faff7bee456988a96e34e706ac2ed2b3242ff..0e02f1ee4033644dc3c8eb4367658f56cb699dde 100644 --- a/Code/Radiometry/otbImageToReflectanceImageFilter.h +++ b/Code/Radiometry/otbImageToReflectanceImageFilter.h @@ -32,52 +32,76 @@ namespace otb { - namespace Functor - { - /** Functor::ImageToReflectanceImageFunctor - * Call the ImageToLuminanceFunctor over the input and the LuminanceToReflectanceFunctor to this result. - * - * \ingroup Functor - * \ingroup ImageToLuminanceFunctor - * \ingroup LuminanceToReflectanceFunctor - */ - template <class TInput, class TOutput> - class ImageToReflectanceImageFunctor - { - public: - ImageToReflectanceImageFunctor() {}; - ~ImageToReflectanceImageFunctor() {}; +namespace Functor +{ +/** Functor::ImageToReflectanceImageFunctor + * Call the ImageToLuminanceFunctor over the input and the LuminanceToReflectanceFunctor to this result. + * + * \ingroup Functor + * \ingroup ImageToLuminanceFunctor + * \ingroup LuminanceToReflectanceFunctor + */ +template <class TInput, class TOutput> +class ImageToReflectanceImageFunctor +{ +public: + ImageToReflectanceImageFunctor() {}; + ~ImageToReflectanceImageFunctor() {}; - typedef Functor::ImageToLuminanceImageFunctor<TInput, TOutput> ImToLumFunctorType; - typedef Functor::LuminanceToReflectanceImageFunctor<TInput, TOutput> LumToReflecFunctorType; + typedef Functor::ImageToLuminanceImageFunctor<TInput, TOutput> ImToLumFunctorType; + typedef Functor::LuminanceToReflectanceImageFunctor<TInput, TOutput> LumToReflecFunctorType; - void SetAlpha(double alpha){ m_ImToLumFunctor.SetAlpha(alpha); }; - void SetBeta(double beta){ m_ImToLumFunctor.SetBeta(beta); }; - void SetSolarIllumination(double solarIllumination){ m_LumToReflecFunctor.SetSolarIllumination(solarIllumination); }; - void SetIlluminationCorrectionCoefficient(double coef){ m_LumToReflecFunctor.SetIlluminationCorrectionCoefficient(coef); }; + void SetAlpha(double alpha) + { + m_ImToLumFunctor.SetAlpha(alpha); + }; + void SetBeta(double beta) + { + m_ImToLumFunctor.SetBeta(beta); + }; + void SetSolarIllumination(double solarIllumination) + { + m_LumToReflecFunctor.SetSolarIllumination(solarIllumination); + }; + void SetIlluminationCorrectionCoefficient(double coef) + { + m_LumToReflecFunctor.SetIlluminationCorrectionCoefficient(coef); + }; - double GetAlpha(){ return m_ImToLumFunctor.GetAlpha();}; - double GetBeta(){ return m_ImToLumFunctor.GetBeta();}; - double GetSolarIllumination(){ return m_LumToReflecFunctor.GetSolarIllumination();}; - double GetIlluminationCorrectionCoefficient(){ return m_LumToReflecFunctor.GetIlluminationCorrectionCoefficient();}; + double GetAlpha() + { + return m_ImToLumFunctor.GetAlpha(); + }; + double GetBeta() + { + return m_ImToLumFunctor.GetBeta(); + }; + double GetSolarIllumination() + { + return m_LumToReflecFunctor.GetSolarIllumination(); + }; + double GetIlluminationCorrectionCoefficient() + { + return m_LumToReflecFunctor.GetIlluminationCorrectionCoefficient(); + }; - inline TOutput operator() (const TInput & inPixel) - { - TOutput outPixel; - TOutput tempPix; - tempPix = m_ImToLumFunctor(inPixel); - outPixel = m_LumToReflecFunctor(tempPix); + inline TOutput operator() (const TInput & inPixel) + { + TOutput outPixel; + TOutput tempPix; + tempPix = m_ImToLumFunctor(inPixel); + outPixel = m_LumToReflecFunctor(tempPix); - return outPixel; - } + return outPixel; + } - private: - ImToLumFunctorType m_ImToLumFunctor; - LumToReflecFunctorType m_LumToReflecFunctor; +private: + ImToLumFunctorType m_ImToLumFunctor; + LumToReflecFunctorType m_LumToReflecFunctor; - }; - } +}; +} /** \class ImageToReflectanceImageFilter * \brief Transform a classical image into the reflectance image. For this it uses the functor ImageToReflectanceFunctor calling for each component of each pixel. @@ -93,13 +117,13 @@ namespace otb */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ImageToReflectanceImageFilter : -public UnaryImageFunctorWithVectorImageFilter< TInputImage, - TOutputImage, - ITK_TYPENAME Functor::ImageToReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, - ITK_TYPENAME TOutputImage::InternalPixelType > > + public UnaryImageFunctorWithVectorImageFilter< TInputImage, + TOutputImage, + ITK_TYPENAME Functor::ImageToReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, + ITK_TYPENAME TOutputImage::InternalPixelType > > { public: -/** Extract input and output images dimensions.*/ + /** Extract input and output images dimensions.*/ itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); @@ -107,7 +131,7 @@ public: typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; typedef typename Functor::ImageToReflectanceImageFunctor<ITK_TYPENAME InputImageType::InternalPixelType, - ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; + ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; /** "typedef" for standard classes. */ @@ -136,7 +160,7 @@ public: /** Image size "typedef" definition. */ typedef typename InputImageType::SizeType SizeType; - /** Set the absolute calibration gains. */ + /** Set the absolute calibration gains. */ itkSetMacro(Alpha, VectorType); /** Give the absolute calibration gains. */ itkGetConstReferenceMacro(Alpha, VectorType); @@ -145,7 +169,7 @@ public: itkSetMacro(Beta, VectorType); /** Give the absolute calibration bias. */ itkGetConstReferenceMacro(Beta, VectorType); - /** Set the solar illumination value. */ + /** Set the solar illumination value. */ itkSetMacro(SolarIllumination, VectorType); /** Give the solar illumination value. */ @@ -158,73 +182,73 @@ public: /** Set the flux normalization coefficient. */ void SetFluxNormalizationCoefficient(double coef) - { - m_FluxNormalizationCoefficient = coef; - m_IsSetFluxNormalizationCoefficient = true; - this->Modified(); - }; - - /** Set the acquisition day. */ - itkSetClampMacro(Day, int, 1, 31); - /** Get the acquisition day. */ - itkGetConstReferenceMacro(Day, int); - /** Set the acquisition mounth. */ - itkSetClampMacro(Month, int, 1, 12); - /** Set the acquisition mounth. */ - itkGetConstReferenceMacro(Month, int); - - - protected: + { + m_FluxNormalizationCoefficient = coef; + m_IsSetFluxNormalizationCoefficient = true; + this->Modified(); + }; + + /** Set the acquisition day. */ + itkSetClampMacro(Day, int, 1, 31); + /** Get the acquisition day. */ + itkGetConstReferenceMacro(Day, int); + /** Set the acquisition mounth. */ + itkSetClampMacro(Month, int, 1, 12); + /** Set the acquisition mounth. */ + itkGetConstReferenceMacro(Month, int); + + +protected: ImageToReflectanceImageFilter() - { - m_Alpha.SetSize(1); - m_Alpha.Fill(0); - m_Beta.SetSize(1); - m_Beta.Fill(0); - m_ZenithalSolarAngle = 1.; - m_FluxNormalizationCoefficient = 1.; - m_SolarIllumination.Fill(1.); - m_IsSetFluxNormalizationCoefficient = false; - m_Day = 1; - m_Month = 1; - - }; - virtual ~ImageToReflectanceImageFilter(){}; + { + m_Alpha.SetSize(1); + m_Alpha.Fill(0); + m_Beta.SetSize(1); + m_Beta.Fill(0); + m_ZenithalSolarAngle = 1.; + m_FluxNormalizationCoefficient = 1.; + m_SolarIllumination.Fill(1.); + m_IsSetFluxNormalizationCoefficient = false; + m_Day = 1; + m_Month = 1; + + }; + virtual ~ImageToReflectanceImageFilter() {}; virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctorVector().clear(); - for(unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) { - FunctorType functor; - double coefTemp = 0.; - if (!m_IsSetFluxNormalizationCoefficient) + this->GetFunctorVector().clear(); + for (unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) + { + FunctorType functor; + double coefTemp = 0.; + if (!m_IsSetFluxNormalizationCoefficient) { if (m_Day*m_Month != 0 && m_Day<32 && m_Month<13) - { - otb_6s_doublereal dsol = 0.; - otb_6s_integer day = static_cast<otb_6s_integer>(m_Day); - otb_6s_integer mounth = static_cast<otb_6s_integer>(m_Month); - int cr(0); - cr = otb_6s_varsol_(&day, &mounth, &dsol); - coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*static_cast<double>(dsol); - } + { + otb_6s_doublereal dsol = 0.; + otb_6s_integer day = static_cast<otb_6s_integer>(m_Day); + otb_6s_integer mounth = static_cast<otb_6s_integer>(m_Month); + int cr(0); + cr = otb_6s_varsol_(&day, &mounth, &dsol); + coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*static_cast<double>(dsol); + } else - { - itkExceptionMacro( << "Day has to be included between 1 and 31, Month beetween 1 and 12."); - } + { + itkExceptionMacro( << "Day has to be included between 1 and 31, Month beetween 1 and 12."); + } } - else + else { coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*m_FluxNormalizationCoefficient*m_FluxNormalizationCoefficient; } - functor.SetIlluminationCorrectionCoefficient(1. / coefTemp); - functor.SetAlpha(m_Alpha[i]); - functor.SetBeta(m_Beta[i]); - functor.SetSolarIllumination(m_SolarIllumination[i]); - this->GetFunctorVector().push_back(functor); - } + functor.SetIlluminationCorrectionCoefficient(1. / coefTemp); + functor.SetAlpha(m_Alpha[i]); + functor.SetBeta(m_Beta[i]); + functor.SetSolarIllumination(m_SolarIllumination[i]); + this->GetFunctorVector().push_back(functor); } + } private: diff --git a/Code/Radiometry/otbLuminanceToReflectanceImageFilter.h b/Code/Radiometry/otbLuminanceToReflectanceImageFilter.h index 9b19ee44f9143eecb747d180ab8a3d4def1486ae..9fb5cd43586901140bd8ba286719e460942bfb46 100644 --- a/Code/Radiometry/otbLuminanceToReflectanceImageFilter.h +++ b/Code/Radiometry/otbLuminanceToReflectanceImageFilter.h @@ -32,63 +32,75 @@ namespace otb { - namespace Functor - { - /** Functor::LuminanceToReflectanceImageFunctor - * Multiply by Pi and by an illumination correction coefficient the quotient between the input and the given solar illumination. - * - * \ingroup Functor - */ - template <class TInput, class TOutput> - class LuminanceToReflectanceImageFunctor +namespace Functor +{ +/** Functor::LuminanceToReflectanceImageFunctor + * Multiply by Pi and by an illumination correction coefficient the quotient between the input and the given solar illumination. + * + * \ingroup Functor + */ +template <class TInput, class TOutput> +class LuminanceToReflectanceImageFunctor +{ +public: + LuminanceToReflectanceImageFunctor() { - public: - LuminanceToReflectanceImageFunctor() - { - m_SolarIllumination = 1.; - m_IlluminationCorrectionCoefficient = 1.; - }; - ~LuminanceToReflectanceImageFunctor() {}; - - void SetSolarIllumination(double solarIllumination){ m_SolarIllumination = solarIllumination;}; - void SetIlluminationCorrectionCoefficient(double coef){ m_IlluminationCorrectionCoefficient = coef;}; - - double GetSolarIllumination(){ return m_SolarIllumination;}; - double GetIlluminationCorrectionCoefficient(){ return m_IlluminationCorrectionCoefficient;}; + m_SolarIllumination = 1.; + m_IlluminationCorrectionCoefficient = 1.; + }; + ~LuminanceToReflectanceImageFunctor() {}; - inline TOutput operator() (const TInput & inPixel) - { - TOutput outPixel; - double temp; - temp = static_cast<double>(inPixel) - * static_cast<double>(M_PI) - * m_IlluminationCorrectionCoefficient - / m_SolarIllumination; - outPixel = static_cast<TOutput>(temp); - return outPixel; - } + void SetSolarIllumination(double solarIllumination) + { + m_SolarIllumination = solarIllumination; + }; + void SetIlluminationCorrectionCoefficient(double coef) + { + m_IlluminationCorrectionCoefficient = coef; + }; - private: - double m_SolarIllumination; - double m_IlluminationCorrectionCoefficient; + double GetSolarIllumination() + { + return m_SolarIllumination; + }; + double GetIlluminationCorrectionCoefficient() + { + return m_IlluminationCorrectionCoefficient; }; - } - /** \class LuminanceToReflectanceImageFilter - * \brief Transform a luminance image into the reflectance. For this it uses the functor LuminanceToReflectanceImageFunctor - * calling for each component of each pixel. - * - * \ingroup ImageToLuminanceImageFunctor - */ + inline TOutput operator() (const TInput & inPixel) + { + TOutput outPixel; + double temp; + temp = static_cast<double>(inPixel) + * static_cast<double>(M_PI) + * m_IlluminationCorrectionCoefficient + / m_SolarIllumination; + outPixel = static_cast<TOutput>(temp); + return outPixel; + } + +private: + double m_SolarIllumination; + double m_IlluminationCorrectionCoefficient; +}; +} + +/** \class LuminanceToReflectanceImageFilter + * \brief Transform a luminance image into the reflectance. For this it uses the functor LuminanceToReflectanceImageFunctor + * calling for each component of each pixel. + * + * \ingroup ImageToLuminanceImageFunctor + */ template <class TInputImage, class TOutputImage> class ITK_EXPORT LuminanceToReflectanceImageFilter : -public UnaryImageFunctorWithVectorImageFilter< TInputImage, - TOutputImage, - ITK_TYPENAME Functor::LuminanceToReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, - ITK_TYPENAME TOutputImage::InternalPixelType > > + public UnaryImageFunctorWithVectorImageFilter< TInputImage, + TOutputImage, + ITK_TYPENAME Functor::LuminanceToReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, + ITK_TYPENAME TOutputImage::InternalPixelType > > { public: -/** Extract input and output images dimensions.*/ + /** Extract input and output images dimensions.*/ itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); @@ -96,7 +108,7 @@ public: typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; typedef typename Functor::LuminanceToReflectanceImageFunctor<ITK_TYPENAME InputImageType::InternalPixelType, - ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; + ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; /** "typedef" for standard classes. */ @@ -125,7 +137,7 @@ public: /** Image size "typedef" definition. */ typedef typename InputImageType::SizeType SizeType; - /** Set the solar illumination value. */ + /** Set the solar illumination value. */ itkSetMacro(SolarIllumination, VectorType); /** Give the solar illumination value. */ itkGetConstReferenceMacro(SolarIllumination, VectorType); @@ -135,23 +147,23 @@ public: /** Give the zenithal solar angle. */ itkGetConstReferenceMacro(ZenithalSolarAngle, double); - /** Set the day. */ + /** Set the day. */ itkSetClampMacro(Day, int, 1, 31); /** Give the day. */ itkGetConstReferenceMacro(Day, int); - /** Set the mounth. */ + /** Set the mounth. */ itkSetClampMacro(Month, int, 1, 12); /** Give the mounth. */ itkGetConstReferenceMacro(Month, int); - /** Set the flux normalization coefficient. */ + /** Set the flux normalization coefficient. */ void SetFluxNormalizationCoefficient(double coef) - { - m_FluxNormalizationCoefficient = coef; - m_IsSetFluxNormalizationCoefficient = true; - this->Modified(); - }; + { + m_FluxNormalizationCoefficient = coef; + m_IsSetFluxNormalizationCoefficient = true; + this->Modified(); + }; /** Give the flux normalization coefficient. */ itkGetConstReferenceMacro(FluxNormalizationCoefficient, double); @@ -160,10 +172,10 @@ public: /** Give the IsSetFluxNormalizationCoefficient boolean. */ itkGetConstReferenceMacro(IsSetFluxNormalizationCoefficient, bool); - protected: +protected: /** Constructor */ LuminanceToReflectanceImageFilter() - { + { m_ZenithalSolarAngle = 1.; m_FluxNormalizationCoefficient = 1.; m_SolarIllumination.SetSize(1); @@ -171,45 +183,45 @@ public: m_Month = 1; m_Day = 1; m_IsSetFluxNormalizationCoefficient = false; - }; + }; /** Destructor */ - virtual ~LuminanceToReflectanceImageFilter(){}; + virtual ~LuminanceToReflectanceImageFilter() {}; /** Update the functor list */ virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctorVector().clear(); - - for(unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) { - FunctorType functor; - double coefTemp = 0.; - if (!m_IsSetFluxNormalizationCoefficient) + this->GetFunctorVector().clear(); + + for (unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) + { + FunctorType functor; + double coefTemp = 0.; + if (!m_IsSetFluxNormalizationCoefficient) { if (m_Day*m_Month != 0 && m_Day<32 && m_Month<13) - { - otb_6s_doublereal dsol = 0.; - otb_6s_integer day = static_cast<otb_6s_integer>(m_Day); - otb_6s_integer month = static_cast<otb_6s_integer>(m_Month); - int cr(0); - cr = otb_6s_varsol_(&day, &month, &dsol); - coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*static_cast<double>(dsol); - } + { + otb_6s_doublereal dsol = 0.; + otb_6s_integer day = static_cast<otb_6s_integer>(m_Day); + otb_6s_integer month = static_cast<otb_6s_integer>(m_Month); + int cr(0); + cr = otb_6s_varsol_(&day, &month, &dsol); + coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*static_cast<double>(dsol); + } else - { - itkExceptionMacro( << "Day has to be included between 1 and 31, Month beetween 1 and 12."); - } + { + itkExceptionMacro( << "Day has to be included between 1 and 31, Month beetween 1 and 12."); + } } - else + else { coefTemp = vcl_cos(m_ZenithalSolarAngle*M_PI/180.)*m_FluxNormalizationCoefficient*m_FluxNormalizationCoefficient; } - functor.SetIlluminationCorrectionCoefficient(1. / coefTemp); - functor.SetSolarIllumination(static_cast<double>(m_SolarIllumination[i])); + functor.SetIlluminationCorrectionCoefficient(1. / coefTemp); + functor.SetSolarIllumination(static_cast<double>(m_SolarIllumination[i])); - this->GetFunctorVector().push_back(functor); - } + this->GetFunctorVector().push_back(functor); } + } private: diff --git a/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.h b/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.h index f4480dcdc28070e8dd7807278192cf6b1cdfb8ea..f9f2861d71802348c2271affd15efa568e83f48f 100644 --- a/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.h +++ b/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.h @@ -34,10 +34,10 @@ namespace otb * */ template <class TInputImage, class TOutputImage, - class TFunction = Functor::ARVI< typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TOutputImage::PixelType> > +class TFunction = Functor::ARVI< typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TOutputImage::PixelType> > class ITK_EXPORT MultiChannelRAndBAndNIRVegetationIndexImageFilter : public itk::InPlaceImageFilter<TInputImage,TOutputImage> { public: @@ -68,8 +68,14 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; - const FunctorType& GetFunctor() const { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -80,10 +86,10 @@ public: void SetFunctor(const FunctorType& functor) { if (m_Functor != functor) - { + { m_Functor = functor; this->Modified(); - } + } } /** Set/Get the red channel index. Value must be in [1...[ */ diff --git a/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.txx b/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.txx index 4c4b6cba673cc06d7889b9e4d68579855a1fc607..845266542904daa1e470b43e71072bdbe8e7b4bf 100644 --- a/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.txx +++ b/Code/Radiometry/otbMultiChannelRAndBAndNIRVegetationIndexImageFilter.txx @@ -59,9 +59,9 @@ MultiChannelRAndBAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunc typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); if ( !outputPtr || !inputPtr) - { + { return; - } + } // Set the output image largest possible region. Use a RegionCopier // so that the input and output images can be different dimensions. @@ -74,20 +74,20 @@ MultiChannelRAndBAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunc const itk::ImageBase<Superclass::InputImageDimension> *phyData; phyData - = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); + = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); if (phyData) - { + { // Copy what we can from the image from spacing and origin of the input // This logic needs to be augmented with logic that select which // dimensions to copy unsigned int i, j; const typename InputImageType::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::PointType& - inputOrigin = inputPtr->GetOrigin(); + inputOrigin = inputPtr->GetOrigin(); const typename InputImageType::DirectionType& - inputDirection = inputPtr->GetDirection(); + inputDirection = inputPtr->GetDirection(); typename OutputImageType::SpacingType outputSpacing; typename OutputImageType::PointType outputOrigin; @@ -96,52 +96,52 @@ MultiChannelRAndBAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunc // copy the input to the output and fill the rest of the // output with zeros. for (i=0; i < Superclass::InputImageDimension; ++i) - { + { outputSpacing[i] = inputSpacing[i]; outputOrigin[i] = inputOrigin[i]; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j < Superclass::InputImageDimension) - { + { outputDirection[j][i] = inputDirection[j][i]; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } for (; i < Superclass::OutputImageDimension; ++i) - { + { outputSpacing[i] = 1.0; outputOrigin[i] = 0.0; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j == i) - { + { outputDirection[j][i] = 1.0; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } // set the spacing and origin outputPtr->SetSpacing( outputSpacing ); outputPtr->SetOrigin( outputOrigin ); outputPtr->SetDirection( outputDirection ); outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info - inputPtr->GetNumberOfComponentsPerPixel()); - } + inputPtr->GetNumberOfComponentsPerPixel()); + } else - { + { // pointer could not be cast back down itkExceptionMacro(<< "otb::MultiChannelRAndBAndNIRVegetationIndexImageFilter::GenerateOutputInformation " << "cannot cast input to " << typeid(itk::ImageBase<Superclass::InputImageDimension>*).name() ); - } + } } @@ -172,13 +172,13 @@ MultiChannelRAndBAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunc inputIt.GoToBegin(); outputIt.GoToBegin(); - while( !inputIt.IsAtEnd() ) - { + while ( !inputIt.IsAtEnd() ) + { outputIt.Set( m_Functor( inputIt.Get()[m_RedIndex-1],inputIt.Get()[m_BlueIndex-1], inputIt.Get()[m_NIRIndex-1] ) ); ++inputIt; ++outputIt; progress.CompletedPixel(); // potential exception thrown here - } + } } template <class TInputImage, class TOutputImage, class TFunction > diff --git a/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.h b/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.h index f3112d18b2262e3ca0bb58151d48ca2a40b5be2a..0bdee3acbeee1bea2a20e7705c615ef825f65e87 100644 --- a/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.h +++ b/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.h @@ -34,9 +34,9 @@ namespace otb * */ template <class TInputImage, class TOutputImage, - class TFunction = Functor::NDVI< typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TOutputImage::PixelType> > +class TFunction = Functor::NDVI< typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TOutputImage::PixelType> > class ITK_EXPORT MultiChannelRAndNIRVegetationIndexImageFilter : public itk::InPlaceImageFilter<TInputImage,TOutputImage> { public: @@ -67,8 +67,14 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; - const FunctorType& GetFunctor() const { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a * copy of the specified Functor. This allows the user to specify a @@ -79,10 +85,10 @@ public: void SetFunctor(const FunctorType& functor) { if (m_Functor != functor) - { + { m_Functor = functor; this->Modified(); - } + } } /** Set/Get the red channel index. Value must be in [1...[ */ diff --git a/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.txx b/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.txx index f652a5b00cc567892e3420fa7aece60f33d1f8ee..8d0695b5d7d6b2aed25e125b4ea53d27a1ea53bb 100644 --- a/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.txx +++ b/Code/Radiometry/otbMultiChannelRAndNIRVegetationIndexImageFilter.txx @@ -59,9 +59,9 @@ MultiChannelRAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunction typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); if ( !outputPtr || !inputPtr) - { + { return; - } + } // Set the output image largest possible region. Use a RegionCopier // so that the input and output images can be different dimensions. @@ -74,20 +74,20 @@ MultiChannelRAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunction const itk::ImageBase<Superclass::InputImageDimension> *phyData; phyData - = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); + = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); if (phyData) - { + { // Copy what we can from the image from spacing and origin of the input // This logic needs to be augmented with logic that select which // dimensions to copy unsigned int i, j; const typename InputImageType::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::PointType& - inputOrigin = inputPtr->GetOrigin(); + inputOrigin = inputPtr->GetOrigin(); const typename InputImageType::DirectionType& - inputDirection = inputPtr->GetDirection(); + inputDirection = inputPtr->GetDirection(); typename OutputImageType::SpacingType outputSpacing; typename OutputImageType::PointType outputOrigin; @@ -96,52 +96,52 @@ MultiChannelRAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunction // copy the input to the output and fill the rest of the // output with zeros. for (i=0; i < Superclass::InputImageDimension; ++i) - { + { outputSpacing[i] = inputSpacing[i]; outputOrigin[i] = inputOrigin[i]; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j < Superclass::InputImageDimension) - { + { outputDirection[j][i] = inputDirection[j][i]; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } for (; i < Superclass::OutputImageDimension; ++i) - { + { outputSpacing[i] = 1.0; outputOrigin[i] = 0.0; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j == i) - { + { outputDirection[j][i] = 1.0; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } // set the spacing and origin outputPtr->SetSpacing( outputSpacing ); outputPtr->SetOrigin( outputOrigin ); outputPtr->SetDirection( outputDirection ); outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info - inputPtr->GetNumberOfComponentsPerPixel()); - } + inputPtr->GetNumberOfComponentsPerPixel()); + } else - { + { // pointer could not be cast back down itkExceptionMacro(<< "otb::MultiChannelRAndNIRVegetationIndexImageFilter::GenerateOutputInformation " << "cannot cast input to " << typeid(itk::ImageBase<Superclass::InputImageDimension>*).name() ); - } + } } @@ -172,14 +172,14 @@ MultiChannelRAndNIRVegetationIndexImageFilter<TInputImage,TOutputImage,TFunction inputIt.GoToBegin(); outputIt.GoToBegin(); - while( !inputIt.IsAtEnd() ) - { + while ( !inputIt.IsAtEnd() ) + { // outputIt.Set( m_Functor( inputIt.Get() ) ); outputIt.Set( m_Functor( inputIt.Get()[m_RedIndex-1], inputIt.Get()[m_NIRIndex-1] ) ); ++inputIt; ++outputIt; progress.CompletedPixel(); // potential exception thrown here - } + } } template <class TInputImage, class TOutputImage, class TFunction > diff --git a/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.h b/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.h index d1c991a3b3fba1188f2ecd6053f60bb9a7ecfeb4..0bfc6fe3d86990d256eae74c64c46ec581ac38fc 100644 --- a/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.h +++ b/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.h @@ -30,10 +30,10 @@ namespace otb */ template <class TInputImageR, class TInputImageB, class TInputImageNIR, class TOutputImage, - class TFunction = Functor::ARVI< typename TInputImageR::PixelType, - typename TInputImageB::PixelType, - typename TInputImageNIR::PixelType, - typename TOutputImage::PixelType > > +class TFunction = Functor::ARVI< typename TInputImageR::PixelType, +typename TInputImageB::PixelType, +typename TInputImageNIR::PixelType, +typename TOutputImage::PixelType > > class ITK_EXPORT RAndBAndNIRVegetationIndexImageFilter : public itk::TernaryFunctorImageFilter< TInputImageR, TInputImageB, TInputImageNIR, TOutputImage, TFunction > { public: diff --git a/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.txx b/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.txx index 90654ed650411df8688a249689e0f42b1e579cfb..bc83afaf25086db1fe6d5076c1710bcb746452ca 100644 --- a/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.txx +++ b/Code/Radiometry/otbRAndBAndNIRVegetationIndexImageFilter.txx @@ -27,7 +27,7 @@ namespace otb * Constructor */ template <class TInputImageR, class TInputImageB, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,TOutputImage,TFunction> ::RAndBAndNIRVegetationIndexImageFilter() { @@ -38,7 +38,7 @@ RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,T * Connect one of the operands for pixel-wise addition */ template <class TInputImageR, class TInputImageB, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,TOutputImage,TFunction> ::SetInputR( const TInputImageR * image ) @@ -52,7 +52,7 @@ RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,T * Connect one of the operands for pixel-wise addition */ template <class TInputImageR, class TInputImageB, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,TOutputImage,TFunction> ::SetInputB( const TInputImageB * image ) @@ -64,7 +64,7 @@ RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,T * Connect one of the operands for pixel-wise addition */ template <class TInputImageR, class TInputImageB, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void RAndBAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageB,TInputImageNIR,TOutputImage,TFunction> ::SetInputNIR( const TInputImageNIR * image ) @@ -77,7 +77,7 @@ void RAndBAndNIRVegetationIndexImageFilter<TInputImageR, TInputImageB, TInputImageNIR, TOutputImage, TFunction> ::PrintSelf(std::ostream& os, itk::Indent indent) const { - Superclass::PrintSelf(os,indent); + Superclass::PrintSelf(os,indent); } } diff --git a/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.h b/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.h index 9c87377a9e2759525d6147b8453d0c156cd715a8..65cb9bbe6ec768ebede76e639041b74fd2cca9dc 100644 --- a/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.h +++ b/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.h @@ -30,9 +30,9 @@ namespace otb */ template <class TInputImageR, class TInputImageNIR, class TOutputImage, - class TFunction = Functor::NDVI< typename TInputImageR::PixelType, - typename TInputImageNIR::PixelType, - typename TOutputImage::PixelType > > +class TFunction = Functor::NDVI< typename TInputImageR::PixelType, +typename TInputImageNIR::PixelType, +typename TOutputImage::PixelType > > class ITK_EXPORT RAndNIRVegetationIndexImageFilter : public itk::BinaryFunctorImageFilter< TInputImageR, TInputImageNIR, TOutputImage, TFunction > { public: @@ -68,9 +68,9 @@ protected: void PrintSelf(std::ostream& os, itk::Indent indent) const; -/* void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ); -*/ + /* void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, + int threadId ); + */ private: RAndNIRVegetationIndexImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.txx b/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.txx index a57662f277fc4e4fab2c4cc4c523ddd772cf4c66..4a1618c570dd0b925a376670c5492acd59f62b2d 100644 --- a/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.txx +++ b/Code/Radiometry/otbRAndNIRVegetationIndexImageFilter.txx @@ -31,7 +31,7 @@ namespace otb * Constructor */ template <class TInputImageR, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > RAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageNIR,TOutputImage,TFunction> ::RAndNIRVegetationIndexImageFilter() { @@ -42,7 +42,7 @@ RAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageNIR,TOutputImage,TFunc * Connect one of the operands for pixel-wise addition */ template <class TInputImageR, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void RAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageNIR,TOutputImage,TFunction> ::SetInputR( const TInputImageR * image1 ) @@ -56,7 +56,7 @@ RAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageNIR,TOutputImage,TFunc * Connect one of the operands for pixel-wise addition */ template <class TInputImageR, class TInputImageNIR, - class TOutputImage, class TFunction > +class TOutputImage, class TFunction > void RAndNIRVegetationIndexImageFilter<TInputImageR,TInputImageNIR,TOutputImage,TFunction> ::SetInputNIR( const TInputImageNIR * image2 ) @@ -115,7 +115,7 @@ void RAndNIRVegetationIndexImageFilter<TInputImageR, TInputImageNIR, TOutputImage, TFunction> ::PrintSelf(std::ostream& os, itk::Indent indent) const { - Superclass::PrintSelf(os,indent); + Superclass::PrintSelf(os,indent); } } diff --git a/Code/Radiometry/otbReflectanceToSurfaceReflectanceImageFilter.h b/Code/Radiometry/otbReflectanceToSurfaceReflectanceImageFilter.h index 3ba4e16c478be868a70518fccfade8a3501be744..557c0cf0a76a77a677a378a8908e81b10ce995b7 100644 --- a/Code/Radiometry/otbReflectanceToSurfaceReflectanceImageFilter.h +++ b/Code/Radiometry/otbReflectanceToSurfaceReflectanceImageFilter.h @@ -29,157 +29,175 @@ namespace otb { - namespace Functor - { - /** Functor::LuminanceToReflectanceImageFunctor - * Compute the surface reflectance pixel from a TOA reflectance. - * - * \ingroup Functor - */ - template <class TInput, class TOutput> - class ReflectanceToSurfaceReflectanceImageFunctor +namespace Functor +{ +/** Functor::LuminanceToReflectanceImageFunctor + * Compute the surface reflectance pixel from a TOA reflectance. + * + * \ingroup Functor + */ +template <class TInput, class TOutput> +class ReflectanceToSurfaceReflectanceImageFunctor +{ +public: + ReflectanceToSurfaceReflectanceImageFunctor() { - public: - ReflectanceToSurfaceReflectanceImageFunctor() - { - m_Coefficient = 1.; - m_Residu = 1.; - m_SphericalAlbedo = 1.; - }; - ~ReflectanceToSurfaceReflectanceImageFunctor() {}; - - /** - * Set/Get the spherical albedo of the atmosphere. - */ - void SetSphericalAlbedo(double albedo){ m_SphericalAlbedo=albedo;}; - double GetSphericalAlbedo(){ return m_SphericalAlbedo; }; - - /** - * Set/Get Coefficient, computed from AtmosphericRadiativeTermsPointerType datas. - */ - void SetCoefficient(double coef){ m_Coefficient = coef; }; - double GetCoefficient(){ return m_Coefficient; }; - - /** - * Set/Get Residu, computed from AtmosphericRadiativeTermsPointerType datas. - */ - void SetResidu(double res){ m_Residu = res; }; - double GetResidu(){ return m_Residu; }; - - inline TOutput operator() (const TInput & inPixel) - { - TOutput outPixel; - double temp, temp2; - temp = static_cast<double>(inPixel)*m_Coefficient + m_Residu; - temp2 = temp / (1. + m_SphericalAlbedo * temp); - outPixel = static_cast<TOutput>(temp2); - - - return outPixel; - } - - private: - double m_SphericalAlbedo; - double m_Coefficient; - double m_Residu; + m_Coefficient = 1.; + m_Residu = 1.; + m_SphericalAlbedo = 1.; }; - } - /** \class ReflectanceToSurfaceReflectanceImageFilter - * \brief Calculates the slope, the orientation incidence and exitance radius values for each pixel. - * - * - * \ingroup AtmosphericRadiativeTerms - * \ingroup AtmosphericCorrectionParameters - * \ingroup LuminanceToReflectanceImageFilter - * \ingroup ImageToReflectanceImageFilter + ~ReflectanceToSurfaceReflectanceImageFunctor() {}; + + /** + * Set/Get the spherical albedo of the atmosphere. */ - template <class TInputImage, class TOutputImage > - class ITK_EXPORT ReflectanceToSurfaceReflectanceImageFilter : - public UnaryImageFunctorWithVectorImageFilter< TInputImage, - TOutputImage, - ITK_TYPENAME Functor::ReflectanceToSurfaceReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, - ITK_TYPENAME TOutputImage::InternalPixelType > > - { - public: - /** Extract input and output images dimensions.*/ - itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); - itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); - - /** "typedef" to simplify the variables definition and the declaration. */ - typedef TInputImage InputImageType; - typedef TOutputImage OutputImageType; - typedef typename Functor::ReflectanceToSurfaceReflectanceImageFunctor<ITK_TYPENAME InputImageType::InternalPixelType, - ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; - /** "typedef" for standard classes. */ - typedef ReflectanceToSurfaceReflectanceImageFilter Self; - typedef UnaryImageFunctorWithVectorImageFilter< InputImageType, OutputImageType, FunctorType > Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** object factory method. */ - itkNewMacro(Self); - - /** return class name. */ - itkTypeMacro(ReflectanceToSurfaceReflectanceImageFilter, UnaryImageFunctorWithVectorImageFilter); - - /** Supported images definition. */ - typedef typename InputImageType::PixelType InputPixelType; - typedef typename InputImageType::InternalPixelType InputInternalPixelType; - typedef typename InputImageType::RegionType InputImageRegionType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename OutputImageType::InternalPixelType OutputInternalPixelType; - typedef typename OutputImageType::RegionType OutputImageRegionType; - - typedef AtmosphericRadiativeTerms::Pointer AtmosphericRadiativeTermsPointerType; - - /** Get/Set Atmospheric Radiative Terms. */ - void SetAtmosphericRadiativeTerms(AtmosphericRadiativeTermsPointerType atmo) + void SetSphericalAlbedo(double albedo) + { + m_SphericalAlbedo=albedo; + }; + double GetSphericalAlbedo() + { + return m_SphericalAlbedo; + }; + + /** + * Set/Get Coefficient, computed from AtmosphericRadiativeTermsPointerType datas. + */ + void SetCoefficient(double coef) + { + m_Coefficient = coef; + }; + double GetCoefficient() + { + return m_Coefficient; + }; + + /** + * Set/Get Residu, computed from AtmosphericRadiativeTermsPointerType datas. + */ + void SetResidu(double res) + { + m_Residu = res; + }; + double GetResidu() + { + return m_Residu; + }; + + inline TOutput operator() (const TInput & inPixel) + { + TOutput outPixel; + double temp, temp2; + temp = static_cast<double>(inPixel)*m_Coefficient + m_Residu; + temp2 = temp / (1. + m_SphericalAlbedo * temp); + outPixel = static_cast<TOutput>(temp2); + + + return outPixel; + } + +private: + double m_SphericalAlbedo; + double m_Coefficient; + double m_Residu; +}; +} +/** \class ReflectanceToSurfaceReflectanceImageFilter + * \brief Calculates the slope, the orientation incidence and exitance radius values for each pixel. + * + * + * \ingroup AtmosphericRadiativeTerms + * \ingroup AtmosphericCorrectionParameters + * \ingroup LuminanceToReflectanceImageFilter + * \ingroup ImageToReflectanceImageFilter + */ +template <class TInputImage, class TOutputImage > +class ITK_EXPORT ReflectanceToSurfaceReflectanceImageFilter : + public UnaryImageFunctorWithVectorImageFilter< TInputImage, + TOutputImage, + ITK_TYPENAME Functor::ReflectanceToSurfaceReflectanceImageFunctor< ITK_TYPENAME TInputImage::InternalPixelType, + ITK_TYPENAME TOutputImage::InternalPixelType > > +{ +public: + /** Extract input and output images dimensions.*/ + itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** "typedef" to simplify the variables definition and the declaration. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename Functor::ReflectanceToSurfaceReflectanceImageFunctor<ITK_TYPENAME InputImageType::InternalPixelType, + ITK_TYPENAME OutputImageType::InternalPixelType> FunctorType; + /** "typedef" for standard classes. */ + typedef ReflectanceToSurfaceReflectanceImageFilter Self; + typedef UnaryImageFunctorWithVectorImageFilter< InputImageType, OutputImageType, FunctorType > Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** object factory method. */ + itkNewMacro(Self); + + /** return class name. */ + itkTypeMacro(ReflectanceToSurfaceReflectanceImageFilter, UnaryImageFunctorWithVectorImageFilter); + + /** Supported images definition. */ + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::InternalPixelType InputInternalPixelType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::InternalPixelType OutputInternalPixelType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + typedef AtmosphericRadiativeTerms::Pointer AtmosphericRadiativeTermsPointerType; + + /** Get/Set Atmospheric Radiative Terms. */ + void SetAtmosphericRadiativeTerms(AtmosphericRadiativeTermsPointerType atmo) { m_AtmosphericRadiativeTerms = atmo; this->SetNthInput(1, m_AtmosphericRadiativeTerms); this->Modified(); } - AtmosphericRadiativeTermsPointerType GetAtmosphericRadiativeTerms() + AtmosphericRadiativeTermsPointerType GetAtmosphericRadiativeTerms() { return m_AtmosphericRadiativeTerms; } - protected: - /** Constructor */ - ReflectanceToSurfaceReflectanceImageFilter() +protected: + /** Constructor */ + ReflectanceToSurfaceReflectanceImageFilter() { m_AtmosphericRadiativeTerms = AtmosphericRadiativeTerms::New(); }; - /** Destructor */ - virtual ~ReflectanceToSurfaceReflectanceImageFilter(){}; + /** Destructor */ + virtual ~ReflectanceToSurfaceReflectanceImageFilter() {}; - /** Initialize the functor vector */ - void BeforeThreadedGenerateData () + /** Initialize the functor vector */ + void BeforeThreadedGenerateData () { this->GetFunctorVector().clear(); - for(unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) - { - double coef; - double res; - coef = static_cast<double>(m_AtmosphericRadiativeTerms->GetTotalGaseousTransmission(i) - * m_AtmosphericRadiativeTerms->GetDownwardTransmittance(i) - * m_AtmosphericRadiativeTerms->GetUpwardTransmittance(i) ); - coef = 1. / coef; - res = -m_AtmosphericRadiativeTerms->GetIntrinsicAtmosphericReflectance(i) * coef; - - FunctorType functor; - functor.SetCoefficient(coef); - functor.SetResidu(res); - functor.SetSphericalAlbedo(static_cast<double>(m_AtmosphericRadiativeTerms->GetSphericalAlbedo(i))); - - this->GetFunctorVector().push_back(functor); - } + for (unsigned int i = 0;i<this->GetInput()->GetNumberOfComponentsPerPixel();++i) + { + double coef; + double res; + coef = static_cast<double>(m_AtmosphericRadiativeTerms->GetTotalGaseousTransmission(i) + * m_AtmosphericRadiativeTerms->GetDownwardTransmittance(i) + * m_AtmosphericRadiativeTerms->GetUpwardTransmittance(i) ); + coef = 1. / coef; + res = -m_AtmosphericRadiativeTerms->GetIntrinsicAtmosphericReflectance(i) * coef; + + FunctorType functor; + functor.SetCoefficient(coef); + functor.SetResidu(res); + functor.SetSphericalAlbedo(static_cast<double>(m_AtmosphericRadiativeTerms->GetSphericalAlbedo(i))); + + this->GetFunctorVector().push_back(functor); + } } - private: - AtmosphericRadiativeTermsPointerType m_AtmosphericRadiativeTerms; - }; +private: + AtmosphericRadiativeTermsPointerType m_AtmosphericRadiativeTerms; +}; } // end namespace otb diff --git a/Code/Radiometry/otbSIXSTraits.cxx b/Code/Radiometry/otbSIXSTraits.cxx index 36068d34a42ddfbc14af9d04111bb89759f2a5aa..24149f59f76244b2a781f76c5de1bd9302c6ecbf 100644 --- a/Code/Radiometry/otbSIXSTraits.cxx +++ b/Code/Radiometry/otbSIXSTraits.cxx @@ -27,204 +27,204 @@ namespace otb void SIXSTraits::ComputeAtmosphericParameters( - const double SolarZenithalAngle, /** The Solar zenithal angle */ - const double SolarAzimutalAngle, /** The Solar azimutal angle */ - const double ViewingZenithalAngle, /** The Viewing zenithal angle */ - const double ViewingAzimutalAngle, /** The Viewing azimutal angle */ - const unsigned int Month, /** The Month */ - const unsigned int Day, /** The Day (in the month) */ - const double AtmosphericPressure, /** The Atmospheric pressure */ - const double WaterVaporAmount, /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ - const double OzoneAmount, /** The Ozone amount (Stratospheric ozone layer content) */ - const AerosolModelType & AerosolModel, /** The Aerosol model */ - const double AerosolOptical, /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ - WavelenghtSpectralType* WavelenghtSpectralBand, /** Wavelenght for the spectral band definition */ - /** Note : The Max wavelenght spectral band value must be updated ! */ - double & AtmosphericReflectance, /** Atmospheric reflectance */ - double & AtmosphericSphericalAlbedo, /** atmospheric spherical albedo */ - double & TotalGaseousTransmission, /** Total gaseous transmission */ - double & DownwardTransmittance, /** downward transmittance */ - double & UpwardTransmittance, /** upward transmittance */ - double & UpwardDiffuseTransmittance, /** upward diffuse transmittance */ - double & UpwardDirectTransmittance, /** Upward direct transmittance */ - double & UpwardDiffuseTransmittanceForRayleigh, /** upward diffuse transmittance for rayleigh */ - double & UpwardDiffuseTransmittanceForAerosol /** supward diffuse transmittance for aerosols */ - ) + const double SolarZenithalAngle, /** The Solar zenithal angle */ + const double SolarAzimutalAngle, /** The Solar azimutal angle */ + const double ViewingZenithalAngle, /** The Viewing zenithal angle */ + const double ViewingAzimutalAngle, /** The Viewing azimutal angle */ + const unsigned int Month, /** The Month */ + const unsigned int Day, /** The Day (in the month) */ + const double AtmosphericPressure, /** The Atmospheric pressure */ + const double WaterVaporAmount, /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ + const double OzoneAmount, /** The Ozone amount (Stratospheric ozone layer content) */ + const AerosolModelType & AerosolModel, /** The Aerosol model */ + const double AerosolOptical, /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ + WavelenghtSpectralType* WavelenghtSpectralBand, /** Wavelenght for the spectral band definition */ + /** Note : The Max wavelenght spectral band value must be updated ! */ + double & AtmosphericReflectance, /** Atmospheric reflectance */ + double & AtmosphericSphericalAlbedo, /** atmospheric spherical albedo */ + double & TotalGaseousTransmission, /** Total gaseous transmission */ + double & DownwardTransmittance, /** downward transmittance */ + double & UpwardTransmittance, /** upward transmittance */ + double & UpwardDiffuseTransmittance, /** upward diffuse transmittance */ + double & UpwardDirectTransmittance, /** Upward direct transmittance */ + double & UpwardDiffuseTransmittanceForRayleigh, /** upward diffuse transmittance for rayleigh */ + double & UpwardDiffuseTransmittanceForAerosol /** supward diffuse transmittance for aerosols */ +) { // geometrical conditions - otb_6s_doublereal asol(static_cast<otb_6s_doublereal>(SolarZenithalAngle)); - otb_6s_doublereal phi0(static_cast<otb_6s_doublereal>(SolarAzimutalAngle)); - otb_6s_doublereal avis(static_cast<otb_6s_doublereal>(ViewingZenithalAngle)); - otb_6s_doublereal phiv(static_cast<otb_6s_doublereal>(ViewingAzimutalAngle)); - otb_6s_integer month(static_cast<otb_6s_integer>(Month)); - otb_6s_integer jday(static_cast<otb_6s_integer>(Day)); - otb_6s_doublereal pressure(static_cast<otb_6s_doublereal>(AtmosphericPressure)); - otb_6s_doublereal uw(static_cast<otb_6s_doublereal>(WaterVaporAmount)); - otb_6s_doublereal uo3(static_cast<otb_6s_doublereal>(OzoneAmount)); + otb_6s_doublereal asol(static_cast<otb_6s_doublereal>(SolarZenithalAngle)); + otb_6s_doublereal phi0(static_cast<otb_6s_doublereal>(SolarAzimutalAngle)); + otb_6s_doublereal avis(static_cast<otb_6s_doublereal>(ViewingZenithalAngle)); + otb_6s_doublereal phiv(static_cast<otb_6s_doublereal>(ViewingAzimutalAngle)); + otb_6s_integer month(static_cast<otb_6s_integer>(Month)); + otb_6s_integer jday(static_cast<otb_6s_integer>(Day)); + otb_6s_doublereal pressure(static_cast<otb_6s_doublereal>(AtmosphericPressure)); + otb_6s_doublereal uw(static_cast<otb_6s_doublereal>(WaterVaporAmount)); + otb_6s_doublereal uo3(static_cast<otb_6s_doublereal>(OzoneAmount)); // atmospheric model - otb_6s_integer iaer(static_cast<otb_6s_integer>(AerosolModel)); - otb_6s_doublereal taer55(static_cast<otb_6s_doublereal>(AerosolOptical)); - - // Init output parameters - AtmosphericReflectance = 0.; - AtmosphericSphericalAlbedo = 0.; - TotalGaseousTransmission = 0.; - DownwardTransmittance = 0.; - UpwardTransmittance = 0.; - UpwardDiffuseTransmittance = 0.; - UpwardDirectTransmittance = 0.; - UpwardDiffuseTransmittanceForRayleigh = 0.; - UpwardDiffuseTransmittanceForAerosol = 0.; - - otb_6s_doublereal wlinf(0.), wlsup(0.); - otb_6s_doublereal otb_ratm__(0.), sast(0.), tgasm(0.), sdtott(0.), sutott(0.); - otb_6s_doublereal tdif_up(0.), tdir_up(0.), tdif_up_ray(0.), tdif_up_aer(0.); - try - { - // 6S official Wavelenght Spectral Band step value - const float SIXSStepOfWavelenghtSpectralBandValues = .0025; - // Generate 6s Wavelenght Spectral Band with the offcicial step value - ComputeWavelenghtSpectralBandValuesFor6S( SIXSStepOfWavelenghtSpectralBandValues, - WavelenghtSpectralBand // Update - ); - - // 6S official tab size Wavelenght Spectral - const unsigned int S_6S_SIZE=1501; - // Generate WavelenghtSpectralBand in 6S compatible buffer s[1501] - wlinf = static_cast<otb_6s_doublereal>(WavelenghtSpectralBand->GetMinSpectralValue()); - wlsup = static_cast<otb_6s_doublereal>(WavelenghtSpectralBand->GetMaxSpectralValue()); - - otb_6s_integer iinf = static_cast<otb_6s_integer>((wlinf - (float).25) / SIXSStepOfWavelenghtSpectralBandValues + (float)1.5); - otb_6s_integer isup = static_cast<otb_6s_integer>((wlsup - (float).25) / SIXSStepOfWavelenghtSpectralBandValues + (float)1.5); - - otb_6s_integer cpt=iinf-1; - otb_6s_doublereal * s(NULL); - s = new otb_6s_doublereal[S_6S_SIZE]; - memset( s, 0, S_6S_SIZE*sizeof(otb_6s_doublereal) ); - const ValuesVectorType & FilterFunctionValues6S = WavelenghtSpectralBand->GetFilterFunctionValues6S(); - // Set the values of FilterFunctionValues6S in s between [iinf-1;isup] - for(unsigned int i=0; cpt<isup; i++) - { - s[cpt] = FilterFunctionValues6S[i]; - cpt++; - } - // Call 6s main function - otbMsgDevMacro(<< "Start call 6S main function ..."); - otb_6s_ssssss_otb_main_function( &asol, &phi0, &avis, &phiv, &month, &jday, - &pressure, &uw, &uo3, - &iaer, - &taer55, - &wlinf, &wlsup, - s, - &otb_ratm__, - &sast, - &tgasm, - &sdtott, - &sutott, - &tdif_up, - &tdir_up, - &tdif_up_ray, - &tdif_up_aer); - otbMsgDevMacro(<< "Done call 6S main function!"); - delete [] s; - s = NULL; - } - catch( std::bad_alloc & err ) - { - itkGenericExceptionMacro( <<"Exception bad_alloc in SIXSTraits class: "<<(char*)err.what()); - } - catch (...) - { - itkGenericExceptionMacro( <<"Unknown exception in SIXSTraits class (catch(...)"); - } - - // Set outputs parameters - AtmosphericReflectance = static_cast<double>(otb_ratm__); - AtmosphericSphericalAlbedo = static_cast<double>(sast); - TotalGaseousTransmission = static_cast<double>(tgasm); - DownwardTransmittance = static_cast<double>(sdtott); - UpwardTransmittance = static_cast<double>(sutott); - UpwardDiffuseTransmittance = static_cast<double>(tdif_up); - UpwardDirectTransmittance = static_cast<double>(tdir_up); - UpwardDiffuseTransmittanceForRayleigh = static_cast<double>(tdif_up_ray); - UpwardDiffuseTransmittanceForAerosol = static_cast<double>(tdif_up_aer); + otb_6s_integer iaer(static_cast<otb_6s_integer>(AerosolModel)); + otb_6s_doublereal taer55(static_cast<otb_6s_doublereal>(AerosolOptical)); + + // Init output parameters + AtmosphericReflectance = 0.; + AtmosphericSphericalAlbedo = 0.; + TotalGaseousTransmission = 0.; + DownwardTransmittance = 0.; + UpwardTransmittance = 0.; + UpwardDiffuseTransmittance = 0.; + UpwardDirectTransmittance = 0.; + UpwardDiffuseTransmittanceForRayleigh = 0.; + UpwardDiffuseTransmittanceForAerosol = 0.; + + otb_6s_doublereal wlinf(0.), wlsup(0.); + otb_6s_doublereal otb_ratm__(0.), sast(0.), tgasm(0.), sdtott(0.), sutott(0.); + otb_6s_doublereal tdif_up(0.), tdir_up(0.), tdif_up_ray(0.), tdif_up_aer(0.); + try + { + // 6S official Wavelenght Spectral Band step value + const float SIXSStepOfWavelenghtSpectralBandValues = .0025; + // Generate 6s Wavelenght Spectral Band with the offcicial step value + ComputeWavelenghtSpectralBandValuesFor6S( SIXSStepOfWavelenghtSpectralBandValues, + WavelenghtSpectralBand // Update + ); + + // 6S official tab size Wavelenght Spectral + const unsigned int S_6S_SIZE=1501; + // Generate WavelenghtSpectralBand in 6S compatible buffer s[1501] + wlinf = static_cast<otb_6s_doublereal>(WavelenghtSpectralBand->GetMinSpectralValue()); + wlsup = static_cast<otb_6s_doublereal>(WavelenghtSpectralBand->GetMaxSpectralValue()); + + otb_6s_integer iinf = static_cast<otb_6s_integer>((wlinf - (float).25) / SIXSStepOfWavelenghtSpectralBandValues + (float)1.5); + otb_6s_integer isup = static_cast<otb_6s_integer>((wlsup - (float).25) / SIXSStepOfWavelenghtSpectralBandValues + (float)1.5); + + otb_6s_integer cpt=iinf-1; + otb_6s_doublereal * s(NULL); + s = new otb_6s_doublereal[S_6S_SIZE]; + memset( s, 0, S_6S_SIZE*sizeof(otb_6s_doublereal) ); + const ValuesVectorType & FilterFunctionValues6S = WavelenghtSpectralBand->GetFilterFunctionValues6S(); + // Set the values of FilterFunctionValues6S in s between [iinf-1;isup] + for (unsigned int i=0; cpt<isup; i++) + { + s[cpt] = FilterFunctionValues6S[i]; + cpt++; + } + // Call 6s main function + otbMsgDevMacro(<< "Start call 6S main function ..."); + otb_6s_ssssss_otb_main_function( &asol, &phi0, &avis, &phiv, &month, &jday, + &pressure, &uw, &uo3, + &iaer, + &taer55, + &wlinf, &wlsup, + s, + &otb_ratm__, + &sast, + &tgasm, + &sdtott, + &sutott, + &tdif_up, + &tdir_up, + &tdif_up_ray, + &tdif_up_aer); + otbMsgDevMacro(<< "Done call 6S main function!"); + delete [] s; + s = NULL; + } + catch ( std::bad_alloc & err ) + { + itkGenericExceptionMacro( <<"Exception bad_alloc in SIXSTraits class: "<<(char*)err.what()); + } + catch (...) + { + itkGenericExceptionMacro( <<"Unknown exception in SIXSTraits class (catch(...)"); + } + + // Set outputs parameters + AtmosphericReflectance = static_cast<double>(otb_ratm__); + AtmosphericSphericalAlbedo = static_cast<double>(sast); + TotalGaseousTransmission = static_cast<double>(tgasm); + DownwardTransmittance = static_cast<double>(sdtott); + UpwardTransmittance = static_cast<double>(sutott); + UpwardDiffuseTransmittance = static_cast<double>(tdif_up); + UpwardDirectTransmittance = static_cast<double>(tdir_up); + UpwardDiffuseTransmittanceForRayleigh = static_cast<double>(tdif_up_ray); + UpwardDiffuseTransmittanceForAerosol = static_cast<double>(tdif_up_aer); } void SIXSTraits::ComputeWavelenghtSpectralBandValuesFor6S( - const double SIXSStepOfWavelenghtSpectralBandValues, - WavelenghtSpectralType* WavelenghtSpectralBand - ) + const double SIXSStepOfWavelenghtSpectralBandValues, + WavelenghtSpectralType* WavelenghtSpectralBand +) { - const double L_min = static_cast<double>(WavelenghtSpectralBand->GetMinSpectralValue()); - const double L_max = static_cast<double>(WavelenghtSpectralBand->GetMaxSpectralValue()); - const double L_userStep = static_cast<double>(WavelenghtSpectralBand->GetUserStep()); - const ValuesVectorType & FilterFunctionValues = WavelenghtSpectralBand->GetFilterFunctionValues(); - unsigned int i = 1; - unsigned int j = 1; - const double invStep = static_cast<double>(1./L_userStep); - double value(0.); - - // Generate WavelenghtSpectralBand if the step is not the offical 6S step value - if( vcl_abs(L_userStep-SIXSStepOfWavelenghtSpectralBandValues) > .000001 ) - { - ValuesVectorType values(1, FilterFunctionValues[0]); //vector size 1 with the value vect[0] - - // Stop the interpolation at the max spectral value. - value = i*SIXSStepOfWavelenghtSpectralBandValues; - while(L_min+value <= L_max ) - { - // Search the User interval that surround the StepOfWavelenghtSpectralBandValues current value. + const double L_min = static_cast<double>(WavelenghtSpectralBand->GetMinSpectralValue()); + const double L_max = static_cast<double>(WavelenghtSpectralBand->GetMaxSpectralValue()); + const double L_userStep = static_cast<double>(WavelenghtSpectralBand->GetUserStep()); + const ValuesVectorType & FilterFunctionValues = WavelenghtSpectralBand->GetFilterFunctionValues(); + unsigned int i = 1; + unsigned int j = 1; + const double invStep = static_cast<double>(1./L_userStep); + double value(0.); + + // Generate WavelenghtSpectralBand if the step is not the offical 6S step value + if ( vcl_abs(L_userStep-SIXSStepOfWavelenghtSpectralBandValues) > .000001 ) + { + ValuesVectorType values(1, FilterFunctionValues[0]); //vector size 1 with the value vect[0] + + // Stop the interpolation at the max spectral value. + value = i*SIXSStepOfWavelenghtSpectralBandValues; + while (L_min+value <= L_max ) + { + // Search the User interval that surround the StepOfWavelenghtSpectralBandValues current value. // removed the <= here, might be wrong - while(j*L_userStep < value) - { - j++; - } + while (j*L_userStep < value) + { + j++; + } // Check if we are not out of bound - if(j>=FilterFunctionValues.size()) + if (j>=FilterFunctionValues.size()) { itkGenericExceptionMacro(<<"Index "<<j<<" out of bound for FilterFunctionValues vector (size: "<<FilterFunctionValues.size()<<")."); } - double valueTemp; - valueTemp = static_cast<double>(FilterFunctionValues[j-1]) - + ((static_cast<double>(FilterFunctionValues[j])-static_cast<double>(FilterFunctionValues[j-1]))*invStep) - *(value-L_userStep*(j-1)); - values.push_back(static_cast<WavelenghtSpectralBandType>(valueTemp)); - - i++; - value = i*SIXSStepOfWavelenghtSpectralBandValues; - } - - if (L_min+(i-1)*SIXSStepOfWavelenghtSpectralBandValues != L_max) - { - values.push_back(0); - } - // Store this values - WavelenghtSpectralBand->SetFilterFunctionValues6S(values); - // Store the new Max MaxSpectralValue - WavelenghtSpectralBand->SetMaxSpectralValue(static_cast<WavelenghtSpectralBandType>(L_min + i*SIXSStepOfWavelenghtSpectralBandValues)); - - } - else - { - // Init with copy of FilterFunctionValues input vector values - WavelenghtSpectralBand->SetFilterFunctionValues6S(FilterFunctionValues); - } + double valueTemp; + valueTemp = static_cast<double>(FilterFunctionValues[j-1]) + + ((static_cast<double>(FilterFunctionValues[j])-static_cast<double>(FilterFunctionValues[j-1]))*invStep) + *(value-L_userStep*(j-1)); + values.push_back(static_cast<WavelenghtSpectralBandType>(valueTemp)); + + i++; + value = i*SIXSStepOfWavelenghtSpectralBandValues; + } + + if (L_min+(i-1)*SIXSStepOfWavelenghtSpectralBandValues != L_max) + { + values.push_back(0); + } + // Store this values + WavelenghtSpectralBand->SetFilterFunctionValues6S(values); + // Store the new Max MaxSpectralValue + WavelenghtSpectralBand->SetMaxSpectralValue(static_cast<WavelenghtSpectralBandType>(L_min + i*SIXSStepOfWavelenghtSpectralBandValues)); + + } + else + { + // Init with copy of FilterFunctionValues input vector values + WavelenghtSpectralBand->SetFilterFunctionValues6S(FilterFunctionValues); + } } void SIXSTraits::ComputeEnvironmentalContribution(const double diffuseTransmittanceForRayleighScattering, - const double diffuseTransmittanceForAerosolScattering, - const double radiusInKilometers, - const double altitude, - const double cosineOfViewingAngle, - double & rayleighEstimation, - double & aerosolEstimation, - double & globalEstimation) + const double diffuseTransmittanceForAerosolScattering, + const double radiusInKilometers, + const double altitude, + const double cosineOfViewingAngle, + double & rayleighEstimation, + double & aerosolEstimation, + double & globalEstimation) { otb_6s_doublereal difr(static_cast<otb_6s_doublereal>(diffuseTransmittanceForRayleighScattering)); otb_6s_doublereal difa(static_cast<otb_6s_doublereal>(diffuseTransmittanceForAerosolScattering)); diff --git a/Code/Radiometry/otbSIXSTraits.h b/Code/Radiometry/otbSIXSTraits.h index 31a79edc1bca5888ee59796f22fd08272466870f..f26a0e45cb8befc522c3bdd65a86641edaabf031 100644 --- a/Code/Radiometry/otbSIXSTraits.h +++ b/Code/Radiometry/otbSIXSTraits.h @@ -45,29 +45,29 @@ public: /** Call 6S main function */ static void ComputeAtmosphericParameters( - const double SolarZenithalAngle, /** The Solar zenithal angle */ - const double SolarAzimutalAngle, /** The Solar azimutal angle */ - const double ViewingZenithalAngle, /** The Viewing zenithal angle */ - const double ViewingAzimutalAngle, /** The Viewing azimutal angle */ - const unsigned int Month, /** The Month */ - const unsigned int Day, /** The Day (in the month) */ - const double AtmosphericPressure, /** The Atmospheric pressure */ - const double WaterVaporAmount, /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ - const double OzoneAmount, /** The Ozone amount (Stratospheric ozone layer content) */ - const AerosolModelType & AerosolModel, /** The Aerosol model */ - const double AerosolOptical, /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ - WavelenghtSpectralType* WavelenghtSpectralBand, /** Wavelenght for the spectral band definition */ - /** Note : The Max wavelenght spectral band value must be updated ! */ - double & AtmosphericReflectance, /** Atmospheric reflectance */ - double & AtmosphericSphericalAlbedo, /** atmospheric spherical albedo */ - double & TotalGaseousTransmission, /** Total gaseous transmission */ - double & DownwardTransmittance, /** downward transmittance */ - double & UpwardTransmittance, /** upward transmittance */ - double & UpwardDiffuseTransmittance, /** upward diffuse transmittance */ - double & UpwardDirectTransmittance, /** Upward direct transmittance */ - double & UpwardDiffuseTransmittanceForRayleigh, /** upward diffuse transmittance for rayleigh */ - double & UpwardDiffuseTransmittanceForAerosol /** upward diffuse transmittance for aerosols */ - ); + const double SolarZenithalAngle, /** The Solar zenithal angle */ + const double SolarAzimutalAngle, /** The Solar azimutal angle */ + const double ViewingZenithalAngle, /** The Viewing zenithal angle */ + const double ViewingAzimutalAngle, /** The Viewing azimutal angle */ + const unsigned int Month, /** The Month */ + const unsigned int Day, /** The Day (in the month) */ + const double AtmosphericPressure, /** The Atmospheric pressure */ + const double WaterVaporAmount, /** The Water vapor amount (Total water vapor content over vertical atmospheric column) */ + const double OzoneAmount, /** The Ozone amount (Stratospheric ozone layer content) */ + const AerosolModelType & AerosolModel, /** The Aerosol model */ + const double AerosolOptical, /** The Aerosol optical (radiative impact of aerosol for the reference wavelenght 550-nm) */ + WavelenghtSpectralType* WavelenghtSpectralBand, /** Wavelenght for the spectral band definition */ + /** Note : The Max wavelenght spectral band value must be updated ! */ + double & AtmosphericReflectance, /** Atmospheric reflectance */ + double & AtmosphericSphericalAlbedo, /** atmospheric spherical albedo */ + double & TotalGaseousTransmission, /** Total gaseous transmission */ + double & DownwardTransmittance, /** downward transmittance */ + double & UpwardTransmittance, /** upward transmittance */ + double & UpwardDiffuseTransmittance, /** upward diffuse transmittance */ + double & UpwardDirectTransmittance, /** Upward direct transmittance */ + double & UpwardDiffuseTransmittanceForRayleigh, /** upward diffuse transmittance for rayleigh */ + double & UpwardDiffuseTransmittanceForAerosol /** upward diffuse transmittance for aerosols */ + ); /** * Check the correpondance between the vector value size and @@ -78,18 +78,18 @@ public: * */ static void ComputeWavelenghtSpectralBandValuesFor6S( - const double SIXSStepOfWavelenghtSpectralBandValues, - WavelenghtSpectralType* WavelenghtSpectralBand - ); + const double SIXSStepOfWavelenghtSpectralBandValues, + WavelenghtSpectralType* WavelenghtSpectralBand + ); static void ComputeEnvironmentalContribution(const double diffuseTransmittanceForRayleighScattering, - const double diffuseTransmittanceForAerosolScattering, - const double radiusInKilometers, - const double altitude, - const double cosineOfViewingAngle, - double & rayleighEstimation, - double & aerosolEstimation, - double & globalEstimation); + const double diffuseTransmittanceForAerosolScattering, + const double radiusInKilometers, + const double altitude, + const double cosineOfViewingAngle, + double & rayleighEstimation, + double & aerosolEstimation, + double & globalEstimation); }; } // namespace otb diff --git a/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.h b/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.h index 6bb6d97be2a38773ac87a3fee364848437168c50..361e613a1da7fe44ba95e7f5d4e68e32f68e1552 100644 --- a/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.h +++ b/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.h @@ -1,22 +1,22 @@ - /*========================================================================= +/*========================================================================= - Program: ORFEO Toolbox - Language: C++ - Date: $Date$ - Version: $Revision$ + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ - Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. - See OTBCopyright.txt for details. + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. - Some parts of this code are derived from ITK. See ITKCopyright.txt - for details. + Some parts of this code are derived from ITK. See ITKCopyright.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. + 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 __otbSurfaceAdjencyEffect6SCorrectionSchemeFilter_h @@ -31,101 +31,119 @@ namespace otb { - namespace Functor - { - /** \class ComputeNeighborhoodContributionFunctor - * \brief Unary neighborhood functor to compute the value of a pixel which is a sum - * of the surrounding pixels value ponderated by a coefficient. - * - * \ingroup Functor - */ - template <class TNeighIter, class TOutput> - class ComputeNeighborhoodContributionFunctor +namespace Functor +{ +/** \class ComputeNeighborhoodContributionFunctor +* \brief Unary neighborhood functor to compute the value of a pixel which is a sum +* of the surrounding pixels value ponderated by a coefficient. +* +* \ingroup Functor +*/ +template <class TNeighIter, class TOutput> +class ComputeNeighborhoodContributionFunctor +{ +public: + ComputeNeighborhoodContributionFunctor() {}; + ~ComputeNeighborhoodContributionFunctor() {}; + + typedef itk::VariableSizeMatrix<double> WeightingMatrixType; + typedef typename std::vector<WeightingMatrixType> WeightingValuesContainerType; + typedef typename TOutput::RealValueType RealValueType; + typedef std::vector<double> DoubleContainerType; + + void SetWeightingValues(const WeightingValuesContainerType & cont) { - public: - ComputeNeighborhoodContributionFunctor() {}; - ~ComputeNeighborhoodContributionFunctor() {}; - - typedef itk::VariableSizeMatrix<double> WeightingMatrixType; - typedef typename std::vector<WeightingMatrixType> WeightingValuesContainerType; - typedef typename TOutput::RealValueType RealValueType; - typedef std::vector<double> DoubleContainerType; - - void SetWeightingValues(const WeightingValuesContainerType & cont){ m_WeightingValues = cont; }; - void SetUpwardTransmittanceRatio(DoubleContainerType upwardTransmittanceRatio){ m_UpwardTransmittanceRatio = upwardTransmittanceRatio;}; - void SetDiffuseRatio(DoubleContainerType diffuseRatio){ m_DiffuseRatio = diffuseRatio;}; - WeightingValuesContainerType GetWeightingValues(){ return m_WeightingValues;}; - DoubleContainerType GetUpwardTransmittanceRatio(){ return m_UpwardTransmittanceRatio;}; - DoubleContainerType GetDiffuseRatio(){ return m_DiffuseRatio;}; - - inline TOutput operator()(const TNeighIter & it) - { - unsigned int neighborhoodSize = it.Size(); - double contribution = 0.; - TOutput outPixel; - outPixel.SetSize(it.GetCenterPixel().Size()); + m_WeightingValues = cont; + }; + void SetUpwardTransmittanceRatio(DoubleContainerType upwardTransmittanceRatio) + { + m_UpwardTransmittanceRatio = upwardTransmittanceRatio; + }; + void SetDiffuseRatio(DoubleContainerType diffuseRatio) + { + m_DiffuseRatio = diffuseRatio; + }; + WeightingValuesContainerType GetWeightingValues() + { + return m_WeightingValues; + }; + DoubleContainerType GetUpwardTransmittanceRatio() + { + return m_UpwardTransmittanceRatio; + }; + DoubleContainerType GetDiffuseRatio() + { + return m_DiffuseRatio; + }; + + inline TOutput operator()(const TNeighIter & it) + { + unsigned int neighborhoodSize = it.Size(); + double contribution = 0.; + TOutput outPixel; + outPixel.SetSize(it.GetCenterPixel().Size()); - // Loop over each component - for (unsigned int j=0; j<outPixel.GetSize(); j++) + // Loop over each component + for (unsigned int j=0; j<outPixel.GetSize(); j++) { contribution = 0; // Load the current channel ponderation value matrix WeightingMatrixType TempChannelWeighting = m_WeightingValues[j]; // Loop over the neighborhood for (unsigned int i = 0; i < neighborhoodSize; ++i) - { - // Current neighborhood pixel index calculation - unsigned int RowIdx = 0; - unsigned int ColIdx = 0; - RowIdx = i/TempChannelWeighting.Cols(); - if(RowIdx != 0) - { - ColIdx = (i+1)-RowIdx*TempChannelWeighting.Cols()-1; - } - else { - ColIdx = i; - } - // Extract the current neighborhood pixel ponderation - double idVal = TempChannelWeighting(RowIdx, ColIdx); - // Extract the current neighborhood pixel value - TOutput tempPix = it.GetPixel(i); + // Current neighborhood pixel index calculation + unsigned int RowIdx = 0; + unsigned int ColIdx = 0; + RowIdx = i/TempChannelWeighting.Cols(); + if (RowIdx != 0) + { + ColIdx = (i+1)-RowIdx*TempChannelWeighting.Cols()-1; + } + else + { + ColIdx = i; + } + // Extract the current neighborhood pixel ponderation + double idVal = TempChannelWeighting(RowIdx, ColIdx); + // Extract the current neighborhood pixel value + TOutput tempPix = it.GetPixel(i); - contribution += static_cast<double>( tempPix[j] )*idVal; + contribution += static_cast<double>( tempPix[j] )*idVal; - } + } outPixel[j] = static_cast<RealValueType>(it.GetCenterPixel()[j])*m_UpwardTransmittanceRatio[j] + contribution*m_DiffuseRatio[j]; } - return outPixel; - } + return outPixel; + } - private: - WeightingValuesContainerType m_WeightingValues; - DoubleContainerType m_UpwardTransmittanceRatio; - DoubleContainerType m_DiffuseRatio; - }; +private: + WeightingValuesContainerType m_WeightingValues; + DoubleContainerType m_UpwardTransmittanceRatio; + DoubleContainerType m_DiffuseRatio; +}; - } +} - /** \class SurfaceAdjencyEffect6SCorrectionSchemeFilter - * \brief Correct the scheme taking care of the surrounding pixels. - * - * The SurfaceAdjencyEffect6SCorrectionSchemeFilter class allows to introduce a neighbor correction to the - * reflectance estimation. The satelite signal is considered as to be a combinaison of the signal coming from - * the target pixel and a weighting of the siganls coming from the neighbor pixels. - * - */ +/** \class SurfaceAdjencyEffect6SCorrectionSchemeFilter + * \brief Correct the scheme taking care of the surrounding pixels. + * + * The SurfaceAdjencyEffect6SCorrectionSchemeFilter class allows to introduce a neighbor correction to the + * reflectance estimation. The satelite signal is considered as to be a combinaison of the signal coming from + * the target pixel and a weighting of the siganls coming from the neighbor pixels. + * + */ template <class TInputImage, class TOutputImage> class ITK_EXPORT SurfaceAdjencyEffect6SCorrectionSchemeFilter : - public UnaryFunctorNeighborhoodImageFilter< TInputImage, - TOutputImage, - ITK_TYPENAME Functor::ComputeNeighborhoodContributionFunctor< itk::ConstNeighborhoodIterator<TInputImage>, - ITK_TYPENAME TOutputImage::PixelType > > + public UnaryFunctorNeighborhoodImageFilter< TInputImage, + TOutputImage, + ITK_TYPENAME Functor::ComputeNeighborhoodContributionFunctor< itk::ConstNeighborhoodIterator<TInputImage>, + ITK_TYPENAME TOutputImage::PixelType > > { public: /** "typedef" to simplify the variables definition and the declaration. */ typedef Functor::ComputeNeighborhoodContributionFunctor<itk::ConstNeighborhoodIterator<TInputImage>, - ITK_TYPENAME TOutputImage::PixelType> FunctorType; + ITK_TYPENAME TOutputImage::PixelType> FunctorType; /** "typedef" for standard classes. */ typedef SurfaceAdjencyEffect6SCorrectionSchemeFilter Self; @@ -143,7 +161,7 @@ public: /** return class name. */ itkTypeMacro(SurfaceAdjencyEffect6SCorrectionSchemeFilter, UnaryFunctorNeighborhoodImageFilter); -/** Extract input and output images dimensions.*/ + /** Extract input and output images dimensions.*/ itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension); itkStaticConstMacro( OutputImageDimension, unsigned int, TOutputImage::ImageDimension); @@ -166,13 +184,13 @@ public: /** typedef for calculation*/ typedef typename itk::ConstNeighborhoodIterator<InputImageType> NeighborIterType; - /** Set/Get the Size of the neighbor window. */ + /** Set/Get the Size of the neighbor window. */ void SetWindowRadius(unsigned int rad) - { - this->SetRadius(rad); - m_WindowRadius = rad; - this->Modified(); - } + { + this->SetRadius(rad); + m_WindowRadius = rad; + this->Modified(); + } itkGetConstReferenceMacro(WindowRadius, unsigned int); /** Set/Get the pixel spacing in kilometers */ @@ -184,23 +202,23 @@ public: /** Get/Set Atmospheric Radiative Terms. */ void SetAtmosphericRadiativeTerms(AtmosphericRadiativeTermsPointerType atmo) - { - m_AtmosphericRadiativeTerms = atmo; - this->SetNthInput(1, m_AtmosphericRadiativeTerms); - this->Modified(); - } + { + m_AtmosphericRadiativeTerms = atmo; + this->SetNthInput(1, m_AtmosphericRadiativeTerms); + this->Modified(); + } AtmosphericRadiativeTermsPointerType GetAtmosphericRadiativeTerms() - { - return m_AtmosphericRadiativeTerms; - } + { + return m_AtmosphericRadiativeTerms; + } /** Compute the functor parameters */ void ComputeParameters(); - protected: +protected: SurfaceAdjencyEffect6SCorrectionSchemeFilter(); - virtual ~SurfaceAdjencyEffect6SCorrectionSchemeFilter(){}; + virtual ~SurfaceAdjencyEffect6SCorrectionSchemeFilter() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; /** GenerateOutputInformation method */ diff --git a/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.txx b/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.txx index e1b0d1ed5a25f0c10736ed70ddfa25094faf7713..a13fa92c637e16bfe43ca9092f8299aa18ef49c4 100644 --- a/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.txx +++ b/Code/Radiometry/otbSurfaceAdjencyEffect6SCorrectionSchemeFilter.txx @@ -58,7 +58,7 @@ SurfaceAdjencyEffect6SCorrectionSchemeFilter<TInputImage, TOutputImage> typename InputImageType::Pointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); typename OutputImageType::Pointer outputPtr = const_cast< TOutputImage * >( this->GetOutput() ); - if(!inputPtr || !outputPtr) + if (!inputPtr || !outputPtr) return; outputPtr->SetNumberOfComponentsPerPixel(inputPtr->GetNumberOfComponentsPerPixel()); } @@ -77,11 +77,11 @@ void SurfaceAdjencyEffect6SCorrectionSchemeFilter<TInputImage, TOutputImage> ::BeforeThreadedGenerateData () { - if(!m_ParametersHaveBeenComputed) - { - this->ComputeParameters(); - m_ParametersHaveBeenComputed = true; - } + if (!m_ParametersHaveBeenComputed) + { + this->ComputeParameters(); + m_ParametersHaveBeenComputed = true; + } } template <class TInputImage, class TOutputImage> @@ -99,31 +99,31 @@ SurfaceAdjencyEffect6SCorrectionSchemeFilter<TInputImage, TOutputImage> double center = static_cast<double>(m_WindowRadius); - for(unsigned int i = 0; i<m_WindowRadius+1; ++i) - { - for(unsigned int j = 0; j<m_WindowRadius+1; ++j) + for (unsigned int i = 0; i<m_WindowRadius+1; ++i) { - double id = static_cast<double>(i); - double jd = static_cast<double>(j); - double currentRadius = m_PixelSpacingInKilometers*vcl_sqrt(vcl_pow(id-center,2)+vcl_pow(jd-center,2)); - radiusMatrix(i,j)=currentRadius; - radiusMatrix(2*m_WindowRadius-i,j)=currentRadius; - radiusMatrix(2*m_WindowRadius-i,2*m_WindowRadius-j)=currentRadius; - radiusMatrix(i,2*m_WindowRadius-j)=currentRadius; - } + for (unsigned int j = 0; j<m_WindowRadius+1; ++j) + { + double id = static_cast<double>(i); + double jd = static_cast<double>(j); + double currentRadius = m_PixelSpacingInKilometers*vcl_sqrt(vcl_pow(id-center,2)+vcl_pow(jd-center,2)); + radiusMatrix(i,j)=currentRadius; + radiusMatrix(2*m_WindowRadius-i,j)=currentRadius; + radiusMatrix(2*m_WindowRadius-i,2*m_WindowRadius-j)=currentRadius; + radiusMatrix(i,2*m_WindowRadius-j)=currentRadius; } + } - for(unsigned int band = 0; band<inputPtr->GetNumberOfComponentsPerPixel();++band) - { - WeightingMatrixType currentWeightingMatrix(2*m_WindowRadius+1,2*m_WindowRadius+1); - double rayleigh = m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittanceForRayleigh(band); - double aerosol = m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittanceForAerosol(band); + for (unsigned int band = 0; band<inputPtr->GetNumberOfComponentsPerPixel();++band) + { + WeightingMatrixType currentWeightingMatrix(2*m_WindowRadius+1,2*m_WindowRadius+1); + double rayleigh = m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittanceForRayleigh(band); + double aerosol = m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittanceForAerosol(band); - currentWeightingMatrix.Fill(0.); + currentWeightingMatrix.Fill(0.); - for(unsigned int i = 0; i<2*m_WindowRadius+1; ++i) - { - for(unsigned int j = 0; j<2*m_WindowRadius+1; ++j) + for (unsigned int i = 0; i<2*m_WindowRadius+1; ++i) + { + for (unsigned int j = 0; j<2*m_WindowRadius+1; ++j) { double notUsed1,notUsed2; double factor = 1; @@ -131,18 +131,18 @@ SurfaceAdjencyEffect6SCorrectionSchemeFilter<TInputImage, TOutputImage> SIXSTraits::ComputeEnvironmentalContribution(rayleigh,aerosol,radiusMatrix(i,j),palt,vcl_cos(m_ZenithalViewingAngle*M_PI/180.),notUsed1,notUsed2,factor); //Call to 6S currentWeightingMatrix(i,j)=factor; } - } - m_WeightingValues.push_back(currentWeightingMatrix); } + m_WeightingValues.push_back(currentWeightingMatrix); + } DoubleContainerType upwardTransmittanceRatio,diffuseRatio; - for(unsigned int band = 0; band<inputPtr->GetNumberOfComponentsPerPixel();++band) - { - upwardTransmittanceRatio.push_back(m_AtmosphericRadiativeTerms->GetUpwardTransmittance(band)/m_AtmosphericRadiativeTerms->GetUpwardDirectTransmittance(band)); - diffuseRatio .push_back(m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittance(band)/m_AtmosphericRadiativeTerms->GetUpwardDirectTransmittance(band)); - } + for (unsigned int band = 0; band<inputPtr->GetNumberOfComponentsPerPixel();++band) + { + upwardTransmittanceRatio.push_back(m_AtmosphericRadiativeTerms->GetUpwardTransmittance(band)/m_AtmosphericRadiativeTerms->GetUpwardDirectTransmittance(band)); + diffuseRatio .push_back(m_AtmosphericRadiativeTerms->GetUpwardDiffuseTransmittance(band)/m_AtmosphericRadiativeTerms->GetUpwardDirectTransmittance(band)); + } this->GetFunctor().SetUpwardTransmittanceRatio(upwardTransmittanceRatio); this->GetFunctor().SetDiffuseRatio(diffuseRatio); this->GetFunctor().SetWeightingValues(m_WeightingValues); diff --git a/Code/Radiometry/otbVegetationIndex.h b/Code/Radiometry/otbVegetationIndex.h index cf6659197ae105e14c68cbf93549eee5b8b4092a..2dc621a2800f5e74e4fc286a8363fc7058fb5559 100644 --- a/Code/Radiometry/otbVegetationIndex.h +++ b/Code/Radiometry/otbVegetationIndex.h @@ -23,240 +23,279 @@ namespace otb { namespace Functor - { - /** \class NDVI - * \brief This functor calculate the NormalizeD Vegetation Index (NDVI) - * - * [Pearson et Miller, 1972] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class NDVI - { - public: +{ +/** \class NDVI + * \brief This functor calculate the NormalizeD Vegetation Index (NDVI) + * + * [Pearson et Miller, 1972] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class NDVI +{ +public: NDVI() {}; ~NDVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dr = static_cast<double>(r); - double dnir = static_cast<double>(nir); - if( (nir + r) == 0 ) - { - return static_cast<TOutput>(0.); - } + double dr = static_cast<double>(r); + double dnir = static_cast<double>(nir); + if ( (nir + r) == 0 ) + { + return static_cast<TOutput>(0.); + } - return ( static_cast<TOutput>((dnir-dr)/(dnir+dr))); + return ( static_cast<TOutput>((dnir-dr)/(dnir+dr))); } - }; +}; - /** \class RVI - * \brief This functor calculate the Ratio Vegetation Index (RVI) - * - * [Rouse et al., 1973] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class RVI - { - public: +/** \class RVI + * \brief This functor calculate the Ratio Vegetation Index (RVI) + * + * [Rouse et al., 1973] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class RVI +{ +public: RVI() {}; ~RVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dr = static_cast<double>(r); - double dnir = static_cast<double>(nir); - if( r == 0 ) - { - return static_cast<TOutput>(0.); - } - return ( static_cast<TOutput>(dnir/dr)); + double dr = static_cast<double>(r); + double dnir = static_cast<double>(nir); + if ( r == 0 ) + { + return static_cast<TOutput>(0.); + } + return ( static_cast<TOutput>(dnir/dr)); } - }; - /** \class PVI - * \brief This functor calculate the Perpendicular Vegetation Index (PVI) - * - * [Richardson et Wiegand, 1977] - * - * \ingroup Functor2 - */ - template <class TInput1, class TInput2, class TOutput> - class PVI - { - public: +}; +/** \class PVI + * \brief This functor calculate the Perpendicular Vegetation Index (PVI) + * + * [Richardson et Wiegand, 1977] + * + * \ingroup Functor2 + */ +template <class TInput1, class TInput2, class TOutput> +class PVI +{ +public: PVI() {}; ~PVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dnir = static_cast<double>(nir); - double dr = static_cast<double>(r); - return ( static_cast<TOutput>( (dnir - m_A*dr - m_B)*m_Coeff) ); - } - /** Set/Get A and B parameters */ - void SetA(const double A) - { - m_A = A; - m_Coeff = 1./(vcl_sqrt(m_A*m_A + 1.)); - } - double GetA(void)const { return ( m_A ); } - void SetB(const double B) { m_B = B; } - double GetB(void)const { return ( m_B ); } + double dnir = static_cast<double>(nir); + double dr = static_cast<double>(r); + return ( static_cast<TOutput>( (dnir - m_A*dr - m_B)*m_Coeff) ); + } + /** Set/Get A and B parameters */ + void SetA(const double A) + { + m_A = A; + m_Coeff = 1./(vcl_sqrt(m_A*m_A + 1.)); + } + double GetA(void)const + { + return ( m_A ); + } + void SetB(const double B) + { + m_B = B; + } + double GetB(void)const + { + return ( m_B ); + } - private: +private: - /** A and B parameters */ - double m_A; - double m_B; - /** Denominator, pre-calculed when the A variable is set */ - double m_Coeff; + /** A and B parameters */ + double m_A; + double m_B; + /** Denominator, pre-calculed when the A variable is set */ + double m_Coeff; - }; +}; - /** \class SAVI - * \brief This functor calculate the Soil Adjusted Vegetation Index (SAVI) - * - * [Huete, 1988] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class SAVI - { - public: +/** \class SAVI + * \brief This functor calculate the Soil Adjusted Vegetation Index (SAVI) + * + * [Huete, 1988] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class SAVI +{ +public: SAVI() : m_L(0.5) {}; ~SAVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dnir = static_cast<double>(nir); - double dr = static_cast<double>(r); - double denominator = dnir + dr + m_L; - if( denominator == 0. ) - { - return static_cast<TOutput>(0.); - } - return ( static_cast<TOutput>( ((dnir-dr)*(1+m_L))/denominator ) ); - } - /** Set/Get L correction */ - void SetL(const double L) { m_L = L; } - double GetL(void)const { return ( m_L ); } + double dnir = static_cast<double>(nir); + double dr = static_cast<double>(r); + double denominator = dnir + dr + m_L; + if ( denominator == 0. ) + { + return static_cast<TOutput>(0.); + } + return ( static_cast<TOutput>( ((dnir-dr)*(1+m_L))/denominator ) ); + } + /** Set/Get L correction */ + void SetL(const double L) + { + m_L = L; + } + double GetL(void)const + { + return ( m_L ); + } - private: +private: - /** L correction */ - double m_L; + /** L correction */ + double m_L; - }; - /** \class TSAVI - * \brief This functor calculate the Transformed Soil Adjusted Vegetation Index (TSAVI) - * - * [Baret et al. 1989, Baret et Guyot, 1991] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class TSAVI - { - public: +}; +/** \class TSAVI + * \brief This functor calculate the Transformed Soil Adjusted Vegetation Index (TSAVI) + * + * [Baret et al. 1989, Baret et Guyot, 1991] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class TSAVI +{ +public: TSAVI() : m_X(0.08) {}; ~TSAVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dnir = static_cast<double>(nir); - double dr = static_cast<double>(r); - double denominator = m_A*dnir + dr + m_X*(1.+m_A*m_A); - if( denominator == 0. ) - { - return static_cast<TOutput>(0.); - } - return ( static_cast<TOutput>( (m_A*(dnir - m_A*dr - m_B))/denominator ) ); - } - /** Set/Get A and B parameters */ - void SetA(const double A) { m_A = A; } - double GetA(void)const { return (m_A); } - void SetB(const double B) { m_B = B; } - double GetB(void)const { return (m_B); } - /** Set/Get X parameter */ - void SetX(const double X) { m_X = X; } - double GetX(void)const { return (m_X); } + double dnir = static_cast<double>(nir); + double dr = static_cast<double>(r); + double denominator = m_A*dnir + dr + m_X*(1.+m_A*m_A); + if ( denominator == 0. ) + { + return static_cast<TOutput>(0.); + } + return ( static_cast<TOutput>( (m_A*(dnir - m_A*dr - m_B))/denominator ) ); + } + /** Set/Get A and B parameters */ + void SetA(const double A) + { + m_A = A; + } + double GetA(void)const + { + return (m_A); + } + void SetB(const double B) + { + m_B = B; + } + double GetB(void)const + { + return (m_B); + } + /** Set/Get X parameter */ + void SetX(const double X) + { + m_X = X; + } + double GetX(void)const + { + return (m_X); + } - private: +private: - /** A and B parameters */ - double m_A; - double m_B; - /** X parameter */ - double m_X; + /** A and B parameters */ + double m_A; + double m_B; + /** X parameter */ + double m_X; - }; +}; - /** \class MSAVI - * \brief This functor calculate the Modified Soil Adjusted Vegetation Index (MSAVI) - * - * [Qi et al., 1994] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TOutput> - class MSAVI - { - public: +/** \class MSAVI + * \brief This functor calculate the Modified Soil Adjusted Vegetation Index (MSAVI) + * + * [Qi et al., 1994] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TOutput> +class MSAVI +{ +public: MSAVI() {}; ~MSAVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &nir) { - double dnir = static_cast<double>(nir); - double dr = static_cast<double>(r); - double sqrt_value = (2*dr+1)*(2*dr+1) - 8*(dr-dnir); - if( sqrt_value < 0. ) - { - return static_cast<TOutput>(0.); - } - return ( static_cast<TOutput>( (2*dr + 1 - vcl_sqrt(sqrt_value))/2. ) ); - } + double dnir = static_cast<double>(nir); + double dr = static_cast<double>(r); + double sqrt_value = (2*dr+1)*(2*dr+1) - 8*(dr-dnir); + if ( sqrt_value < 0. ) + { + return static_cast<TOutput>(0.); + } + return ( static_cast<TOutput>( (2*dr + 1 - vcl_sqrt(sqrt_value))/2. ) ); + } - }; +}; - /** \class ARVI - * \brief This functor calculate the Atmospherically Resistant Vegetation Index (ARVI) - * - * This vegetation index use three inputs channels - * - * [Yoram J. Kaufman and Didier Tanré, 1992] - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TInput3, class TOutput> - class ARVI - { - public: +/** \class ARVI + * \brief This functor calculate the Atmospherically Resistant Vegetation Index (ARVI) + * + * This vegetation index use three inputs channels + * + * [Yoram J. Kaufman and Didier Tanré, 1992] + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TInput3, class TOutput> +class ARVI +{ +public: ARVI() : m_Gamma(0.5) {}; ~ARVI() {}; inline TOutput operator()(const TInput1 &r, const TInput2 &b, const TInput3 &nir) { - double dr = static_cast<double>(r); - double db = static_cast<double>(b); - double dnir = static_cast<double>(nir); - double RHOrb = dr - m_Gamma*(db - dr); - double denominator = dnir + RHOrb; - if( denominator == 0. ) - { - return static_cast<TOutput>(0.); - } - return ( static_cast<TOutput>( (dnir - RHOrb)/denominator ) ); - } - /** Set/Get Gamma parameter */ - void SetGamma(const double gamma) { m_Gamma = gamma; } - double GetGamma(void)const { return (m_Gamma); } + double dr = static_cast<double>(r); + double db = static_cast<double>(b); + double dnir = static_cast<double>(nir); + double RHOrb = dr - m_Gamma*(db - dr); + double denominator = dnir + RHOrb; + if ( denominator == 0. ) + { + return static_cast<TOutput>(0.); + } + return ( static_cast<TOutput>( (dnir - RHOrb)/denominator ) ); + } + /** Set/Get Gamma parameter */ + void SetGamma(const double gamma) + { + m_Gamma = gamma; + } + double GetGamma(void)const + { + return (m_Gamma); + } - private: +private: - /** Gamma parameter */ - double m_Gamma; - }; + /** Gamma parameter */ + double m_Gamma; +}; - } // namespace Functor +} // namespace Functor } // namespace otb #endif diff --git a/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.h b/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.h index e53c7336ee5546bd7649d315ba301168ab833d4f..2db946380839a6be43a7d0a8cdde804acaf2ed9d 100644 --- a/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.h +++ b/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.h @@ -35,12 +35,12 @@ namespace otb */ template <class TInputImage, class TOutputImage, - class TFunction = Functor::PolarimetricSynthesisFunctor< - typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TInputImage::InternalPixelType, - typename TOutputImage::PixelType> > +class TFunction = Functor::PolarimetricSynthesisFunctor< +typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TInputImage::InternalPixelType, +typename TOutputImage::PixelType> > class ITK_EXPORT MultiChannelsPolarimetricSynthesisFilter : public itk::InPlaceImageFilter<TInputImage,TOutputImage> { public: @@ -77,8 +77,14 @@ public: * (Functors do not have to derive from itk::LightObject, so they do * not necessarily have a reference count. So we cannot return a * SmartPointer.) */ - FunctorType& GetFunctor() { return m_Functor; }; - const FunctorType& GetFunctor() const { return m_Functor; }; + FunctorType& GetFunctor() + { + return m_Functor; + }; + const FunctorType& GetFunctor() const + { + return m_Functor; + }; /** Set the functor object. This replaces the current Functor with a @@ -90,24 +96,24 @@ public: void SetFunctor(const FunctorType& functor) { if (m_Functor != functor) - { + { m_Functor = functor; this->Modified(); - } + } } /** Set the Incident ElectroMagneticField */ void SetEi(ComplexArrayType ei) { - m_Ei = ei; - this->GetFunctor().SetEi(ei); - this->Modified(); + m_Ei = ei; + this->GetFunctor().SetEi(ei); + this->Modified(); } /** Set the Reflected ElectroMagneticField */ void SetEr(ComplexArrayType er) { - m_Er = er; - this->GetFunctor().SetEr(er); - this->Modified(); + m_Er = er; + this->GetFunctor().SetEr(er); + this->Modified(); } /** Set/Get PsiI */ @@ -144,7 +150,7 @@ protected: /** Constructor */ MultiChannelsPolarimetricSynthesisFilter(); /** Destructor */ - virtual ~MultiChannelsPolarimetricSynthesisFilter(){}; + virtual ~MultiChannelsPolarimetricSynthesisFilter() {}; /** MultiChannelsPolarimetricSynthesisFilter can produce an image * which is a synthesis of channels HH, HV, VH and VV. diff --git a/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.txx b/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.txx index 0be0d91c2c6ff6252662b44291cd41a217e0a070..0dc659735ece17574c9c6087807233e7ba6c9b8c 100644 --- a/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.txx +++ b/Code/SARPolarimetry/otbMultiChannelsPolarimetricSynthesisFilter.txx @@ -42,9 +42,9 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> m_ArchitectureType = PolarimetricData::New(); } - /** - * GenerateOutputInformation() - */ +/** + * GenerateOutputInformation() + */ template <class TInputImage, class TOutputImage, class TFunction> void MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> @@ -58,9 +58,9 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); if ( !outputPtr || !inputPtr) - { + { return; - } + } // Set the output image largest possible region. Use a RegionCopier // so that the input and output images can be different dimensions. @@ -73,20 +73,20 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> const itk::ImageBase<Superclass::InputImageDimension> *phyData; phyData - = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); + = dynamic_cast<const itk::ImageBase<Superclass::InputImageDimension>*>(this->GetInput()); if (phyData) - { + { // Copy what we can from the image from spacing and origin of the input // This logic needs to be augmented with logic that select which // dimensions to copy unsigned int i, j; const typename InputImageType::SpacingType& - inputSpacing = inputPtr->GetSpacing(); + inputSpacing = inputPtr->GetSpacing(); const typename InputImageType::PointType& - inputOrigin = inputPtr->GetOrigin(); + inputOrigin = inputPtr->GetOrigin(); const typename InputImageType::DirectionType& - inputDirection = inputPtr->GetDirection(); + inputDirection = inputPtr->GetDirection(); typename OutputImageType::SpacingType outputSpacing; typename OutputImageType::PointType outputOrigin; @@ -95,51 +95,51 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> // copy the input to the output and fill the rest of the // output with zeros. for (i=0; i < Superclass::InputImageDimension; ++i) - { + { outputSpacing[i] = inputSpacing[i]; outputOrigin[i] = inputOrigin[i]; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j < Superclass::InputImageDimension) - { + { outputDirection[j][i] = inputDirection[j][i]; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } for (; i < Superclass::OutputImageDimension; ++i) - { + { outputSpacing[i] = 1.0; outputOrigin[i] = 0.0; for (j=0; j < Superclass::OutputImageDimension; j++) - { + { if (j == i) - { + { outputDirection[j][i] = 1.0; - } + } else - { + { outputDirection[j][i] = 0.0; - } } } + } // set the spacing and origin outputPtr->SetSpacing( outputSpacing ); outputPtr->SetOrigin( outputOrigin ); outputPtr->SetDirection( outputDirection ); - } + } else - { + { // pointer could not be cast back down itkExceptionMacro(<< "otb::MultiChannelsPolarimetricSynthesisFilter::GenerateOutputInformation " << "cannot cast input to " << typeid(itk::ImageBase<Superclass::InputImageDimension>*).name() ); - } + } } @@ -176,54 +176,54 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> // Computation with 4 channels switch (val) { - case HH_HV_VH_VV : - while( !inputIt.IsAtEnd() ) - { - outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], - inputIt.Get()[2], inputIt.Get()[3] ) ); - ++inputIt; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - - // With 3 channels : HH HV VV ou HH VH VV - case HH_HV_VV : - while( !inputIt.IsAtEnd() ) - { - outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], - inputIt.Get()[1], inputIt.Get()[2] ) ); - ++inputIt; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - - // Only HH and HV are present - case HH_HV : - while( !inputIt.IsAtEnd() ) - { - outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], 0, 0 ) ); - ++inputIt; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - - // Only VH and VV are present - case VH_VV : - while( !inputIt.IsAtEnd() ) - { - outputIt.Set( m_Gain * GetFunctor()( 0, 0, inputIt.Get()[2], inputIt.Get()[3] ) ); - ++inputIt; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - - default : - itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); - return; + case HH_HV_VH_VV : + while ( !inputIt.IsAtEnd() ) + { + outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], + inputIt.Get()[2], inputIt.Get()[3] ) ); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + + // With 3 channels : HH HV VV ou HH VH VV + case HH_HV_VV : + while ( !inputIt.IsAtEnd() ) + { + outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], + inputIt.Get()[1], inputIt.Get()[2] ) ); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + + // Only HH and HV are present + case HH_HV : + while ( !inputIt.IsAtEnd() ) + { + outputIt.Set( m_Gain * GetFunctor()( inputIt.Get()[0], inputIt.Get()[1], 0, 0 ) ); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + + // Only VH and VV are present + case VH_VV : + while ( !inputIt.IsAtEnd() ) + { + outputIt.Set( m_Gain * GetFunctor()( 0, 0, inputIt.Get()[2], inputIt.Get()[3] ) ); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + + default : + itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); + return; } } @@ -279,38 +279,38 @@ MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> ArchitectureType val = m_ArchitectureType->GetArchitectureType(); - switch(val) - { + switch (val) + { - case HH_HV_VH_VV : - break; - case HH_HV_VV : - break; - case HH_VH_VV : - break; - // Only HH and HV are present - case HH_HV : - - // Forcing KhiI=0 PsiI=0 - this->SetKhiI(0); - this->SetPsiI(0); - break; - - // Only VH and VV are present - case VH_VV : - - // Forcing KhiI=0 PsiI=90 - this->SetKhiI(0); - this->SetPsiI(90); - break; - - default : - itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !!"); - return; - } + case HH_HV_VH_VV : + break; + case HH_HV_VV : + break; + case HH_VH_VV : + break; + // Only HH and HV are present + case HH_HV : + + // Forcing KhiI=0 PsiI=0 + this->SetKhiI(0); + this->SetPsiI(0); + break; + + // Only VH and VV are present + case VH_VV : + + // Forcing KhiI=0 PsiI=90 + this->SetKhiI(0); + this->SetPsiI(90); + break; + + default : + itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !!"); + return; + } - if(GetMode()==1)ForceCoPolar(); - else if(GetMode()==2)ForceCrossPolar(); + if (GetMode()==1)ForceCoPolar(); + else if (GetMode()==2)ForceCrossPolar(); } @@ -344,8 +344,8 @@ void MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> ::ForceCoPolar() { - SetPsiR(m_PsiI); - SetKhiR(m_KhiI); + SetPsiR(m_PsiI); + SetKhiR(m_KhiI); } /** @@ -356,9 +356,9 @@ void MultiChannelsPolarimetricSynthesisFilter<TInputImage,TOutputImage,TFunction> ::ForceCrossPolar() { - SetPsiR(m_PsiI+90); - SetKhiR(-m_KhiI); - SetMode(2); + SetPsiR(m_PsiI+90); + SetKhiR(-m_KhiI); + SetMode(2); } /** diff --git a/Code/SARPolarimetry/otbPolarimetricData.cxx b/Code/SARPolarimetry/otbPolarimetricData.cxx index d158c44bfa97851135d36c191156e63171dd2b47..a8a76a4ea833b28ab6290d6e943027867ea0a153 100644 --- a/Code/SARPolarimetry/otbPolarimetricData.cxx +++ b/Code/SARPolarimetry/otbPolarimetricData.cxx @@ -39,43 +39,43 @@ PolarimetricData // With all the channels if ( IsPresent[0] && IsPresent[1] && IsPresent[2] && IsPresent[3] ) - { - SetArchitectureType(HH_HV_VH_VV); - } - else - // With 3 channels : HH HV VV - if ( IsPresent[0] && IsPresent[1] && !IsPresent[2] && IsPresent[3] ) { - SetArchitectureType(HH_HV_VV); + SetArchitectureType(HH_HV_VH_VV); } else - // With 3 channels : HH VH VV - if ( IsPresent[0] && !IsPresent[1] && IsPresent[2] && IsPresent[3] ) - { - SetArchitectureType(HH_VH_VV); - } - else - // Only HH and HV are present - if ( IsPresent[0] && IsPresent[1] && !IsPresent[2] && !IsPresent[3] ) + // With 3 channels : HH HV VV + if ( IsPresent[0] && IsPresent[1] && !IsPresent[2] && IsPresent[3] ) { - SetArchitectureType(HH_HV); - } - else - // Only VH and VV are present - if ( !IsPresent[0] && !IsPresent[1] && IsPresent[2] && IsPresent[3] ) - { - SetArchitectureType(VH_VV); - } - else - // Only HH and VV are present - if ( IsPresent[0] && !IsPresent[1] && !IsPresent[2] && IsPresent[3] ) - { - SetArchitectureType(HH_VV); - } - else - { - SetArchitectureType(UNKNOWN); - } + SetArchitectureType(HH_HV_VV); + } + else + // With 3 channels : HH VH VV + if ( IsPresent[0] && !IsPresent[1] && IsPresent[2] && IsPresent[3] ) + { + SetArchitectureType(HH_VH_VV); + } + else + // Only HH and HV are present + if ( IsPresent[0] && IsPresent[1] && !IsPresent[2] && !IsPresent[3] ) + { + SetArchitectureType(HH_HV); + } + else + // Only VH and VV are present + if ( !IsPresent[0] && !IsPresent[1] && IsPresent[2] && IsPresent[3] ) + { + SetArchitectureType(VH_VV); + } + else + // Only HH and VV are present + if ( IsPresent[0] && !IsPresent[1] && !IsPresent[2] && IsPresent[3] ) + { + SetArchitectureType(HH_VV); + } + else + { + SetArchitectureType(UNKNOWN); + } } void @@ -83,32 +83,32 @@ PolarimetricData ::DetermineArchitecture(int NumberOfImages, bool EmissionH,bool EmissionV) { - switch(NumberOfImages) - { - case 4 : - SetArchitectureType(HH_HV_VH_VV); - break; + switch (NumberOfImages) + { + case 4 : + SetArchitectureType(HH_HV_VH_VV); + break; - case 3: - SetArchitectureType(HH_HV_VV); - break; + case 3: + SetArchitectureType(HH_HV_VV); + break; - case 2 : + case 2 : - if (EmissionH && !EmissionV ) - { - SetArchitectureType(HH_HV); - } - else if (!EmissionH && EmissionV ) - { - SetArchitectureType(VH_VV); - } - break; - - default: - itkExceptionMacro("Unknown architecture !"); - return; + if (EmissionH && !EmissionV ) + { + SetArchitectureType(HH_HV); } + else if (!EmissionH && EmissionV ) + { + SetArchitectureType(VH_VV); + } + break; + + default: + itkExceptionMacro("Unknown architecture !"); + return; + } } @@ -117,7 +117,7 @@ void PolarimetricData ::PrintSelf(std::ostream& os, itk::Indent indent) const { - os << indent << "ArchitectureType "<< m_ArchitectureType<< " : "<< std::endl; + os << indent << "ArchitectureType "<< m_ArchitectureType<< " : "<< std::endl; } } // end namespace otb diff --git a/Code/SARPolarimetry/otbPolarimetricData.h b/Code/SARPolarimetry/otbPolarimetricData.h index d9965a05b6d2e26b02a1a93587985a5810396b1d..8cfb7b72cafc2352b75cd94127a142642ab293c2 100644 --- a/Code/SARPolarimetry/otbPolarimetricData.h +++ b/Code/SARPolarimetry/otbPolarimetricData.h @@ -27,26 +27,28 @@ namespace otb /** * This enumeration describes the different architectures we can find in polarimetry. */ - typedef enum { - HH_HV_VH_VV=0, - HH_HV_VV=1, - HH_VH_VV=2, - HH_HV=3, - VH_VV=4, - HH_VV=5, - UNKNOWN=6} ArchitectureType; - - - /** \class PolarimetricData - * \brief This class allows to determine the type of architecture we get. - * - * - * \sa - */ +typedef enum +{ + HH_HV_VH_VV=0, + HH_HV_VV=1, + HH_VH_VV=2, + HH_HV=3, + VH_VV=4, + HH_VV=5, + UNKNOWN=6 +} ArchitectureType; + + +/** \class PolarimetricData +* \brief This class allows to determine the type of architecture we get. +* +* +* \sa +*/ class ITK_EXPORT PolarimetricData : public itk::DataObject { - public: +public: /** Standard typedefs */ typedef PolarimetricData Self; @@ -68,16 +70,16 @@ class ITK_EXPORT PolarimetricData : public itk::DataObject itkSetMacro(ArchitectureType,ArchitectureType); itkGetMacro(ArchitectureType,ArchitectureType); - protected: +protected: /** Constructor */ PolarimetricData(); /** Destructor */ - ~PolarimetricData(){}; + ~PolarimetricData() {}; /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: PolarimetricData(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.h b/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.h index e6971c609f29aac3fd506f753adaabcd951ad8d4..a3b6872d19528ba286a7b5bfa23a9b2b1cca30ea 100644 --- a/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.h +++ b/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.h @@ -59,21 +59,21 @@ namespace otb */ template <class TInputImageHH,class TInputImageHV,class TInputImageVH,class TInputImageVV,class TOutputImage, - class TFunction = Functor::PolarimetricSynthesisFunctor< - typename TInputImageHH::PixelType, - typename TInputImageHV::PixelType, - typename TInputImageVH::PixelType, - typename TInputImageVV::PixelType, - typename TOutputImage::PixelType > > +class TFunction = Functor::PolarimetricSynthesisFunctor< +typename TInputImageHH::PixelType, +typename TInputImageHV::PixelType, +typename TInputImageVH::PixelType, +typename TInputImageVV::PixelType, +typename TOutputImage::PixelType > > class ITK_EXPORT PolarimetricSynthesisFilter : public otb::QuaternaryFunctorImageFilter< TInputImageHH, - TInputImageHV, TInputImageVH, TInputImageVV, TOutputImage, TFunction > + TInputImageHV, TInputImageVH, TInputImageVV, TOutputImage, TFunction > { public: /** Standard typedefs */ typedef PolarimetricSynthesisFilter Self; typedef otb::QuaternaryFunctorImageFilter< TInputImageHH, TInputImageHV, - TInputImageVH, TInputImageVV, TOutputImage, TFunction > Superclass; + TInputImageVH, TInputImageVV, TOutputImage, TFunction > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -126,16 +126,16 @@ public: /** Set the ElectroMagneticField Incident */ void SetEi(ComplexArrayType ei) { - m_Ei = ei; - this->GetFunctor().SetEi(ei); - this->Modified(); + m_Ei = ei; + this->GetFunctor().SetEi(ei); + this->Modified(); } /** Set the ElectroMagneticField Reflected */ void SetEr(ComplexArrayType er) { - m_Er = er; - this->GetFunctor().SetEr(er); - this->Modified(); + m_Er = er; + this->GetFunctor().SetEr(er); + this->Modified(); } /** Force the copolar mode */ void ForceCoPolar(); @@ -159,7 +159,7 @@ protected: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, - int threadId ); + int threadId ); /** Computation of the electromagnetic fields Ei Er */ void ComputeElectromagneticFields(); diff --git a/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.txx b/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.txx index 69cf6e1b5244a0e882f58ddabf9a6211408ef24b..1fe1855688b09b3ea28b6c28b82a252d0b36fda9 100644 --- a/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.txx +++ b/Code/SARPolarimetry/otbPolarimetricSynthesisFilter.txx @@ -48,18 +48,18 @@ PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImag ::GenerateOutputInformation() { // if HH is set, use HH to generate output information - if(m_PresentInputImages[0]) + if (m_PresentInputImages[0]) { - this->GetOutput()->CopyInformation(this->GetInput(0)); + this->GetOutput()->CopyInformation(this->GetInput(0)); } // else, use VH - else if(m_PresentInputImages[2]) + else if (m_PresentInputImages[2]) { - this->GetOutput()->CopyInformation(this->GetInput(2)); + this->GetOutput()->CopyInformation(this->GetInput(2)); } else { - itkExceptionMacro(<<"Bad input polarization images: neither HH image nor VH image is set!"); + itkExceptionMacro(<<"Bad input polarization images: neither HH image nor VH image is set!"); } } @@ -146,9 +146,9 @@ void PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImageVV,TOutputImage,TFunction> ::ForceCoPolar() { - SetPsiR(m_PsiI); - SetKhiR(m_KhiI); - SetMode(1); + SetPsiR(m_PsiI); + SetKhiR(m_KhiI); + SetMode(1); } /** @@ -159,9 +159,9 @@ void PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImageVV,TOutputImage,TFunction> ::ForceCrossPolar() { - SetPsiR(m_PsiI+90); - SetKhiR(-m_KhiI); - SetMode(2); + SetPsiR(m_PsiI+90); + SetKhiR(-m_KhiI); + SetMode(2); } /** @@ -173,35 +173,35 @@ PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImag ::VerifyAndForceInputs() { - switch(m_ArchitectureType->GetArchitectureType()) - { - case HH_HV : - // Forcing KhiI=0 PsiI=0 - this->SetKhiI(0); - this->SetPsiI(0); - break; + switch (m_ArchitectureType->GetArchitectureType()) + { + case HH_HV : + // Forcing KhiI=0 PsiI=0 + this->SetKhiI(0); + this->SetPsiI(0); + break; - case VH_VV : - // Forcing KhiI=0 PsiI=90 - this->SetKhiI(0); - this->SetPsiI(90); - break; + case VH_VV : + // Forcing KhiI=0 PsiI=90 + this->SetKhiI(0); + this->SetPsiI(90); + break; - case HH_VV : - itkExceptionMacro("Only the HH and VV channels are available : Polarimetric synthesis is not supported !"); - return; + case HH_VV : + itkExceptionMacro("Only the HH and VV channels are available : Polarimetric synthesis is not supported !"); + return; - case UNKNOWN : - itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); - return; + case UNKNOWN : + itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); + return; - default : - break; + default : + break; - } + } - if(GetMode()==1)ForceCoPolar(); - else if(GetMode()==2)ForceCrossPolar(); + if (GetMode()==1)ForceCoPolar(); + else if (GetMode()==2)ForceCrossPolar(); } @@ -254,14 +254,14 @@ PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImag ::BeforeThreadedGenerateData() { - // First Part. Determine the kind of architecture - m_ArchitectureType->DetermineArchitecture(m_PresentInputImages); + // First Part. Determine the kind of architecture + m_ArchitectureType->DetermineArchitecture(m_PresentInputImages); - // Second Part. Verify and force the inputs - VerifyAndForceInputs(); + // Second Part. Verify and force the inputs + VerifyAndForceInputs(); - // Third Part. Estimation of the incident field Ei and the reflected field Er - ComputeElectromagneticFields(); + // Third Part. Estimation of the incident field Ei and the reflected field Er + ComputeElectromagneticFields(); } @@ -281,169 +281,169 @@ PolarimetricSynthesisFilter<TInputImageHH,TInputImageHV,TInputImageVH,TInputImag switch (m_ArchitectureType->GetArchitectureType()) { - // With 4 channels : - case HH_HV_VH_VV : - { - // We use dynamic_cast since inputs are stored as DataObjects. The - // ImageToImageFilter::GetInput(int) always returns a pointer to a - // TInputImage1 so it cannot be used for the second or third input. - HHInputImagePointer inputPtrHH - = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); - HVInputImagePointer inputPtrHV - = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); - VHInputImagePointer inputPtrVH - = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); - VVInputImagePointer inputPtrVV - = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); - - itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); - - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - inputItHH.GoToBegin(); - inputItHV.GoToBegin(); - inputItVH.GoToBegin(); - inputItVV.GoToBegin(); - - while( !inputItHH.IsAtEnd() ) - { - outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), inputItVH.Get(), inputItVV.Get()) ); - ++inputItHH; - ++inputItHV; - ++inputItVH; - ++inputItVV; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - } - // With 3 channels : HH HV VV - case HH_HV_VV : - - { - HHInputImagePointer inputPtrHH - = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); - HVInputImagePointer inputPtrHV - = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); - VVInputImagePointer inputPtrVV - = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); - - itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); - itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); - - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - inputItHH.GoToBegin(); - inputItHV.GoToBegin(); - inputItVV.GoToBegin(); - - while( !inputItHH.IsAtEnd() ) - { - outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), inputItHV.Get(), inputItVV.Get()) ); - ++inputItHH; - ++inputItHV; - ++inputItVV; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - } - // With 3 channels : HH VH VV - case HH_VH_VV : - { - - HHInputImagePointer inputPtrHH - = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); - VHInputImagePointer inputPtrVH - = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); - VVInputImagePointer inputPtrVV - = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); - OutputImagePointer outputPtr = this->GetOutput(0); - - itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); - - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - inputItHH.GoToBegin(); - inputItVH.GoToBegin(); - inputItVV.GoToBegin(); - - while( !inputItHH.IsAtEnd() ) - { - outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItVH.Get(), inputItVH.Get(), inputItVV.Get()) ); - ++inputItHH; - ++inputItVH; - ++inputItVV; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - } - // With 2 channels : HH HV - case HH_HV : - { - - HHInputImagePointer inputPtrHH - = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); - HVInputImagePointer inputPtrHV - = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); - - itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); - itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); - - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - inputItHH.GoToBegin(); - inputItHV.GoToBegin(); - - while( !inputItHH.IsAtEnd() ) - { - outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), 0,0 )); - ++inputItHH; - ++inputItHV; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - } - // With 2 channels : VH VV - case VH_VV : - { - VHInputImagePointer inputPtrVH - = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); - VVInputImagePointer inputPtrVV - = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); - - itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); - itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); - itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); - - itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - inputItVH.GoToBegin(); - inputItVV.GoToBegin(); - - while( !inputItVH.IsAtEnd() ) - { - outputIt.Set( m_Gain * Superclass::GetFunctor()(0,0, inputItVH.Get(), inputItVV.Get()) ); - ++inputItVH; - ++inputItVV; - ++outputIt; - progress.CompletedPixel(); // potential exception thrown here - } - break; - } - default : - itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); - return; + // With 4 channels : + case HH_HV_VH_VV : + { + // We use dynamic_cast since inputs are stored as DataObjects. The + // ImageToImageFilter::GetInput(int) always returns a pointer to a + // TInputImage1 so it cannot be used for the second or third input. + HHInputImagePointer inputPtrHH + = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); + HVInputImagePointer inputPtrHV + = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); + VHInputImagePointer inputPtrVH + = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); + VVInputImagePointer inputPtrVV + = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); + + itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); + + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputItHH.GoToBegin(); + inputItHV.GoToBegin(); + inputItVH.GoToBegin(); + inputItVV.GoToBegin(); + + while ( !inputItHH.IsAtEnd() ) + { + outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), inputItVH.Get(), inputItVV.Get()) ); + ++inputItHH; + ++inputItHV; + ++inputItVH; + ++inputItVV; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + } + // With 3 channels : HH HV VV + case HH_HV_VV : + + { + HHInputImagePointer inputPtrHH + = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); + HVInputImagePointer inputPtrHV + = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); + VVInputImagePointer inputPtrVV + = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); + + itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); + itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputItHH.GoToBegin(); + inputItHV.GoToBegin(); + inputItVV.GoToBegin(); + + while ( !inputItHH.IsAtEnd() ) + { + outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), inputItHV.Get(), inputItVV.Get()) ); + ++inputItHH; + ++inputItHV; + ++inputItVV; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + } + // With 3 channels : HH VH VV + case HH_VH_VV : + { + + HHInputImagePointer inputPtrHH + = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); + VHInputImagePointer inputPtrVH + = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); + VVInputImagePointer inputPtrVV + = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); + OutputImagePointer outputPtr = this->GetOutput(0); + + itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); + + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputItHH.GoToBegin(); + inputItVH.GoToBegin(); + inputItVV.GoToBegin(); + + while ( !inputItHH.IsAtEnd() ) + { + outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItVH.Get(), inputItVH.Get(), inputItVV.Get()) ); + ++inputItHH; + ++inputItVH; + ++inputItVV; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + } + // With 2 channels : HH HV + case HH_HV : + { + + HHInputImagePointer inputPtrHH + = dynamic_cast<const TInputImageHH*>((itk::ProcessObject::GetInput(0))); + HVInputImagePointer inputPtrHV + = dynamic_cast<const TInputImageHV*>((itk::ProcessObject::GetInput(1))); + + itk::ImageRegionConstIterator<TInputImageHH> inputItHH(inputPtrHH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageHV> inputItHV(inputPtrHV, outputRegionForThread); + itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputItHH.GoToBegin(); + inputItHV.GoToBegin(); + + while ( !inputItHH.IsAtEnd() ) + { + outputIt.Set( m_Gain * Superclass::GetFunctor()(inputItHH.Get(), inputItHV.Get(), 0,0 )); + ++inputItHH; + ++inputItHV; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + } + // With 2 channels : VH VV + case VH_VV : + { + VHInputImagePointer inputPtrVH + = dynamic_cast<const TInputImageVH*>((itk::ProcessObject::GetInput(2))); + VVInputImagePointer inputPtrVV + = dynamic_cast<const TInputImageVV*>((itk::ProcessObject::GetInput(3))); + + itk::ImageRegionConstIterator<TInputImageVH> inputItVH(inputPtrVH, outputRegionForThread); + itk::ImageRegionConstIterator<TInputImageVV> inputItVV(inputPtrVV, outputRegionForThread); + itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputItVH.GoToBegin(); + inputItVV.GoToBegin(); + + while ( !inputItVH.IsAtEnd() ) + { + outputIt.Set( m_Gain * Superclass::GetFunctor()(0,0, inputItVH.Get(), inputItVV.Get()) ); + ++inputItVH; + ++inputItVV; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } + break; + } + default : + itkExceptionMacro("Unknown architecture : Polarimetric synthesis is impossible !"); + return; } } // end namespace otb diff --git a/Code/SARPolarimetry/otbPolarimetricSynthesisFunctor.h b/Code/SARPolarimetry/otbPolarimetricSynthesisFunctor.h index cbc5eb6b4c64f660417c800882691274bcbba9aa..d5c107aa7095b954b6818b9068a0031d2da97b11 100644 --- a/Code/SARPolarimetry/otbPolarimetricSynthesisFunctor.h +++ b/Code/SARPolarimetry/otbPolarimetricSynthesisFunctor.h @@ -22,62 +22,64 @@ namespace otb { namespace Functor +{ +/** \class PolarimetricSynthesisFunctor + * \brief This functor calculate the polarimetric synthesis + * using the electroMagneticField vectors as follow: + * $$ \sigma(\psi_{i},\chi_{i},\psi_{r},\chi_{r}) = + \vec(E_{r}}\cdot\left[ S \right] \vec(E_{i}}$$ + * + * \ingroup Functor + */ +template <class TInput1, class TInput2, class TInput3, class TInput4, class TOutput> +class PolarimetricSynthesisFunctor +{ +public: + /** Some typedefs. */ + typedef typename std::complex <double> ComplexType; + typedef typename itk::FixedArray<ComplexType,2> ComplexArrayType; + + /** Set the ElectroMagneticField Incident */ + void SetEi( ComplexArrayType ei ) { - /** \class PolarimetricSynthesisFunctor - * \brief This functor calculate the polarimetric synthesis - * using the electroMagneticField vectors as follow: - * $$ \sigma(\psi_{i},\chi_{i},\psi_{r},\chi_{r}) = - \vec(E_{r}}\cdot\left[ S \right] \vec(E_{i}}$$ - * - * \ingroup Functor - */ - template <class TInput1, class TInput2, class TInput3, class TInput4, class TOutput> - class PolarimetricSynthesisFunctor - { - public: - /** Some typedefs. */ - typedef typename std::complex <double> ComplexType; - typedef typename itk::FixedArray<ComplexType,2> ComplexArrayType; - - /** Set the ElectroMagneticField Incident */ - void SetEi( ComplexArrayType ei ){ - m_Ei = ei; - } - - /** Set the ElectroMagneticField Reflected */ - void SetEr( ComplexArrayType er ){ - m_Er = er; - } - - /** Constructor */ + m_Ei = ei; + } + + /** Set the ElectroMagneticField Reflected */ + void SetEr( ComplexArrayType er ) + { + m_Er = er; + } + + /** Constructor */ PolarimetricSynthesisFunctor() - { - m_Ei.Fill(1); - m_Er.Fill(1); - }; - /** Destructor */ + { + m_Ei.Fill(1); + m_Er.Fill(1); + }; + /** Destructor */ virtual ~PolarimetricSynthesisFunctor() {}; - inline TOutput operator()(const TInput1 &Shh, const TInput2 &Shv, const TInput3 &Svh, const TInput4 &Svv) + inline TOutput operator()(const TInput1 &Shh, const TInput2 &Shv, const TInput3 &Svh, const TInput4 &Svv) { - ComplexType tmp; - double scalar; + ComplexType tmp; + double scalar; - tmp = vcl_conj(m_Er[0])*( m_Ei[0]*Shh + m_Ei[1]*Shv ) + vcl_conj(m_Er[1])*( m_Ei[0]*Svh + m_Ei[1]*Svv ); + tmp = vcl_conj(m_Er[0])*( m_Ei[0]*Shh + m_Ei[1]*Shv ) + vcl_conj(m_Er[1])*( m_Ei[0]*Svh + m_Ei[1]*Svv ); - scalar=(double) ( vcl_pow( std::abs(tmp),2) ); + scalar=(double) ( vcl_pow( std::abs(tmp),2) ); - return ( static_cast<TOutput>(scalar) ); - } + return ( static_cast<TOutput>(scalar) ); + } - private : - /** Electromagnetic Field Incident */ - ComplexArrayType m_Ei; - /** Electromagnetic Field Reflected */ - ComplexArrayType m_Er; +private : + /** Electromagnetic Field Incident */ + ComplexArrayType m_Ei; + /** Electromagnetic Field Reflected */ + ComplexArrayType m_Er; - }; +}; - } // namespace Functor +} // namespace Functor } // namespace otb #endif diff --git a/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.h b/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.h index 00b422e615430c00f46f713cebb86c6714517025..4320ac09a41b2a63c0142105670aba26b4f7445b 100644 --- a/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.h +++ b/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.h @@ -28,7 +28,7 @@ namespace otb */ template <class TInputImage, class TOutputGraph> class ITK_EXPORT ImageListToRCC8GraphFilter - : public RCC8GraphSource<TOutputGraph> + : public RCC8GraphSource<TOutputGraph> { public: /** Standard typedefs */ @@ -50,7 +50,7 @@ public: typedef ImageList<InputImageType> InputImageListType; typedef typename InputImageListType::Pointer InputImageListPointerType; typedef typename InputImageListType::ConstPointer InputImageListConstPointer; - /** Template output parameters typedefs */ + /** Template output parameters typedefs */ typedef TOutputGraph OutputGraphType; typedef typename Superclass::OutputGraphPointerType OutputGraphPointerType; typedef typename OutputGraphType::VertexType VertexType; @@ -67,7 +67,7 @@ protected: ImageListToRCC8GraphFilter(); /** Destructor */ virtual ~ImageListToRCC8GraphFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: diff --git a/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.txx b/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.txx index ae0628e97a6fecb218ba04a4866bee51d2f527f1..24b67bb12953e3636757201ee402724345c0b34e 100644 --- a/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.txx +++ b/Code/SpatialReasoning/otbImageListToRCC8GraphFilter.txx @@ -54,13 +54,13 @@ ImageListToRCC8GraphFilter<TInputImage,TOutputGraph> { // If there is no input if (this->GetNumberOfInputs()<1) - { + { // exit return 0; - } + } // else return the first input return static_cast<InputImageListType * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } /** * PrintSelf Method diff --git a/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.h b/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.h index 441f4f6211e0ff9b5eed30e92a1ad04731d85909..be9dfcd427ed7425b591a576f0c55547a6cacaf6 100644 --- a/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.h +++ b/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.h @@ -29,7 +29,7 @@ namespace otb */ template <class TInputImage, class TOutputGraph> class ITK_EXPORT ImageMultiSegmentationToRCC8GraphFilter - : public ImageListToRCC8GraphFilter<TInputImage,TOutputGraph> + : public ImageListToRCC8GraphFilter<TInputImage,TOutputGraph> { public: /** Standard class typedefs. */ diff --git a/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.txx b/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.txx index e1ee261812cf4dd29a52c937b6743d38a0630e72..caa7060fb568cdde4606d4c30005fbee7821acb1 100644 --- a/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.txx +++ b/Code/SpatialReasoning/otbImageMultiSegmentationToRCC8GraphFilter.txx @@ -63,11 +63,11 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> ::GetNumberOfRelations() { unsigned int result = 0; - for(unsigned int i = 0;i<8;++i) - { - result+=m_Accumulator[i]; + for (unsigned int i = 0;i<8;++i) + { + result+=m_Accumulator[i]; - } + } return result; } template <class TInputImage, class TOutputGraph> @@ -87,41 +87,42 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> // otbMsgDebugMacro(<<"RCC8GraphFilter: entering GetKnowledge method."); // This is the RCC8 composition table - const int knowledge[8][8] - ={ - /** DC EC PO TPP TPPi NTPP i EQ */ - /** DC */ {-3, -2, -2, -2, 0, -2, 0, 0}, - /** EC */ {-1, -3, -2, -3, -1, -3, 0, 1}, - /** PO */ {-1, -1, -3, -3, -1, -3, -1, 2}, - /** TPP */ { 0, -1, -2, -3, -3, 5, -1, 3}, - /** TPPi*/ {-1, -1, -1, -3, -1, -3, 6, 4}, - /** NTPP*/ { 0, 0, -2, 5, -2, 5, -3, 5}, - /** NTPPi*/{-1, -1, -1, -1, 6, -3, 6, 6}, - /** EQ */ { 0, 1, 2, 3, 4, 5, 6, 7} - }; + const int knowledge[8][8] + = + { + /** DC EC PO TPP TPPi NTPP i EQ */ + /** DC */ {-3, -2, -2, -2, 0, -2, 0, 0}, + /** EC */ {-1, -3, -2, -3, -1, -3, 0, 1}, + /** PO */ {-1, -1, -3, -3, -1, -3, -1, 2}, + /** TPP */ { 0, -1, -2, -3, -3, 5, -1, 3}, + /** TPPi*/ {-1, -1, -1, -3, -1, -3, 6, 4}, + /** NTPP*/ { 0, 0, -2, 5, -2, 5, -3, 5}, + /** NTPPi*/{-1, -1, -1, -1, 6, -3, 6, 6}, + /** EQ */ { 0, 1, 2, 3, 4, 5, 6, 7} + }; int value = knowledge[r1][r2]; // Each negative case correspond to a level of knowledge - if(value>=0) - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: FULL"); - return KnowledgeStateType(FULL,static_cast<RCC8ValueType>(value)); - } - else if(value==-1) - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: LEVEL_1"); - return KnowledgeStateType(LEVEL_1,OTB_RCC8_DC); - } - else if(value==-2) - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.LEVEL_3"); - return KnowledgeStateType(LEVEL_3,OTB_RCC8_DC); - } + if (value>=0) + { + // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: FULL"); + return KnowledgeStateType(FULL,static_cast<RCC8ValueType>(value)); + } + else if (value==-1) + { + // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: LEVEL_1"); + return KnowledgeStateType(LEVEL_1,OTB_RCC8_DC); + } + else if (value==-2) + { + // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.LEVEL_3"); + return KnowledgeStateType(LEVEL_3,OTB_RCC8_DC); + } else - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.NO_INFO"); - return KnowledgeStateType(NO_INFO,OTB_RCC8_DC); - } + { + // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.NO_INFO"); + return KnowledgeStateType(NO_INFO,OTB_RCC8_DC); + } } /** * Main computation method. @@ -142,7 +143,8 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> // invert value vector RCC8ValueType invert[8]={OTB_RCC8_DC,OTB_RCC8_EC,OTB_RCC8_PO,OTB_RCC8_TPPI, - OTB_RCC8_TPP,OTB_RCC8_NTPPI,OTB_RCC8_NTPP,OTB_RCC8_EQ}; + OTB_RCC8_TPP,OTB_RCC8_NTPPI,OTB_RCC8_NTPP,OTB_RCC8_EQ + }; // Some typedefs typedef otb::ImageToEdgePathFilter<InputImageType,PathType> EdgeExtractionFilterType; @@ -155,7 +157,7 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> typedef RCC8InEdgeIterator<OutputGraphType> InEdgeIteratorType; typedef RCC8OutEdgeIterator<OutputGraphType> OutEdgeIteratorType; - // Vector of label + // Vector of label std::vector<PixelType> maxLabelVector; // Vertex indexes @@ -164,43 +166,43 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> unsigned int nbVertices = 0; // For each segmentation image - for(ConstListIteratorType it = segList->Begin();it!=segList->End();++it) - { - // Compute the maximum label - typename MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New(); - minMax->SetImage(it.Get()); - minMax->ComputeMaximum(); - maxLabelVector.push_back(minMax->GetMaximum()); - otbMsgDebugMacro(<<"Number of objects in image "<<segmentationImageIndex<<": " - <<minMax->GetMaximum()); - - // then for each region of the images - for(PixelType label=1; label<=maxLabelVector.back();++label) + for (ConstListIteratorType it = segList->Begin();it!=segList->End();++it) { - typename PathListType::Pointer region = PathListType::New(); - typename EdgeExtractionFilterType::Pointer extraction = EdgeExtractionFilterType::New(); - extraction->SetInput(it.Get()); - extraction->SetForegroundValue(label); - extraction->Update(); - region->PushBack(extraction->GetOutput()); - typename SimplifyPathFilterType::Pointer simplifier = SimplifyPathFilterType::New(); - simplifier->SetInput(region); - simplifier->GetFunctor().SetTolerance(0.1); - simplifier->Update(); - - // Create a new vertex - VertexPointerType vertex = VertexType::New(); - // Set its properties - vertex->SetPath(simplifier->GetOutput()->GetNthElement(0)); - vertex->SetSegmentationLevel(segmentationImageIndex/2); - vertex->SetSegmentationType(segmentationImageIndex%2); - // Put it in the graph - graph->SetVertex(vertexIndex,vertex); - vertexIndex++; - ++nbVertices; - } - segmentationImageIndex++; + // Compute the maximum label + typename MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New(); + minMax->SetImage(it.Get()); + minMax->ComputeMaximum(); + maxLabelVector.push_back(minMax->GetMaximum()); + otbMsgDebugMacro(<<"Number of objects in image "<<segmentationImageIndex<<": " + <<minMax->GetMaximum()); + + // then for each region of the images + for (PixelType label=1; label<=maxLabelVector.back();++label) + { + typename PathListType::Pointer region = PathListType::New(); + typename EdgeExtractionFilterType::Pointer extraction = EdgeExtractionFilterType::New(); + extraction->SetInput(it.Get()); + extraction->SetForegroundValue(label); + extraction->Update(); + region->PushBack(extraction->GetOutput()); + typename SimplifyPathFilterType::Pointer simplifier = SimplifyPathFilterType::New(); + simplifier->SetInput(region); + simplifier->GetFunctor().SetTolerance(0.1); + simplifier->Update(); + + // Create a new vertex + VertexPointerType vertex = VertexType::New(); + // Set its properties + vertex->SetPath(simplifier->GetOutput()->GetNthElement(0)); + vertex->SetSegmentationLevel(segmentationImageIndex/2); + vertex->SetSegmentationType(segmentationImageIndex%2); + // Put it in the graph + graph->SetVertex(vertexIndex,vertex); + vertexIndex++; + ++nbVertices; } + segmentationImageIndex++; + } itk::ProgressReporter progress(this,0,nbVertices*nbVertices); @@ -208,12 +210,12 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> VertexIteratorType vIt2(graph); // For each couple of vertices - for(vIt1.GoToBegin();!vIt1.IsAtEnd();++vIt1) - { - for(vIt2.GoToBegin();!vIt2.IsAtEnd();++vIt2) + for (vIt1.GoToBegin();!vIt1.IsAtEnd();++vIt1) { - //We do not examine each couple because of the RCC8 symmetry - if(vIt1.GetIndex()<vIt2.GetIndex()) + for (vIt2.GoToBegin();!vIt2.IsAtEnd();++vIt2) + { + //We do not examine each couple because of the RCC8 symmetry + if (vIt1.GetIndex()<vIt2.GetIndex()) { // Compute the RCC8 relation @@ -223,86 +225,86 @@ ImageMultiSegmentationToRCC8GraphFilter<TInputImage, TOutputGraph> RCC8ValueType value=OTB_RCC8_DC; // if the optimisations are activated - if(m_Optimisation) - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: Entering optimisation loop"); - InEdgeIteratorType inIt1(vIt1.GetIndex(),graph); - InEdgeIteratorType inIt2(vIt2.GetIndex(),graph); - // otbMsgDebugMacro(<<"Optimisation loop: iterators initialised"); - VertexDescriptorType betweenIndex; - KnowledgeStateType know(NO_INFO,OTB_RCC8_DC); - inIt1.GoToBegin(); - - // Iterate through the edges going to the first vertex - while(!inIt1.IsAtEnd()&&(know.first!=FULL)) + if (m_Optimisation) { - betweenIndex = inIt1.GetSourceIndex(); - inIt2.GoToBegin(); - bool edgeFound = false; - while(!inIt2.IsAtEnd()&&(know.first!=FULL)) - { - // try to find an intermediate vertex between the two ones which - // we vant to compute the relationship - if(inIt2.GetSourceIndex()==betweenIndex) + // otbMsgDebugMacro(<<"RCC8GraphFilter: Entering optimisation loop"); + InEdgeIteratorType inIt1(vIt1.GetIndex(),graph); + InEdgeIteratorType inIt2(vIt2.GetIndex(),graph); + // otbMsgDebugMacro(<<"Optimisation loop: iterators initialised"); + VertexDescriptorType betweenIndex; + KnowledgeStateType know(NO_INFO,OTB_RCC8_DC); + inIt1.GoToBegin(); + + // Iterate through the edges going to the first vertex + while (!inIt1.IsAtEnd()&&(know.first!=FULL)) { - // if an intermediate vertex is found - edgeFound = true; - // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); - // See if it brings some info on the RCCC8 value - know = GetKnowledge(invert[inIt1.GetValue()],inIt2.GetValue()); - calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); - calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); - // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); + betweenIndex = inIt1.GetSourceIndex(); + inIt2.GoToBegin(); + bool edgeFound = false; + while (!inIt2.IsAtEnd()&&(know.first!=FULL)) + { + // try to find an intermediate vertex between the two ones which + // we vant to compute the relationship + if (inIt2.GetSourceIndex()==betweenIndex) + { + // if an intermediate vertex is found + edgeFound = true; + // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); + // See if it brings some info on the RCCC8 value + know = GetKnowledge(invert[inIt1.GetValue()],inIt2.GetValue()); + calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); + calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); + // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); + } + ++inIt2; + } + // If no intermediate was found + if (!edgeFound) + { + // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); + // Try using a DC relationship + know = GetKnowledge(invert[inIt1.GetValue()],OTB_RCC8_DC); + calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); + calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); + // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); + } + ++inIt1; } - ++inIt2; - } - // If no intermediate was found - if(!edgeFound) - { - // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); - // Try using a DC relationship - know = GetKnowledge(invert[inIt1.GetValue()],OTB_RCC8_DC); - calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); - calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); - // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); - } - ++inIt1; - } - // If the search has fully determined the RCC8 - if(know.first==FULL) - { - // Get the value - value=know.second; + // If the search has fully determined the RCC8 + if (know.first==FULL) + { + // Get the value + value=know.second; + } + else + { + // Else trigger the computation + // (which will take the optimisation phase info into account) + calc->Compute(); + value=calc->GetValue(); + } + // otbMsgDebugMacro(<<"RCC8GraphFilter: Leaving optimisation loop"); } - else + // If the optimisations are not activated + else { - // Else trigger the computation - // (which will take the optimisation phase info into account) calc->Compute(); value=calc->GetValue(); } - // otbMsgDebugMacro(<<"RCC8GraphFilter: Leaving optimisation loop"); - } - // If the optimisations are not activated - else - { - calc->Compute(); - value=calc->GetValue(); - } m_Accumulator[value]+=1; m_Accumulator[invert[value]]+=1; // If the vertices are connected - if(value>OTB_RCC8_DC) - { - // Add the edge to the graph. - otbMsgDevMacro(<<"Adding edge: "<<vIt1.GetIndex()<<" -> "<<vIt2.GetIndex()<<": "<<value); - graph->AddEdge(vIt1.GetIndex(),vIt2.GetIndex(),value); - } + if (value>OTB_RCC8_DC) + { + // Add the edge to the graph. + otbMsgDevMacro(<<"Adding edge: "<<vIt1.GetIndex()<<" -> "<<vIt2.GetIndex()<<": "<<value); + graph->AddEdge(vIt1.GetIndex(),vIt2.GetIndex(),value); + } } - progress.CompletedPixel(); - progress.CompletedPixel(); - } + progress.CompletedPixel(); + progress.CompletedPixel(); } + } } template <class TInputImage, class TOutputGraph> diff --git a/Code/SpatialReasoning/otbImageToImageRCC8Calculator.h b/Code/SpatialReasoning/otbImageToImageRCC8Calculator.h index 6547c34f8138d9794cd26bca1ff0369cdb61a13b..b056c58a8213ea44538f0403284fb9f50919bae3 100644 --- a/Code/SpatialReasoning/otbImageToImageRCC8Calculator.h +++ b/Code/SpatialReasoning/otbImageToImageRCC8Calculator.h @@ -47,7 +47,7 @@ namespace otb * to the smallest set needed to determine the relation. */ template <class TInputImage> - class ITK_EXPORT ImageToImageRCC8Calculator : public itk::ImageToImageFilter<TInputImage,TInputImage> +class ITK_EXPORT ImageToImageRCC8Calculator : public itk::ImageToImageFilter<TInputImage,TInputImage> { public: /** Standard class typedefs. */ @@ -104,12 +104,12 @@ public: /** Set/Get the inside value of the region of image 2*/ itkSetMacro(InsideValue2,PixelType); itkGetMacro(InsideValue2,PixelType); -/** Set external knowledge to help the decision process */ + /** Set external knowledge to help the decision process */ itkSetMacro(Level1APrioriKnowledge,bool); itkSetMacro(Level3APrioriKnowledge,bool); itkGetMacro(Level1APrioriKnowledge,bool); itkGetMacro(Level3APrioriKnowledge,bool); - protected: +protected: /** Constructor */ ImageToImageRCC8Calculator(); /** Destructor */ @@ -172,7 +172,7 @@ public: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** The RCC8 relation value */ RCC8ValueType m_Value; /** The minimal ROI needed to compute the relation value */ diff --git a/Code/SpatialReasoning/otbImageToImageRCC8Calculator.txx b/Code/SpatialReasoning/otbImageToImageRCC8Calculator.txx index ca52ade85b00df430984b97c45b76ab1cf72caee..d3ac96352a681ef8282eb2ced02b230a412c1ada 100644 --- a/Code/SpatialReasoning/otbImageToImageRCC8Calculator.txx +++ b/Code/SpatialReasoning/otbImageToImageRCC8Calculator.txx @@ -34,130 +34,130 @@ namespace otb { - /** - * Constructor - */ - template<class TInputImage> - ImageToImageRCC8Calculator<TInputImage> - ::ImageToImageRCC8Calculator() - { - m_Value = OTB_RCC8_DC; - m_InsideValue1 = static_cast<PixelType>(255); - m_InsideValue2 = static_cast<PixelType>(255); - m_Level1APrioriKnowledge=false; - m_Level3APrioriKnowledge=false; - this->SetNumberOfRequiredInputs(2); - } - /** - * Set the first input image. - * \param image - */ - template<class TInputImage> - void - ImageToImageRCC8Calculator<TInputImage> - ::SetInput1(ImageType * image) - { - this->SetNthInput(0,const_cast<ImageType *>(image)); - } - /** - * Set the second input image. - * \param image - */ - template<class TInputImage> - void - ImageToImageRCC8Calculator<TInputImage> - ::SetInput2(ImageType * image) - { - this->SetNthInput(1,const_cast<ImageType *>(image)); - } - /** - * Get the first input image. - * \return The first input image. - */ - template<class TInputImage> - typename ImageToImageRCC8Calculator<TInputImage> - ::ImageType* - ImageToImageRCC8Calculator<TInputImage> - ::GetInput1(void) - { - return dynamic_cast<ImageType*>(this->itk::ProcessObject::GetInput(0)); - } - /** - * Get the second input image. - * \return The second input image. - */ - template<class TInputImage> - typename ImageToImageRCC8Calculator<TInputImage> - ::ImageType* - ImageToImageRCC8Calculator<TInputImage> - ::GetInput2(void) - { - return dynamic_cast<ImageType*>(this->itk::ProcessObject::GetInput(1)); - } - /** - * Get the RCC8 relation. - * \return The RCC8 relation value. - */ - template <class TInputImage> - typename ImageToImageRCC8Calculator<TInputImage> - ::RCC8ValueType - ImageToImageRCC8Calculator<TInputImage> - ::GetValue(void) - { - return m_Value; - } - /** - * Compute the minimal image region required. - * \return The minimal region required. - */ - template <class TInputImage> - typename ImageToImageRCC8Calculator<TInputImage> - ::RegionType - ImageToImageRCC8Calculator<TInputImage> - ::ComputeMinimalRegion(void) - { - // Input images pointers - typename ImageType::Pointer image1 = this->GetInput1(); - typename ImageType::Pointer image2 = this->GetInput2(); - typename ImageType::RegionType region1, region2, region; - typedef otb::BinaryImageMinimalBoundingRegionCalculator<ImageType> RegionCalculator; - typename RegionCalculator::Pointer rc =RegionCalculator::New(); - rc->SetInput(image1); - rc->SetPad(2); - rc->SetInsideValue(this->GetInsideValue1()); - rc->Update(); - region1=rc->GetRegion(); - rc=RegionCalculator::New(); - rc->SetInput(image2); - rc->SetPad(2); - rc->SetInsideValue(this->GetInsideValue2()); - rc->Update(); - region2=rc->GetRegion(); - // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion() Region1: index: "<<region1.GetIndex()<<" size: "<<region1.GetSize()); - // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion() Region2: index: "<<region2.GetIndex()<<" size: "<<region2.GetSize()); +/** + * Constructor + */ +template<class TInputImage> +ImageToImageRCC8Calculator<TInputImage> +::ImageToImageRCC8Calculator() +{ + m_Value = OTB_RCC8_DC; + m_InsideValue1 = static_cast<PixelType>(255); + m_InsideValue2 = static_cast<PixelType>(255); + m_Level1APrioriKnowledge=false; + m_Level3APrioriKnowledge=false; + this->SetNumberOfRequiredInputs(2); +} +/** + * Set the first input image. + * \param image + */ +template<class TInputImage> +void +ImageToImageRCC8Calculator<TInputImage> +::SetInput1(ImageType * image) +{ + this->SetNthInput(0,const_cast<ImageType *>(image)); +} +/** + * Set the second input image. + * \param image + */ +template<class TInputImage> +void +ImageToImageRCC8Calculator<TInputImage> +::SetInput2(ImageType * image) +{ + this->SetNthInput(1,const_cast<ImageType *>(image)); +} +/** + * Get the first input image. + * \return The first input image. + */ +template<class TInputImage> +typename ImageToImageRCC8Calculator<TInputImage> +::ImageType* +ImageToImageRCC8Calculator<TInputImage> +::GetInput1(void) +{ + return dynamic_cast<ImageType*>(this->itk::ProcessObject::GetInput(0)); +} +/** + * Get the second input image. + * \return The second input image. + */ +template<class TInputImage> +typename ImageToImageRCC8Calculator<TInputImage> +::ImageType* +ImageToImageRCC8Calculator<TInputImage> +::GetInput2(void) +{ + return dynamic_cast<ImageType*>(this->itk::ProcessObject::GetInput(1)); +} +/** + * Get the RCC8 relation. + * \return The RCC8 relation value. + */ +template <class TInputImage> +typename ImageToImageRCC8Calculator<TInputImage> +::RCC8ValueType +ImageToImageRCC8Calculator<TInputImage> +::GetValue(void) +{ + return m_Value; +} +/** + * Compute the minimal image region required. + * \return The minimal region required. + */ +template <class TInputImage> +typename ImageToImageRCC8Calculator<TInputImage> +::RegionType +ImageToImageRCC8Calculator<TInputImage> +::ComputeMinimalRegion(void) +{ + // Input images pointers + typename ImageType::Pointer image1 = this->GetInput1(); + typename ImageType::Pointer image2 = this->GetInput2(); + typename ImageType::RegionType region1, region2, region; + typedef otb::BinaryImageMinimalBoundingRegionCalculator<ImageType> RegionCalculator; + typename RegionCalculator::Pointer rc =RegionCalculator::New(); + rc->SetInput(image1); + rc->SetPad(2); + rc->SetInsideValue(this->GetInsideValue1()); + rc->Update(); + region1=rc->GetRegion(); + rc=RegionCalculator::New(); + rc->SetInput(image2); + rc->SetPad(2); + rc->SetInsideValue(this->GetInsideValue2()); + rc->Update(); + region2=rc->GetRegion(); + // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion() Region1: index: "<<region1.GetIndex()<<" size: "<<region1.GetSize()); + // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion() Region2: index: "<<region2.GetIndex()<<" size: "<<region2.GetSize()); //TODELETE std::cout<<"RCC8Calculator->ComputeMinimalRegion() Region1: index: "<<region1.GetIndex()<<" size: "<<region1.GetSize()<<std::endl; - //TODELETE std::cout<<"RCC8Calculator->ComputeMinimalRegion() Region2: index: "<<region2.GetIndex()<<" size: "<<region2.GetSize()<<std::endl; +//TODELETE std::cout<<"RCC8Calculator->ComputeMinimalRegion() Region2: index: "<<region2.GetIndex()<<" size: "<<region2.GetSize()<<std::endl; - typename ImageType::SizeType size; - typename ImageType::IndexType index; + typename ImageType::SizeType size; + typename ImageType::IndexType index; - for(int i=0;i<ImageType::ImageDimension;i++) - { - index[i]=std::min(region1.GetIndex()[i],region2.GetIndex()[i]); - int potSize = std::max(region1.GetIndex()[i]+region1.GetSize()[i], - region2.GetIndex()[i]+region2.GetSize()[i]); - size[i]=(potSize-index[i]<0 ? 0 : potSize-index[i]); - } - region.SetIndex(index); - region.SetSize(size); - region.PadByRadius(2); - region.Crop(image1->GetLargestPossibleRegion()); - region.Crop(image2->GetLargestPossibleRegion()); - // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion(): index: "<<index<<" size: "<<size); - //TODELETE std::cout<<"RCC8Calculator->ComputeMinimalRegion(): index: "<<index<<" size: "<<size<<std::endl; - return region; + for (int i=0;i<ImageType::ImageDimension;i++) + { + index[i]=std::min(region1.GetIndex()[i],region2.GetIndex()[i]); + int potSize = std::max(region1.GetIndex()[i]+region1.GetSize()[i], + region2.GetIndex()[i]+region2.GetSize()[i]); + size[i]=(potSize-index[i]<0 ? 0 : potSize-index[i]); } + region.SetIndex(index); + region.SetSize(size); + region.PadByRadius(2); + region.Crop(image1->GetLargestPossibleRegion()); + region.Crop(image2->GetLargestPossibleRegion()); + // otbMsgDebugMacro(<<"RCC8Calculator->ComputeMinimalRegion(): index: "<<index<<" size: "<<size); + //TODELETE std::cout<<"RCC8Calculator->ComputeMinimalRegion(): index: "<<index<<" size: "<<size<<std::endl; + return region; +} /** * Compute a bool image of minimal ROI size, surrounded by a false padding, and corresponding * to the input image. @@ -193,328 +193,328 @@ ImageToImageRCC8Calculator<TInputImage> Iterator outputIt(output,m_MinimalROI); inputIt.GoToBegin(); outputIt.GoToBegin(); - while(!inputIt.IsAtEnd()&&!outputIt.IsAtEnd()) - { - outputIt.Set(inputIt.Get()==insideValue); - ++inputIt; - ++outputIt; - } + while (!inputIt.IsAtEnd()&&!outputIt.IsAtEnd()) + { + outputIt.Set(inputIt.Get()==insideValue); + ++inputIt; + ++outputIt; + } return output; } - /** - * Compute the intersection between regions edges. - * \return true if the intersection is not empty. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::ComputeEdgeEdgeBool(void) - { +/** + * Compute the intersection between regions edges. + * \return true if the intersection is not empty. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::ComputeEdgeEdgeBool(void) +{ /// Definition of the Filters used to compute the boolean - typedef itk::SubtractImageFilter<BoolImageType,BoolImageType,BoolImageType> SubtractFilterType; - typedef itk::BinaryBallStructuringElement<bool,BoolImageType::ImageDimension> BinaryBallStructuringElementType; - typedef itk::BinaryDilateImageFilter<BoolImageType,BoolImageType,BinaryBallStructuringElementType> DilateFilterType; - typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; - /// Declaration and instantiation - typename DilateFilterType::Pointer dilateFilter1 = DilateFilterType::New(); - typename DilateFilterType::Pointer dilateFilter2 = DilateFilterType::New(); - typename SubtractFilterType::Pointer subtractFilter1 = SubtractFilterType::New(); - typename SubtractFilterType::Pointer subtractFilter2 = SubtractFilterType::New(); - typename AndFilterType::Pointer andFilter = AndFilterType::New(); - /// Configuration of the erosion filter - BinaryBallStructuringElementType structElement1,structElement2; - structElement1.SetRadius(1); - structElement2.SetRadius(1); - structElement1.CreateStructuringElement(); - structElement2.CreateStructuringElement(); - dilateFilter1->SetKernel(structElement1); - dilateFilter2->SetKernel(structElement2); - /// The erosion is performed to get the surounding edge of this - /// region by substraction to the original image - dilateFilter1->SetInput(m_BoolImage1); - dilateFilter1->Update(); - subtractFilter1->SetInput2(m_BoolImage1); - subtractFilter1->SetInput1(dilateFilter1->GetOutput()); - subtractFilter1->Update(); - /// The erosion is performed to get the surounding edge of this - /// region by substraction to the original image - dilateFilter2->SetInput(m_BoolImage2); - dilateFilter2->Update(); - subtractFilter2->SetInput2(m_BoolImage2); - subtractFilter2->SetInput1(dilateFilter2->GetOutput()); - subtractFilter2->Update(); - /// Now we can compute the intersection between the 2 edges - andFilter->SetInput1(subtractFilter1->GetOutput()); - andFilter->SetInput2(subtractFilter2->GetOutput()); - andFilter->Update(); - /// test if the intersection is empty or not - return this->IsBoolImageNotEmpty(andFilter->GetOutput()); - } - /** - * Compute the intersection between exterior of region1 and - * interior of region2. - * \return true if the intersection is not empty. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::ComputeExterInterBool(void) - { + typedef itk::SubtractImageFilter<BoolImageType,BoolImageType,BoolImageType> SubtractFilterType; + typedef itk::BinaryBallStructuringElement<bool,BoolImageType::ImageDimension> BinaryBallStructuringElementType; + typedef itk::BinaryDilateImageFilter<BoolImageType,BoolImageType,BinaryBallStructuringElementType> DilateFilterType; + typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; + /// Declaration and instantiation + typename DilateFilterType::Pointer dilateFilter1 = DilateFilterType::New(); + typename DilateFilterType::Pointer dilateFilter2 = DilateFilterType::New(); + typename SubtractFilterType::Pointer subtractFilter1 = SubtractFilterType::New(); + typename SubtractFilterType::Pointer subtractFilter2 = SubtractFilterType::New(); + typename AndFilterType::Pointer andFilter = AndFilterType::New(); + /// Configuration of the erosion filter + BinaryBallStructuringElementType structElement1,structElement2; + structElement1.SetRadius(1); + structElement2.SetRadius(1); + structElement1.CreateStructuringElement(); + structElement2.CreateStructuringElement(); + dilateFilter1->SetKernel(structElement1); + dilateFilter2->SetKernel(structElement2); + /// The erosion is performed to get the surounding edge of this + /// region by substraction to the original image + dilateFilter1->SetInput(m_BoolImage1); + dilateFilter1->Update(); + subtractFilter1->SetInput2(m_BoolImage1); + subtractFilter1->SetInput1(dilateFilter1->GetOutput()); + subtractFilter1->Update(); + /// The erosion is performed to get the surounding edge of this + /// region by substraction to the original image + dilateFilter2->SetInput(m_BoolImage2); + dilateFilter2->Update(); + subtractFilter2->SetInput2(m_BoolImage2); + subtractFilter2->SetInput1(dilateFilter2->GetOutput()); + subtractFilter2->Update(); + /// Now we can compute the intersection between the 2 edges + andFilter->SetInput1(subtractFilter1->GetOutput()); + andFilter->SetInput2(subtractFilter2->GetOutput()); + andFilter->Update(); + /// test if the intersection is empty or not + return this->IsBoolImageNotEmpty(andFilter->GetOutput()); +} +/** + * Compute the intersection between exterior of region1 and + * interior of region2. + * \return true if the intersection is not empty. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::ComputeExterInterBool(void) +{ /// Definition of the filters used - typedef itk::InvertIntensityImageFilter<BoolImageType,BoolImageType> InvertFilterType; - typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; - /// Declaration and instantiation - typename InvertFilterType::Pointer invert = InvertFilterType::New(); - typename AndFilterType::Pointer andFilter = AndFilterType::New(); - /// The exterior is the inverted input image - invert->SetMaximum(true); - invert->SetInput(m_BoolImage1); - andFilter->SetInput1(m_BoolImage2); - andFilter->SetInput2(invert->GetOutput()); - andFilter->Update(); - /// test if the intersection is empty or not - return IsBoolImageNotEmpty(andFilter->GetOutput()); - } - /** - * Compute the intersection between interior of region1 and - * exterior of region2. - * \return true if the intersection is not empty. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::ComputeInterExterBool(void) - { - /// Definition of the filters used - typedef itk::InvertIntensityImageFilter<BoolImageType,BoolImageType> InvertFilterType; - typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; - //TODELETE typedef otb::Image<unsigned char,2> TmpImageType; - //TODELETE typedef itk::CastImageFilter<BoolImageType,TmpImageType> CastFilterType; + typedef itk::InvertIntensityImageFilter<BoolImageType,BoolImageType> InvertFilterType; + typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; + /// Declaration and instantiation + typename InvertFilterType::Pointer invert = InvertFilterType::New(); + typename AndFilterType::Pointer andFilter = AndFilterType::New(); + /// The exterior is the inverted input image + invert->SetMaximum(true); + invert->SetInput(m_BoolImage1); + andFilter->SetInput1(m_BoolImage2); + andFilter->SetInput2(invert->GetOutput()); + andFilter->Update(); + /// test if the intersection is empty or not + return IsBoolImageNotEmpty(andFilter->GetOutput()); +} +/** + * Compute the intersection between interior of region1 and + * exterior of region2. + * \return true if the intersection is not empty. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::ComputeInterExterBool(void) +{ + /// Definition of the filters used + typedef itk::InvertIntensityImageFilter<BoolImageType,BoolImageType> InvertFilterType; + typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; +//TODELETE typedef otb::Image<unsigned char,2> TmpImageType; +//TODELETE typedef itk::CastImageFilter<BoolImageType,TmpImageType> CastFilterType; - //TODELETE typedef ImageFileWriter<TmpImageType> WriterType; - /// Declaration and instantiation - typename InvertFilterType::Pointer invert = InvertFilterType::New(); - typename AndFilterType::Pointer andFilter = AndFilterType::New(); - /// The exterior is the inverted input image - invert->SetMaximum(true); - invert->SetInput(m_BoolImage2); +//TODELETE typedef ImageFileWriter<TmpImageType> WriterType; + /// Declaration and instantiation + typename InvertFilterType::Pointer invert = InvertFilterType::New(); + typename AndFilterType::Pointer andFilter = AndFilterType::New(); + /// The exterior is the inverted input image + invert->SetMaximum(true); + invert->SetInput(m_BoolImage2); - //TODELETE typename CastFilterType::Pointer caster = CastFilterType::New(); +//TODELETE typename CastFilterType::Pointer caster = CastFilterType::New(); //TODELETE caster->SetInput(invert->GetOutput()); - //TODELETE typename WriterType::Pointer writer = WriterType::New(); +//TODELETE typename WriterType::Pointer writer = WriterType::New(); //TODELETE writer->SetFileName("invert.tif"); - //TODELETE writer->SetInput(caster->GetOutput()); +//TODELETE writer->SetInput(caster->GetOutput()); //TODELETE writer->Update(); - andFilter->SetInput1(m_BoolImage1); - andFilter->SetInput2(invert->GetOutput()); - andFilter->Update(); + andFilter->SetInput1(m_BoolImage1); + andFilter->SetInput2(invert->GetOutput()); + andFilter->Update(); - //TODELETE caster = CastFilterType::New(); - //TODELETE caster->SetInput(andFilter->GetOutput()); - //TODELETE writer = WriterType::New(); - //TODELETE writer->SetFileName("and.tif"); - //TODELETE writer->SetInput(caster->GetOutput()); - //TODELETE writer->Update(); +//TODELETE caster = CastFilterType::New(); +//TODELETE caster->SetInput(andFilter->GetOutput()); +//TODELETE writer = WriterType::New(); +//TODELETE writer->SetFileName("and.tif"); +//TODELETE writer->SetInput(caster->GetOutput()); +//TODELETE writer->Update(); - /// test if the intersection is empty or not - return IsBoolImageNotEmpty(andFilter->GetOutput()); + /// test if the intersection is empty or not + return IsBoolImageNotEmpty(andFilter->GetOutput()); +} +/** + * Compute the intersection between regions interiors. + * \return true if the intersection is not empty. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::ComputeInterInterBool(void) +{ + /// Definition of the filters used + typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; + typedef itk::MinimumMaximumImageCalculator<BoolImageType> MinMaxCalculatorType; + /// Declaration and instantiation + typename AndFilterType::Pointer andFilter = AndFilterType::New(); + /// The exterior is the inverted input image + andFilter->SetInput1(m_BoolImage1); + andFilter->SetInput2(m_BoolImage2); + andFilter->Update(); + /// test if the intersection is empty or not + return IsBoolImageNotEmpty(andFilter->GetOutput()); +} +/** + * Compute the relation value from the input booleans. Please note + * that the actual computed value is set to the m_Value parameters, and has + * nothing to do with the returned boolean, which indicates if the determination + * process was successful. + * \param edgeEdgeBool True if edge-edge intersection is not empty. + * \param interExterBool True if interior-exterior intersection is not empty. + * \param ExterInterBool True if exterior-interior intersection is not empty. + * \return True if the decision process was successful. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::ComputeRelation(bool edgeEdgeBool, bool interExterBool, bool exterInterBool) +{ + // otbMsgDebugMacro(<<"RCC8Calculator->ComputeRelation()"); + // This decision process is based on a decision tree + if ((!interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) + { + m_Value=OTB_RCC8_EQ; + return true; } - /** - * Compute the intersection between regions interiors. - * \return true if the intersection is not empty. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::ComputeInterInterBool(void) + else if ((!interExterBool)&&(edgeEdgeBool)&&(exterInterBool)) { - /// Definition of the filters used - typedef itk::AndImageFilter<BoolImageType,BoolImageType,BoolImageType> AndFilterType; - typedef itk::MinimumMaximumImageCalculator<BoolImageType> MinMaxCalculatorType; - /// Declaration and instantiation - typename AndFilterType::Pointer andFilter = AndFilterType::New(); - /// The exterior is the inverted input image - andFilter->SetInput1(m_BoolImage1); - andFilter->SetInput2(m_BoolImage2); - andFilter->Update(); - /// test if the intersection is empty or not - return IsBoolImageNotEmpty(andFilter->GetOutput()); + m_Value=OTB_RCC8_TPP; + return true; } - /** - * Compute the relation value from the input booleans. Please note - * that the actual computed value is set to the m_Value parameters, and has - * nothing to do with the returned boolean, which indicates if the determination - * process was successful. - * \param edgeEdgeBool True if edge-edge intersection is not empty. - * \param interExterBool True if interior-exterior intersection is not empty. - * \param ExterInterBool True if exterior-interior intersection is not empty. - * \return True if the decision process was successful. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::ComputeRelation(bool edgeEdgeBool, bool interExterBool, bool exterInterBool) + else if ((interExterBool)&&(!edgeEdgeBool)&&(!exterInterBool)) { - // otbMsgDebugMacro(<<"RCC8Calculator->ComputeRelation()"); - // This decision process is based on a decision tree - if ((!interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) - { - m_Value=OTB_RCC8_EQ; - return true; - } - else if ((!interExterBool)&&(edgeEdgeBool)&&(exterInterBool)) - { - m_Value=OTB_RCC8_TPP; - return true; - } - else if ((interExterBool)&&(!edgeEdgeBool)&&(!exterInterBool)) - { - m_Value=OTB_RCC8_NTPPI; - return true; - } - else if ((interExterBool)&&(!edgeEdgeBool)&&(exterInterBool)) - { - m_Value=OTB_RCC8_DC; - return true; - } - else if ((interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) - { - m_Value=OTB_RCC8_TPPI; - return true; - } - else - { - return false; - } + m_Value=OTB_RCC8_NTPPI; + return true; } - /** - * Test if the boolean image is totally black or not. This is a based on the lazy operator - * paradigm. - * \param The image to test. - * \return True or false. - */ - template<class TInputImage> - bool - ImageToImageRCC8Calculator<TInputImage> - ::IsBoolImageNotEmpty(BoolImagePointerType image) + else if ((interExterBool)&&(!edgeEdgeBool)&&(exterInterBool)) { - typedef itk::ImageRegionConstIterator<BoolImageType> IteratorType; - // TODO : we'll eventually need to change something. - IteratorType it(image,image->GetLargestPossibleRegion()); - it.GoToBegin(); - while(!it.IsAtEnd()) - { - if(it.Get()) + m_Value=OTB_RCC8_DC; + return true; + } + else if ((interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) + { + m_Value=OTB_RCC8_TPPI; + return true; + } + else + { + return false; + } +} +/** + * Test if the boolean image is totally black or not. This is a based on the lazy operator + * paradigm. + * \param The image to test. + * \return True or false. + */ +template<class TInputImage> +bool +ImageToImageRCC8Calculator<TInputImage> +::IsBoolImageNotEmpty(BoolImagePointerType image) +{ + typedef itk::ImageRegionConstIterator<BoolImageType> IteratorType; + // TODO : we'll eventually need to change something. + IteratorType it(image,image->GetLargestPossibleRegion()); + it.GoToBegin(); + while (!it.IsAtEnd()) + { + if (it.Get()) { return true; } - ++it; - } - return false; + ++it; } - /** - * Main computation method. - */ - template <class TInputImage> - void - ImageToImageRCC8Calculator<TInputImage> - ::GenerateData(void) + return false; +} +/** + * Main computation method. + */ +template <class TInputImage> +void +ImageToImageRCC8Calculator<TInputImage> +::GenerateData(void) +{ + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData()"); + /// First we compute the minimal region of interest we will use for the relation computation + m_MinimalROI=this->ComputeMinimalRegion(); + /// If they are disjoint, the answer is trivial + if ((m_MinimalROI.GetSize()[0]<=1)||(m_MinimalROI.GetSize()[1]<=1)) { - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData()"); - /// First we compute the minimal region of interest we will use for the relation computation - m_MinimalROI=this->ComputeMinimalRegion(); - /// If they are disjoint, the answer is trivial - if((m_MinimalROI.GetSize()[0]<=1)||(m_MinimalROI.GetSize()[1]<=1)) - { - /// The relation is DC - m_Value=OTB_RCC8_DC; - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Disjoint regions"); - } - else - { - /// else each input images is cast to boolean type and reduced to - // the minimal region - m_BoolImage1=ConvertToBoolImage(this->GetInput1(),m_InsideValue1); - m_BoolImage2=ConvertToBoolImage(this->GetInput2(),m_InsideValue2); - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Bool images computed: "<<m_BoolImage1->GetLargestPossibleRegion().GetSize()); - /// Then the boolean which will be used to determine the relation - /// are declared - bool edgeEdgeBool,interExterBool,exterInterBool,interInterBool; - /// The boolean edgeEdge is needed in each case, so it si computed - /// now - edgeEdgeBool = ComputeEdgeEdgeBool(); - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): edgeEdge "<<edgeEdgeBool); - //TODELETE std::cout<<"RCC8Calculator->GenerateData(): edgeEdge "<<edgeEdgeBool<<std::endl; - /// Here comes the outside knowledge - if(this->GetLevel1APrioriKnowledge()) + /// The relation is DC + m_Value=OTB_RCC8_DC; + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Disjoint regions"); + } + else + { + /// else each input images is cast to boolean type and reduced to + // the minimal region + m_BoolImage1=ConvertToBoolImage(this->GetInput1(),m_InsideValue1); + m_BoolImage2=ConvertToBoolImage(this->GetInput2(),m_InsideValue2); + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Bool images computed: "<<m_BoolImage1->GetLargestPossibleRegion().GetSize()); + /// Then the boolean which will be used to determine the relation + /// are declared + bool edgeEdgeBool,interExterBool,exterInterBool,interInterBool; + /// The boolean edgeEdge is needed in each case, so it si computed + /// now + edgeEdgeBool = ComputeEdgeEdgeBool(); + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): edgeEdge "<<edgeEdgeBool); + //TODELETE std::cout<<"RCC8Calculator->GenerateData(): edgeEdge "<<edgeEdgeBool<<std::endl; + /// Here comes the outside knowledge + if (this->GetLevel1APrioriKnowledge()) { /// If the Level1APrioriKnowledge is set, then the /// interExterBool is set to true // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Level1APrioriKnowledge."); interExterBool=true; } - else + else { /// Else it must be computed interExterBool = ComputeInterExterBool(); // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): interExter "<<interExterBool); } - /// At this stage we can determine if the relation is of type NTPP - //TODELETE std::cout<<"RCC8Calculator->GenerateData(): interExter "<<interExterBool<<std::endl; - if((!interExterBool)&&(!edgeEdgeBool)) + /// At this stage we can determine if the relation is of type NTPP + //TODELETE std::cout<<"RCC8Calculator->GenerateData(): interExter "<<interExterBool<<std::endl; + if ((!interExterBool)&&(!edgeEdgeBool)) { m_Value=OTB_RCC8_NTPP; } - else + else { /// If not, we must consider the intersection between exterior - if(this->GetLevel3APrioriKnowledge()) - { - /// If the Level3APRioriKnowledge flag is set, this boolean - /// can be determined from the two others - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Level3APrioriKnowledge."); - exterInterBool=true; - } - else - { - /// Else it must be computed - exterInterBool = ComputeExterInterBool(); - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): ExterInter "<<exterInterBool); - } - //TODELETE std::cout<<"RCC8Calculator->GenerateData(): ExterInter "<<exterInterBool<<std::endl; - /// If it is not sufficient to compute the relation - if(!ComputeRelation(edgeEdgeBool,interExterBool,exterInterBool)) - { - /// Compute the last boolean - interInterBool = ComputeInterInterBool(); - //TODELETE std::cout<<"RCC8Calculator->GenerateData(): InterInter "<<interInterBool<<std::endl; - // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): InterInter "<<interInterBool); - /// Which allow the full determination - if ((interExterBool)&&(edgeEdgeBool)&&(exterInterBool)&&(!interInterBool)) + if (this->GetLevel3APrioriKnowledge()) { - m_Value=OTB_RCC8_EC; + /// If the Level3APRioriKnowledge flag is set, this boolean + /// can be determined from the two others + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): Level3APrioriKnowledge."); + exterInterBool=true; } - else + else { - m_Value=OTB_RCC8_PO; + /// Else it must be computed + exterInterBool = ComputeExterInterBool(); + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): ExterInter "<<exterInterBool); } + //TODELETE std::cout<<"RCC8Calculator->GenerateData(): ExterInter "<<exterInterBool<<std::endl; + /// If it is not sufficient to compute the relation + if (!ComputeRelation(edgeEdgeBool,interExterBool,exterInterBool)) + { + /// Compute the last boolean + interInterBool = ComputeInterInterBool(); + //TODELETE std::cout<<"RCC8Calculator->GenerateData(): InterInter "<<interInterBool<<std::endl; + // otbMsgDebugMacro(<<"RCC8Calculator->GenerateData(): InterInter "<<interInterBool); + /// Which allow the full determination + if ((interExterBool)&&(edgeEdgeBool)&&(exterInterBool)&&(!interInterBool)) + { + m_Value=OTB_RCC8_EC; + } + else + { + m_Value=OTB_RCC8_PO; } - } } + } } - /** - * PrintSelf method - */ - template<class TInputImage> - void - ImageToImageRCC8Calculator<TInputImage> - ::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - } +} +/** +* PrintSelf method +*/ +template<class TInputImage> +void +ImageToImageRCC8Calculator<TInputImage> +::PrintSelf( std::ostream& os,itk::Indent indent ) const +{ + Superclass::PrintSelf(os,indent); +} } // end namespace itk diff --git a/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.h b/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.h index 1b4f2e2bd8de98525e65b066241ace3e477b5f06..8483cfac69e05cea559322f2c197809527a0f0bc 100644 --- a/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.h +++ b/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.h @@ -34,7 +34,7 @@ namespace otb */ template <class TPolygonList, class TOutputGraph> class ITK_EXPORT PolygonListToRCC8GraphFilter - : public RCC8GraphSource<TOutputGraph> + : public RCC8GraphSource<TOutputGraph> { public: /** Standard class typedefs. */ @@ -46,7 +46,7 @@ public: itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(PolygonListToRCC8GraphFilter,RCC8GraphSource); - + /** Input related typedef */ typedef TPolygonList PolygonListType; typedef typename PolygonListType::ConstPointer PolygonListConstPointerType; @@ -68,7 +68,7 @@ public: /** RCC8 calculator typedef */ typedef PolygonToPolygonRCC8Calculator<PolygonType> RCC8CalculatorType; - + /** Graph iterators typedefs */ typedef RCC8VertexIterator<OutputGraphType> VertexIteratorType; typedef RCC8InEdgeIterator<OutputGraphType> InEdgeIteratorType; @@ -122,7 +122,7 @@ protected: /** Multi-threading implementation */ virtual void BeforeThreadedGenerateData(); - + virtual void AfterThreadedGenerateData(); /** startIndex and stopIndex represent the indeces of the vertex to diff --git a/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.txx b/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.txx index c3c0f24ffe62770e321a47a2f0b0c1528a3dd900..36a7368a31d3e58e6be1e4e1440659e4dc3afac6 100644 --- a/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.txx +++ b/Code/SpatialReasoning/otbPolygonListToRCC8GraphFilter.txx @@ -48,7 +48,7 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(0, - const_cast< PolygonListType * >( input ) ); + const_cast< PolygonListType * >( input ) ); } template <class TPolygonList, class TOutputGraph> @@ -57,12 +57,12 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> ::GetInput(void) { if (this->GetNumberOfInputs() < 1) - { + { return 0; - } - + } + return static_cast<const TPolygonList * > - (this->itk::ProcessObject::GetInput(0) ); + (this->itk::ProcessObject::GetInput(0) ); } @@ -81,11 +81,11 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> ::GetNumberOfRelations() { unsigned int result = 0; - for(unsigned int i = 0;i<8;++i) - { + for (unsigned int i = 0;i<8;++i) + { result+=m_Accumulator[i]; - } + } return result; } template <class TPolygonList, class TOutputGraph> @@ -106,40 +106,41 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> // otbMsgDebugMacro(<<"RCC8GraphFilter: entering GetKnowledge method."); // This is the RCC8 composition table const int knowledge[8][8] - ={ - /** DC EC PO TPP TPPi NTPP i EQ */ - /** DC */ {-3, -2, -2, -2, 0, -2, 0, 0}, - /** EC */ {-1, -3, -2, -3, -1, -3, 0, 1}, - /** PO */ {-1, -1, -3, -3, -1, -3, -1, 2}, - /** TPP */ { 0, -1, -2, -3, -3, 5, -1, 3}, - /** TPPi*/ {-1, -1, -1, -3, -1, -3, 6, 4}, - /** NTPP*/ { 0, 0, -2, 5, -2, 5, -3, 5}, - /** NTPPi*/{-1, -1, -1, -1, 6, -3, 6, 6}, - /** EQ */ { 0, 1, 2, 3, 4, 5, 6, 7} - }; + = + { + /** DC EC PO TPP TPPi NTPP i EQ */ + /** DC */ {-3, -2, -2, -2, 0, -2, 0, 0}, + /** EC */ {-1, -3, -2, -3, -1, -3, 0, 1}, + /** PO */ {-1, -1, -3, -3, -1, -3, -1, 2}, + /** TPP */ { 0, -1, -2, -3, -3, 5, -1, 3}, + /** TPPi*/ {-1, -1, -1, -3, -1, -3, 6, 4}, + /** NTPP*/ { 0, 0, -2, 5, -2, 5, -3, 5}, + /** NTPPi*/{-1, -1, -1, -1, 6, -3, 6, 6}, + /** EQ */ { 0, 1, 2, 3, 4, 5, 6, 7} + }; int value = knowledge[r1][r2]; // Each negative case correspond to a level of knowledge - if(value>=0) - { + if (value>=0) + { // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: FULL"); return KnowledgeStateType(FULL,static_cast<RCC8ValueType>(value)); - } - else if(value==-1) - { + } + else if (value==-1) + { // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method: LEVEL_1"); return KnowledgeStateType(LEVEL_1,OTB_RCC8_DC); - } - else if(value==-2) - { + } + else if (value==-2) + { // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.LEVEL_3"); return KnowledgeStateType(LEVEL_3,OTB_RCC8_DC); - } + } else - { + { // otbMsgDebugMacro(<<"RCC8GraphFilter: leaving GetKnowledge method.NO_INFO"); return KnowledgeStateType(NO_INFO,OTB_RCC8_DC); - } + } } /** * Main computation method. @@ -153,11 +154,11 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> // some calculations prior to splitting the main computations into // separate threads this->BeforeThreadedGenerateData(); - + // Set up the multithreaded processing ThreadStruct str; str.Filter = this; - + // // Initializing edges vectors per thread EdgeMapType defaultEdgeMap; m_EdgesPerThread = EdgeMapVectorType(this->GetNumberOfThreads(),defaultEdgeMap); @@ -165,7 +166,7 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> // Setting up multithreader this->GetMultiThreader()->SetNumberOfThreads(this->GetNumberOfThreads()); this->GetMultiThreader()->SetSingleMethod(this->ThreaderCallback, &str); - + // multithread the execution this->GetMultiThreader()->SingleMethodExecute(); @@ -194,30 +195,30 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> typedef typename PolygonListType::ConstIterator PolygonListConstIteratorType; // Loads the polygons list to graph nodes - for(PolygonListConstIteratorType it = inputPtr->Begin(); - it!=inputPtr->End();++it) - { + for (PolygonListConstIteratorType it = inputPtr->Begin(); + it!=inputPtr->End();++it) + { // Create a new vertex VertexPointerType vertex = VertexType::New(); // Set its properties vertex->SetPath(it.Get()); - + // look for the appropriate segmentation index - + unsigned int segIndex = 1; - while(segIndex < m_SegmentationRanges.size() && (nbVertices<m_SegmentationRanges[segIndex-1] || nbVertices >= m_SegmentationRanges[segIndex])) - { + while (segIndex < m_SegmentationRanges.size() && (nbVertices<m_SegmentationRanges[segIndex-1] || nbVertices >= m_SegmentationRanges[segIndex])) + { segIndex++; - } + } vertex->SetSegmentationLevel(segIndex-1); - + // Put it in the graph graph->SetVertex(nbVertices,vertex); otbMsgDevMacro(<<"Adding vertex: " <<nbVertices); ++nbVertices; - } + } } template <class TPolygonList, class TOutputGraph> @@ -233,7 +234,8 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> // invert value vector RCC8ValueType invert[8]={OTB_RCC8_DC,OTB_RCC8_EC,OTB_RCC8_PO,OTB_RCC8_TPPI, - OTB_RCC8_TPP,OTB_RCC8_NTPPI,OTB_RCC8_NTPP,OTB_RCC8_EQ}; + OTB_RCC8_TPP,OTB_RCC8_NTPPI,OTB_RCC8_NTPP,OTB_RCC8_EQ + }; unsigned int nbVertices = graph->GetNumberOfVertices(); itk::ProgressReporter progress(this,threadId,((int)stopIndex-(int)startIndex)*nbVertices); @@ -242,111 +244,111 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> VertexIteratorType vIt1(graph); VertexIteratorType vIt2(graph); - + unsigned int count = 0; // For each couple of vertices - for(vIt1.GoToBegin();!vIt1.IsAtEnd();++vIt1) - { + for (vIt1.GoToBegin();!vIt1.IsAtEnd();++vIt1) + { // TODO: this is not correct and should be replaced by a // vIt1(graph, index1, index2), which does not exist for the moment - if((count>=startIndex) && (count<stopIndex)) + if ((count>=startIndex) && (count<stopIndex)) + { + for (vIt2.GoToBegin();!vIt2.IsAtEnd();++vIt2) { - for(vIt2.GoToBegin();!vIt2.IsAtEnd();++vIt2) - { - //We do not examine each couple because of the RCC8 symmetry - if(vIt1.GetIndex()<vIt2.GetIndex()) - { - - // Compute the RCC8 relation - typename RCC8CalculatorType::Pointer calc = RCC8CalculatorType::New(); - calc->SetPolygon1(vIt1.Get()->GetPath()); - calc->SetPolygon2(vIt2.Get()->GetPath()); - RCC8ValueType value=OTB_RCC8_DC; - - // if the optimisations are activated - if(m_Optimisation) - { - // otbMsgDebugMacro(<<"RCC8GraphFilter: Entering optimisation loop"); - InEdgeIteratorType inIt1(vIt1.GetIndex(),graph); - InEdgeIteratorType inIt2(vIt2.GetIndex(),graph); - // otbMsgDebugMacro(<<"Optimisation loop: iterators initialised"); - VertexDescriptorType betweenIndex; - KnowledgeStateType know(NO_INFO,OTB_RCC8_DC); - inIt1.GoToBegin(); - - // Iterate through the edges going to the first vertex - while(!inIt1.IsAtEnd()&&(know.first!=FULL)) - { - betweenIndex = inIt1.GetSourceIndex(); - inIt2.GoToBegin(); - bool edgeFound = false; - while(!inIt2.IsAtEnd()&&(know.first!=FULL)) - { - // try to find an intermediate vertex between the two ones which - // we vant to compute the relationship - if(inIt2.GetSourceIndex()==betweenIndex) - { - // if an intermediate vertex is found - edgeFound = true; - // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); - // See if it brings some info on the RCCC8 value - know = GetKnowledge(invert[inIt1.GetValue()],inIt2.GetValue()); - calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); - calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); - // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); - } - ++inIt2; - } - // If no intermediate was found - if(!edgeFound) - { - // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); - // Try using a DC relationship - know = GetKnowledge(invert[inIt1.GetValue()],OTB_RCC8_DC); - calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); - calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); - // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); - } - ++inIt1; - } - // If the search has fully determined the RCC8 - if(know.first==FULL) - { - // Get the value - value=know.second; - } - else - { - // Else trigger the computation - // (which will take the optimisation phase info into account) - calc->Compute(); - value=calc->GetValue(); - } - // otbMsgDebugMacro(<<"RCC8GraphFilter: Leaving optimisation loop"); - } - // If the optimisations are not activated - else - { - calc->Compute(); - value=calc->GetValue(); - } - m_Accumulator[value]+=1; - m_Accumulator[invert[value]]+=1; - // If the vertices are connected - if(value>OTB_RCC8_DC) - { - // Add the edge to the graph. - otbMsgDevMacro(<<"Adding edge: "<<vIt1.GetIndex()<<" -> "<<vIt2.GetIndex()<<": "<<value); - m_EdgesPerThread[threadId][EdgePairType(vIt1.GetIndex(),vIt2.GetIndex())]=value; - } - } - progress.CompletedPixel(); - progress.CompletedPixel(); - } + //We do not examine each couple because of the RCC8 symmetry + if (vIt1.GetIndex()<vIt2.GetIndex()) + { + + // Compute the RCC8 relation + typename RCC8CalculatorType::Pointer calc = RCC8CalculatorType::New(); + calc->SetPolygon1(vIt1.Get()->GetPath()); + calc->SetPolygon2(vIt2.Get()->GetPath()); + RCC8ValueType value=OTB_RCC8_DC; + + // if the optimisations are activated + if (m_Optimisation) + { + // otbMsgDebugMacro(<<"RCC8GraphFilter: Entering optimisation loop"); + InEdgeIteratorType inIt1(vIt1.GetIndex(),graph); + InEdgeIteratorType inIt2(vIt2.GetIndex(),graph); + // otbMsgDebugMacro(<<"Optimisation loop: iterators initialised"); + VertexDescriptorType betweenIndex; + KnowledgeStateType know(NO_INFO,OTB_RCC8_DC); + inIt1.GoToBegin(); + + // Iterate through the edges going to the first vertex + while (!inIt1.IsAtEnd()&&(know.first!=FULL)) + { + betweenIndex = inIt1.GetSourceIndex(); + inIt2.GoToBegin(); + bool edgeFound = false; + while (!inIt2.IsAtEnd()&&(know.first!=FULL)) + { + // try to find an intermediate vertex between the two ones which + // we vant to compute the relationship + if (inIt2.GetSourceIndex()==betweenIndex) + { + // if an intermediate vertex is found + edgeFound = true; + // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); + // See if it brings some info on the RCCC8 value + know = GetKnowledge(invert[inIt1.GetValue()],inIt2.GetValue()); + calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); + calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); + // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); + } + ++inIt2; + } + // If no intermediate was found + if (!edgeFound) + { + // otbMsgDebugMacro(<<"Optimisation loop: found an intermediary vertex:" <<betweenIndex); + // Try using a DC relationship + know = GetKnowledge(invert[inIt1.GetValue()],OTB_RCC8_DC); + calc->SetLevel1APrioriKnowledge(know.first==LEVEL_1); + calc->SetLevel3APrioriKnowledge(know.first==LEVEL_3); + // otbMsgDebugMacro(<<"Optimisation loop: knowledge: "<<know.first<<","<<know.second); + } + ++inIt1; + } + // If the search has fully determined the RCC8 + if (know.first==FULL) + { + // Get the value + value=know.second; + } + else + { + // Else trigger the computation + // (which will take the optimisation phase info into account) + calc->Compute(); + value=calc->GetValue(); + } + // otbMsgDebugMacro(<<"RCC8GraphFilter: Leaving optimisation loop"); + } + // If the optimisations are not activated + else + { + calc->Compute(); + value=calc->GetValue(); + } + m_Accumulator[value]+=1; + m_Accumulator[invert[value]]+=1; + // If the vertices are connected + if (value>OTB_RCC8_DC) + { + // Add the edge to the graph. + otbMsgDevMacro(<<"Adding edge: "<<vIt1.GetIndex()<<" -> "<<vIt2.GetIndex()<<": "<<value); + m_EdgesPerThread[threadId][EdgePairType(vIt1.GetIndex(),vIt2.GetIndex())]=value; + } + } + progress.CompletedPixel(); + progress.CompletedPixel(); } - ++count; } + ++count; + } otbMsgDebugMacro(<<"End thread "<<threadId); } @@ -358,37 +360,37 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> { // in order to have the same output graph whatever the number of // thread is, we use a map to sort the edges in lexicographical - // order + // order OutputGraphPointerType graph = this->GetOutput(); EdgeMapType globalEdgeMap; - + // merge all edges - for(typename EdgeMapVectorType::iterator vIt = m_EdgesPerThread.begin(); - vIt!=m_EdgesPerThread.end();++vIt) + for (typename EdgeMapVectorType::iterator vIt = m_EdgesPerThread.begin(); + vIt!=m_EdgesPerThread.end();++vIt) + { + for (typename EdgeMapType::iterator mIt = (*vIt).begin(); + mIt != (*vIt).end();++mIt) { - for(typename EdgeMapType::iterator mIt = (*vIt).begin(); - mIt != (*vIt).end();++mIt) - { globalEdgeMap[mIt->first]=mIt->second; - } } + } // Report edges to the graph - for(typename EdgeMapType::iterator mIt = globalEdgeMap.begin(); - mIt != globalEdgeMap.end();++mIt) - { - graph->AddEdge(mIt->first.first,mIt->first.second,mIt->second); - } + for (typename EdgeMapType::iterator mIt = globalEdgeMap.begin(); + mIt != globalEdgeMap.end();++mIt) + { + graph->AddEdge(mIt->first.first,mIt->first.second,mIt->second); + } } // Callback routine used by the threading library. This routine just calls // the ThreadedGenerateData method after setting the correct region for this -// thread. +// thread. template <class TPolygonList, class TOutputGraph> -ITK_THREAD_RETURN_TYPE +ITK_THREAD_RETURN_TYPE PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> ::ThreaderCallback( void *arg ) { @@ -403,28 +405,28 @@ PolygonListToRCC8GraphFilter<TPolygonList, TOutputGraph> total = str->Filter->GetOutput()->GetNumberOfVertices(); if (threadId < static_cast<int>(total)) - { - + { + // Split the adjacency matrix in strip of equal dimension start = static_cast<unsigned int>(vcl_floor(total*vcl_sqrt(static_cast<double>(threadId)/static_cast<double>(threadCount))+0.5)); stop = static_cast<unsigned int>(vcl_floor(total*vcl_sqrt(static_cast<double>(threadId+1)/static_cast<double>(threadCount))+0.5)); if (stop > total) stop = total; - + // For very small graphs it might occur that start = stop. In this // case the vertex at that index will be processed in the next strip. - if(start!=stop) - { + if (start!=stop) + { str->Filter->ThreadedGenerateData(start, stop, threadId); - } } + } // else // { // otherwise don't use this thread. Sometimes the threads dont - // break up very well and it is just as efficient to leave a + // break up very well and it is just as efficient to leave a // few threads idle. // } - + return ITK_THREAD_RETURN_VALUE; } diff --git a/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.h b/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.h index 354708da7f395b7b281656531ed6a479f9a7358d..3d35210fe122087cc455430ded45af4567448995 100644 --- a/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.h +++ b/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.h @@ -45,7 +45,7 @@ namespace otb * of regiosn, it is optimised : the decision is managed by a decision tree. */ template <class TInputPolygon> - class ITK_EXPORT PolygonToPolygonRCC8Calculator : public itk::Object +class ITK_EXPORT PolygonToPolygonRCC8Calculator : public itk::Object { public: /** Standard class typedefs. */ @@ -100,7 +100,7 @@ public: virtual bool RegionsIntersectionIsNull(const RegionType& region1, const RegionType& region2); - protected: +protected: /** Constructor */ PolygonToPolygonRCC8Calculator(); /** Destructor */ @@ -108,7 +108,7 @@ public: /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** The RCC8 relation value */ RCC8ValueType m_Value; /** Decision tree Level 1 A priori knowledge */ diff --git a/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.txx b/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.txx index 303e896ffb561296a3d158af3eb9b297d71941c8..42c253348ab074c86ad7e7b5e0d889f92ec94258 100644 --- a/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.txx +++ b/Code/SpatialReasoning/otbPolygonToPolygonRCC8Calculator.txx @@ -55,10 +55,10 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> // First check if bounding regions are disjoints RegionType region1 = m_Polygon1->GetBoundingRegion(); RegionType region2 = m_Polygon2->GetBoundingRegion(); - + // If intersection is not null, we have to do the computation - if(!RegionsIntersectionIsNull(region1,region2)) - { + if (!RegionsIntersectionIsNull(region1,region2)) + { bool edgeEdgeBool,interExterBool,exterInterBool,interInterBool; /// The boolean edgeEdge is needed in each case, so it si computed @@ -67,60 +67,60 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> //std::cout<<"EdgeEdge: "<<edgeEdgeBool<<std::endl; - if(this->GetLevel1APrioriKnowledge()) - { + if (this->GetLevel1APrioriKnowledge()) + { interExterBool=true; - } + } else - { + { /// Else it must be computed interExterBool = ComputeInterExter(m_Polygon1,m_Polygon2); - } + } //std::cout<<"InterExter: "<<interExterBool<<std::endl; /// At this stage we can determine if the relation is of type NTPP - if((!interExterBool)&&(!edgeEdgeBool)) - { + if ((!interExterBool)&&(!edgeEdgeBool)) + { m_Value=OTB_RCC8_NTPP; - } + } else - { + { /// If not, we must consider the intersection between exterior - if(this->GetLevel3APrioriKnowledge()) - { - /// If the Level3APRioriKnowledge flag is set, this boolean - /// can be determined from the two others - exterInterBool=true; - } + if (this->GetLevel3APrioriKnowledge()) + { + /// If the Level3APRioriKnowledge flag is set, this boolean + /// can be determined from the two others + exterInterBool=true; + } else - { - /// Else it must be computed - exterInterBool = ComputeInterExter(m_Polygon2,m_Polygon1); - } + { + /// Else it must be computed + exterInterBool = ComputeInterExter(m_Polygon2,m_Polygon1); + } //std::cout<<"ExterInter: "<<exterInterBool<<std::endl; /// If it is not sufficient to compute the relation - if(!ComputeRelation(edgeEdgeBool,interExterBool,exterInterBool)) - { - /// Compute the last boolean - interInterBool = ComputeInterInter(m_Polygon1,m_Polygon2); - - //std::cout<<"InterInter: "<<interInterBool<<std::endl; - - /// Which allow the full determination - if ((interExterBool)&&(edgeEdgeBool)&&(exterInterBool)&&(!interInterBool)) - { - m_Value=OTB_RCC8_EC; - } - else - { - m_Value=OTB_RCC8_PO; - } - } + if (!ComputeRelation(edgeEdgeBool,interExterBool,exterInterBool)) + { + /// Compute the last boolean + interInterBool = ComputeInterInter(m_Polygon1,m_Polygon2); + + //std::cout<<"InterInter: "<<interInterBool<<std::endl; + + /// Which allow the full determination + if ((interExterBool)&&(edgeEdgeBool)&&(exterInterBool)&&(!interInterBool)) + { + m_Value=OTB_RCC8_EC; + } + else + { + m_Value=OTB_RCC8_PO; + } } } + } } template<class TInputPolygon> @@ -128,17 +128,17 @@ bool PolygonToPolygonRCC8Calculator<TInputPolygon> ::RegionsIntersectionIsNull(const RegionType& region1, const RegionType& region2) { - for(unsigned int dim = 0; dim<RegionType::ImageDimension;++dim) + for (unsigned int dim = 0; dim<RegionType::ImageDimension;++dim) + { + if (region1.GetIndex()[dim]+static_cast<int>(region1.GetSize()[dim]) < region2.GetIndex()[dim]) { - if(region1.GetIndex()[dim]+static_cast<int>(region1.GetSize()[dim]) < region2.GetIndex()[dim]) - { return true; - } - else if(region2.GetIndex()[dim]+static_cast<int>(region2.GetSize()[dim]) < region1.GetIndex()[dim]) - { + } + else if (region2.GetIndex()[dim]+static_cast<int>(region2.GetSize()[dim]) < region1.GetIndex()[dim]) + { return true; - } } + } return false; } @@ -150,34 +150,34 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> { // This decision process is based on a decision tree if ((!interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) - { + { m_Value=OTB_RCC8_EQ; return true; - } + } else if ((!interExterBool)&&(edgeEdgeBool)&&(exterInterBool)) - { + { m_Value=OTB_RCC8_TPP; return true; - } + } else if ((interExterBool)&&(!edgeEdgeBool)&&(!exterInterBool)) - { + { m_Value=OTB_RCC8_NTPPI; return true; - } + } else if ((interExterBool)&&(!edgeEdgeBool)&&(exterInterBool)) - { + { m_Value=OTB_RCC8_DC; return true; - } + } else if ((interExterBool)&&(edgeEdgeBool)&&(!exterInterBool)) - { + { m_Value=OTB_RCC8_TPPI; return true; - } + } else - { + { return false; - } + } } template<class TInputPolygon> @@ -199,39 +199,39 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> //std::cout<<current<<" is on edge: "<<polygon2->IsOnEdge(current)<<std::endl; unsigned int index = 0; - if(isExterior) - { + if (isExterior) + { resp = true; - } + } ++it; while (!resp && it != it_end) - { + { bool nextIsInside = polygon2->IsInside(it.Value()); if (isInside && nextIsInside) - { + { //std::cout<<current<<" is inside and "<<it.Value()<<" is inside, nb crossings: "<<polygon2->NbCrossing(current,it.Value())<<std::endl; resp = polygon2->NbCrossing(current,it.Value()) >0; - } + } current = it.Value(); isInside = nextIsInside; isExterior = !isInside && !polygon2->IsOnEdge(current); //std::cout<<current<<" is inside: "<<isInside<<std::endl; //std::cout<<current<<" is on edge: "<<polygon2->IsOnEdge(current)<<std::endl; - if(isExterior) - { + if (isExterior) + { resp = true; - } + } ++index; ++it; - } + } - if(!resp && isInside && firstIsInside) - { + if (!resp && isInside && firstIsInside) + { resp = polygon2->NbCrossing(current,first)>0; //std::cout<<current<<" is inside and "<<first<<" is inside, nb crossings: "<<polygon2->NbCrossing(current,first)<<std::endl; - } + } return resp; } @@ -250,37 +250,37 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> bool currentIsInside = polygon2->IsInside(current); bool firstIsInside = currentIsInside; - if(currentIsInside) - { + if (currentIsInside) + { resp = true; - } + } ++it; while (!resp && it != it_end) - { + { bool nextIsInside = polygon2->IsInside(it.Value()); if (!currentIsInside && !nextIsInside && !polygon2->IsOnEdge(current) && !polygon2->IsOnEdge(it.Value())) - { + { unsigned int nbCrossings = polygon2->NbCrossing(current,it.Value()); resp = nbCrossings>0; - } + } currentIsInside =nextIsInside; current = it.Value(); - if(currentIsInside) - { + if (currentIsInside) + { resp = true; - } - ++it; } + ++it; + } if (!resp && !currentIsInside && !firstIsInside && !polygon2->IsOnEdge(current) && !polygon2->IsOnEdge(first)) - { + { unsigned int nbCrossings = polygon2->NbCrossing(current,first); resp = nbCrossings>0; - } + } return resp; } template<class TInputPolygon> @@ -299,36 +299,36 @@ PolygonToPolygonRCC8Calculator<TInputPolygon> ++it; while (! resp && it != it_end) + { + if (polygon2->NbTouching(current,it.Value())>0) { - if(polygon2->NbTouching(current,it.Value())>0) - { resp = true; //std::cout<<"NbCrossing: "<<current<<" -> "<<it.Value()<<": "<<polygon2->NbCrossing(current,it.Value())<<std::endl; - } - if(polygon2->NbCrossing(current,it.Value())>0) - { + } + if (polygon2->NbCrossing(current,it.Value())>0) + { resp = true; //std::cout<<"NbTouching: "<<current<<" -> "<<it.Value()<<": "<<polygon2->NbTouching(current,it.Value())<<std::endl; - } + } current = it.Value(); - if(polygon2->IsOnEdge(current)) - { + if (polygon2->IsOnEdge(current)) + { resp = true; //std::cout<<"IsOnEdge: "<<current<<": "<<polygon2->IsOnEdge(current)<<std::endl; - } - ++it; } - if(!resp && polygon2->NbTouching(current,first)>0) - { + ++it; + } + if (!resp && polygon2->NbTouching(current,first)>0) + { resp = true; //std::cout<<"NbCrossing: "<<current<<" -> "<<first<<": "<<polygon2->NbCrossing(current,first)<<std::endl; - } - if(polygon2->NbCrossing(current,first)>0) - { + } + if (polygon2->NbCrossing(current,first)>0) + { resp = true; //std::cout<<"NbTouching: "<<current<<" -> "<<first<<": "<<polygon2->NbTouching(current,first)<<std::endl; - } + } return resp; } diff --git a/Code/SpatialReasoning/otbRCC8Edge.cxx b/Code/SpatialReasoning/otbRCC8Edge.cxx index c226a2ee0ca4df8a0f3b2fef0dfe9cdec1f3632c..c9b07d859e44b7fdbaf7f255b350fd85f236fbf5 100644 --- a/Code/SpatialReasoning/otbRCC8Edge.cxx +++ b/Code/SpatialReasoning/otbRCC8Edge.cxx @@ -25,15 +25,15 @@ namespace otb */ RCC8Edge::RCC8Edge() { - m_Value = OTB_RCC8_DC; + m_Value = OTB_RCC8_DC; } /** * PrintSelf method */ void RCC8Edge::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"RCC8 Value: "<<m_Value<<std::endl; - } +{ + Superclass::PrintSelf(os,indent); + os<<indent<<"RCC8 Value: "<<m_Value<<std::endl; +} } // end namespace otb diff --git a/Code/SpatialReasoning/otbRCC8Edge.h b/Code/SpatialReasoning/otbRCC8Edge.h index 1d8db9010a1488f29e98c94fb6a712c1129e9ce5..1106d6972e9b502419e9dcb517c20591602f2212 100644 --- a/Code/SpatialReasoning/otbRCC8Edge.h +++ b/Code/SpatialReasoning/otbRCC8Edge.h @@ -31,7 +31,7 @@ namespace otb */ class ITK_EXPORT RCC8Edge : public itk::DataObject { - public: +public: /** Standard class typedefs */ typedef RCC8Edge Self; typedef itk::DataObject Superclass; @@ -42,7 +42,7 @@ class ITK_EXPORT RCC8Edge : public itk::DataObject /** Run-time type information (and related methods). */ itkTypeMacro(RCC8Edge,DataObject); /** RCC8 values typedef */ - typedef RCC8Value RCC8ValueType; + typedef RCC8Value RCC8ValueType; /** RCC8 relation value accessors */ itkGetMacro(Value,RCC8ValueType); itkSetMacro(Value,RCC8ValueType); @@ -51,11 +51,11 @@ protected: /** Constructor */ RCC8Edge(); /** Desctructor */ - ~RCC8Edge(){}; -/** PrintSelf method */ + ~RCC8Edge() {}; + /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** The RCC8 value */ RCC8ValueType m_Value; }; diff --git a/Code/SpatialReasoning/otbRCC8EdgeIterator.h b/Code/SpatialReasoning/otbRCC8EdgeIterator.h index 3ee3fdb5f5ebc8a808487d3e1d792ea821fd2e1a..597059d91a5949d7de9002e15b4cc50fccb0f5b0 100644 --- a/Code/SpatialReasoning/otbRCC8EdgeIterator.h +++ b/Code/SpatialReasoning/otbRCC8EdgeIterator.h @@ -29,7 +29,7 @@ namespace otb template <class TGraph> class ITK_EXPORT RCC8EdgeIterator { - public: +public: /** self typedef */ typedef RCC8EdgeIterator Self; @@ -48,19 +48,19 @@ class ITK_EXPORT RCC8EdgeIterator /** Constructor */ RCC8EdgeIterator(); - /** Copy constructor */ - RCC8EdgeIterator(const Self& iter); - /** Constructor with input graph */ - RCC8EdgeIterator(TGraph * graph); + /** Copy constructor */ + RCC8EdgeIterator(const Self& iter); + /** Constructor with input graph */ + RCC8EdgeIterator(TGraph * graph); /** * Get the current edge value. * \return The value of the current edge pointed by the iterator. */ RCC8ValueType GetValue(void); - /** - * Return the source vertex of the current edge. - * \return The source edge. - */ + /** + * Return the source vertex of the current edge. + * \return The source edge. + */ VertexPointerType GetSourceVertex(void); /** * Return the target vertex of the current edge. @@ -78,15 +78,15 @@ class ITK_EXPORT RCC8EdgeIterator */ VertexDescriptorType GetTargetIndex(void); - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - bool IsAtEnd(void); - /** - * Go to the beginning. - */ - void GoToBegin(void); + /** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ + bool IsAtEnd(void); + /** + * Go to the beginning. + */ + void GoToBegin(void); /** * Increment. */ @@ -116,7 +116,7 @@ class ITK_EXPORT RCC8EdgeIterator * Instantiation operator. */ Self& operator=(const Self& it); - private: +private: // End InternalIteratorType m_End; // Internal iterator. diff --git a/Code/SpatialReasoning/otbRCC8EdgeIterator.txx b/Code/SpatialReasoning/otbRCC8EdgeIterator.txx index 50e7ff568664f4cbbbf44015e5e6120e1e6f0966..c9bb0c5d708c64529c9285bb240cb46f49689a2d 100644 --- a/Code/SpatialReasoning/otbRCC8EdgeIterator.txx +++ b/Code/SpatialReasoning/otbRCC8EdgeIterator.txx @@ -22,197 +22,197 @@ namespace otb { - /** Constructor */ - template <class TGraph> - RCC8EdgeIterator<TGraph> - ::RCC8EdgeIterator() - { +/** Constructor */ +template <class TGraph> +RCC8EdgeIterator<TGraph> +::RCC8EdgeIterator() +{ m_Graph = GraphType::New(); tie(m_Iter,m_End)=edges(*m_Graph->GetGraph()); - } - /** - * Copy operator. - */ - template <class TGraph> - RCC8EdgeIterator<TGraph> - ::RCC8EdgeIterator(const Self& iter) - { - m_Iter=iter.m_Iter; - m_Graph=iter.m_Graph; - m_End=iter.m_End; - } - /** - *Constructor with input graph - */ - template <class TGraph> - RCC8EdgeIterator<TGraph> - ::RCC8EdgeIterator(TGraph * graph) - { - m_Graph=graph; - tie(m_Iter,m_End)=edges(*m_Graph->GetGraph()); - } - /** - * Get the current edge value. - * \return The value of the current edge pointed by the iterator. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::RCC8ValueType - RCC8EdgeIterator<TGraph> - ::GetValue(void) - { - return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); - } - /** - * Return the source vertex of the current edge. - * \return The source edge. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::VertexPointerType - RCC8EdgeIterator<TGraph> - ::GetSourceVertex(void) - { - return (*m_Graph->GetGraph())[source(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return the target vertex of the current edge. - * \return The target vertex. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::VertexPointerType - RCC8EdgeIterator<TGraph> - ::GetTargetVertex(void) - { - return (*m_Graph->GetGraph())[target(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return the source vertex index of the current edge. - * \return The souce vertex index. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::VertexDescriptorType - RCC8EdgeIterator<TGraph> - ::GetSourceIndex(void) - { - IndexMapType index = get(boost::vertex_index, (*m_Graph->GetGraph())); - return index[source(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return the target vertex index of the current edge. - * \return The target vertex index. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::VertexDescriptorType - RCC8EdgeIterator<TGraph> - ::GetTargetIndex(void) - { - IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); - return index[target(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - template <class TGraph> - bool - RCC8EdgeIterator<TGraph> - ::IsAtEnd(void) - { - return (m_Iter==m_End); - } - /** - * Go to the beginning. - */ - template <class TGraph> - void - RCC8EdgeIterator<TGraph> - ::GoToBegin(void) - { - tie(m_Iter,m_End)=edges(*m_Graph->GetGraph()); - } - /** - * Increment. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::Self& - RCC8EdgeIterator<TGraph> - ::operator++() - { - ++m_Iter; - return *this; - } - /** - * Decrement. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::Self& - RCC8EdgeIterator<TGraph> - ::operator--() - { - --m_Iter; - return *this; - } - /** - * Add - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::Self& - RCC8EdgeIterator<TGraph> - ::operator+(int i) - { - m_Iter=m_Iter+i; - return *this; - } - /** - * Remove - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::Self& - RCC8EdgeIterator<TGraph> - ::operator-(int i) - { - m_Iter=m_Iter-i; - return *this; - } - /** - * Difference comparison operator. - */ - template <class TGraph> - bool - RCC8EdgeIterator<TGraph> - ::operator!=(const Self& iter) - { - return (m_Iter != iter.m_Iter); - } - /** - * Equality comparison operator. - */ - template <class TGraph> - bool - RCC8EdgeIterator<TGraph> - ::operator==(const Self& iter) - { - return (m_Iter == iter.m_Iter); - } - /** - * Instantiation operator. - */ - template <class TGraph> - typename RCC8EdgeIterator<TGraph> - ::Self& - RCC8EdgeIterator<TGraph> - ::operator=(const Self& iter) - { - m_Iter = iter.m_Iter; - return *this; - } +} +/** + * Copy operator. + */ +template <class TGraph> +RCC8EdgeIterator<TGraph> +::RCC8EdgeIterator(const Self& iter) +{ + m_Iter=iter.m_Iter; + m_Graph=iter.m_Graph; + m_End=iter.m_End; +} +/** + *Constructor with input graph + */ +template <class TGraph> +RCC8EdgeIterator<TGraph> +::RCC8EdgeIterator(TGraph * graph) +{ + m_Graph=graph; + tie(m_Iter,m_End)=edges(*m_Graph->GetGraph()); +} +/** + * Get the current edge value. + * \return The value of the current edge pointed by the iterator. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::RCC8ValueType +RCC8EdgeIterator<TGraph> +::GetValue(void) +{ + return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); +} +/** + * Return the source vertex of the current edge. + * \return The source edge. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::VertexPointerType +RCC8EdgeIterator<TGraph> +::GetSourceVertex(void) +{ + return (*m_Graph->GetGraph())[source(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return the target vertex of the current edge. + * \return The target vertex. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::VertexPointerType +RCC8EdgeIterator<TGraph> +::GetTargetVertex(void) +{ + return (*m_Graph->GetGraph())[target(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return the source vertex index of the current edge. + * \return The souce vertex index. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::VertexDescriptorType +RCC8EdgeIterator<TGraph> +::GetSourceIndex(void) +{ + IndexMapType index = get(boost::vertex_index, (*m_Graph->GetGraph())); + return index[source(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return the target vertex index of the current edge. + * \return The target vertex index. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::VertexDescriptorType +RCC8EdgeIterator<TGraph> +::GetTargetIndex(void) +{ + IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); + return index[target(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ +template <class TGraph> +bool +RCC8EdgeIterator<TGraph> +::IsAtEnd(void) +{ + return (m_Iter==m_End); +} +/** + * Go to the beginning. + */ +template <class TGraph> +void +RCC8EdgeIterator<TGraph> +::GoToBegin(void) +{ + tie(m_Iter,m_End)=edges(*m_Graph->GetGraph()); +} +/** + * Increment. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::Self& +RCC8EdgeIterator<TGraph> +::operator++() +{ + ++m_Iter; + return *this; +} +/** + * Decrement. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::Self& +RCC8EdgeIterator<TGraph> +::operator--() +{ + --m_Iter; + return *this; +} +/** + * Add + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::Self& +RCC8EdgeIterator<TGraph> +::operator+(int i) +{ + m_Iter=m_Iter+i; + return *this; +} +/** + * Remove + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::Self& +RCC8EdgeIterator<TGraph> +::operator-(int i) +{ + m_Iter=m_Iter-i; + return *this; +} +/** + * Difference comparison operator. + */ +template <class TGraph> +bool +RCC8EdgeIterator<TGraph> +::operator!=(const Self& iter) +{ + return (m_Iter != iter.m_Iter); +} +/** + * Equality comparison operator. + */ +template <class TGraph> +bool +RCC8EdgeIterator<TGraph> +::operator==(const Self& iter) +{ + return (m_Iter == iter.m_Iter); +} +/** + * Instantiation operator. + */ +template <class TGraph> +typename RCC8EdgeIterator<TGraph> +::Self& +RCC8EdgeIterator<TGraph> +::operator=(const Self& iter) +{ + m_Iter = iter.m_Iter; + return *this; +} } // End namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8Graph.h b/Code/SpatialReasoning/otbRCC8Graph.h index 0398a46b42d92cb13f3743f41b12957b1a43d56a..3f1af44f9cb9db1830222923f9bbcfc392a125ee 100644 --- a/Code/SpatialReasoning/otbRCC8Graph.h +++ b/Code/SpatialReasoning/otbRCC8Graph.h @@ -42,9 +42,9 @@ namespace otb */ template <class TVertex> class ITK_EXPORT RCC8Graph : - public itk::DataObject + public itk::DataObject { - public: +public: /** Standard class typedefs. */ typedef RCC8Graph Self; typedef itk::DataObject Superclass; @@ -64,7 +64,7 @@ class ITK_EXPORT RCC8Graph : /** Typedef for the boost graph representation */ typedef boost::adjacency_list <boost::vecS,boost::vecS,boost::bidirectionalS, - VertexPointerType,EdgePointerType> InternalGraphType; + VertexPointerType,EdgePointerType> InternalGraphType; /** Edges and vertices descriptors typedefs (boost objects)*/ typedef typename InternalGraphType::vertex_descriptor VertexDescriptorType; typedef typename InternalGraphType::edge_descriptor EdgeDescriptorType; @@ -77,7 +77,10 @@ class ITK_EXPORT RCC8Graph : * Return the internal boost graph object. * \return The internal boost graph object */ - InternalGraphType * GetGraph(void){return &m_Graph;}; + InternalGraphType * GetGraph(void) + { + return &m_Graph; + }; /** * Since the number of vertices is mandatory to instantiate the * internal boost representation, the build method has to be called @@ -113,14 +116,14 @@ protected: /** Constructor */ RCC8Graph(); /** Destructor */ - ~RCC8Graph(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; - /** - * Initialize a range of vertex. - * \param num The index of the last vertices to intialize. - */ - void Initialize( unsigned int num); + ~RCC8Graph() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; + /** + * Initialize a range of vertex. + * \param num The index of the last vertices to intialize. + */ + void Initialize( unsigned int num); diff --git a/Code/SpatialReasoning/otbRCC8Graph.txx b/Code/SpatialReasoning/otbRCC8Graph.txx index 3ffe7011d1c9498a9b0552d6378010218136524e..dc01539f4cdc61ab35c83e6d02c236244741e0f6 100644 --- a/Code/SpatialReasoning/otbRCC8Graph.txx +++ b/Code/SpatialReasoning/otbRCC8Graph.txx @@ -20,111 +20,111 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TVertex> - RCC8Graph<TVertex> - ::RCC8Graph() - { - m_NumberOfVertices = 0; - }; - /** - * since the number of vertices is mandatory to instantiate the - * internal boost representation, the build method has to be called - * once this parameter is set. - */ - template <class TVertex> - void - RCC8Graph<TVertex> - ::Build(void) - { - this->Initialize(m_NumberOfVertices-1); - } - /** - * Initialize a range of vertex. - * \param num The index of the last vertices to intialize. - */ - template <class TVertex> - void - RCC8Graph<TVertex> - ::Initialize( unsigned int num) - { - for(unsigned int i = boost::num_vertices(m_Graph); i<=num;i++) - { - VertexDescriptorType id = boost::add_vertex(m_Graph); - VertexPointerType vertex = VertexType::New(); - m_Graph[id]=vertex; - } - } - /** - * Set a vertex. - * \param index The index of the vertex in the graph. - * \param vertex The vertex to set. - */ - template<class TVertex> - void - RCC8Graph<TVertex> - ::SetVertex(unsigned int index, VertexPointerType vertex) - { - if(index>=m_NumberOfVertices) - { - this->Initialize(index); - m_NumberOfVertices = index+1; - } - VertexDescriptorType v = *boost::vertices(m_Graph).first; - m_Graph[v+index]= vertex; - } - /** - * Get a vertex. - * \param index The index of the vertex in the graph - * \return The vertex. - */ - template <class TVertex> - typename RCC8Graph<TVertex> - ::VertexPointerType - RCC8Graph<TVertex> - ::GetVertex(unsigned int index) - { - VertexDescriptorType v = *boost::vertices(m_Graph).first; - return m_Graph[v+index]; - } - /** - * Add an edge in the graph. - * \param index1 The index of the source vertex. - * \param index2 The index of the target vertex. - * \param r The rcc8 value associated to the edge. - */ - template <class TVertex> - void - RCC8Graph<TVertex> - ::AddEdge(unsigned int index1, unsigned int index2, RCC8ValueType r) - { - EdgeDescriptorType e = boost::add_edge(index1,index2,m_Graph).first; - EdgeType::Pointer edge = EdgeType::New(); - edge->SetValue(r); - m_Graph[e]=edge; - } - /** - * Get number of edges - * /return The number of edges. - */ - template <class TVertex> - unsigned int - RCC8Graph<TVertex> - ::GetNumberOfEdges(void) +/** + * Constructor + */ +template <class TVertex> +RCC8Graph<TVertex> +::RCC8Graph() +{ + m_NumberOfVertices = 0; +}; +/** + * since the number of vertices is mandatory to instantiate the + * internal boost representation, the build method has to be called + * once this parameter is set. + */ +template <class TVertex> +void +RCC8Graph<TVertex> +::Build(void) +{ + this->Initialize(m_NumberOfVertices-1); +} +/** + * Initialize a range of vertex. + * \param num The index of the last vertices to intialize. + */ +template <class TVertex> +void +RCC8Graph<TVertex> +::Initialize( unsigned int num) +{ + for (unsigned int i = boost::num_vertices(m_Graph); i<=num;i++) { - return num_edges(m_Graph); + VertexDescriptorType id = boost::add_vertex(m_Graph); + VertexPointerType vertex = VertexType::New(); + m_Graph[id]=vertex; } - /** - * PrintSelf method - */ - template <class TVertex> - void - RCC8Graph<TVertex> - ::PrintSelf( std::ostream& os,itk::Indent indent ) const +} +/** + * Set a vertex. + * \param index The index of the vertex in the graph. + * \param vertex The vertex to set. + */ +template<class TVertex> +void +RCC8Graph<TVertex> +::SetVertex(unsigned int index, VertexPointerType vertex) +{ + if (index>=m_NumberOfVertices) { - Superclass::PrintSelf(os,indent); + this->Initialize(index); + m_NumberOfVertices = index+1; } + VertexDescriptorType v = *boost::vertices(m_Graph).first; + m_Graph[v+index]= vertex; +} +/** + * Get a vertex. + * \param index The index of the vertex in the graph + * \return The vertex. + */ +template <class TVertex> +typename RCC8Graph<TVertex> +::VertexPointerType +RCC8Graph<TVertex> +::GetVertex(unsigned int index) +{ + VertexDescriptorType v = *boost::vertices(m_Graph).first; + return m_Graph[v+index]; +} +/** + * Add an edge in the graph. + * \param index1 The index of the source vertex. + * \param index2 The index of the target vertex. + * \param r The rcc8 value associated to the edge. + */ +template <class TVertex> +void +RCC8Graph<TVertex> +::AddEdge(unsigned int index1, unsigned int index2, RCC8ValueType r) +{ + EdgeDescriptorType e = boost::add_edge(index1,index2,m_Graph).first; + EdgeType::Pointer edge = EdgeType::New(); + edge->SetValue(r); + m_Graph[e]=edge; +} +/** + * Get number of edges + * /return The number of edges. + */ +template <class TVertex> +unsigned int +RCC8Graph<TVertex> +::GetNumberOfEdges(void) +{ + return num_edges(m_Graph); +} +/** + * PrintSelf method + */ +template <class TVertex> +void +RCC8Graph<TVertex> +::PrintSelf( std::ostream& os,itk::Indent indent ) const +{ + Superclass::PrintSelf(os,indent); +} }// end namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8GraphFileReader.h b/Code/SpatialReasoning/otbRCC8GraphFileReader.h index 6aa2864e35279ed62d42f2244ca113898ed323a7..72a3f0cd2e379361faba457eab378c70ad779df9 100644 --- a/Code/SpatialReasoning/otbRCC8GraphFileReader.h +++ b/Code/SpatialReasoning/otbRCC8GraphFileReader.h @@ -27,7 +27,7 @@ namespace otb * \brief Base exception class for IO problems during reading. */ class ITK_EXPORT RCC8GraphFileReaderException - : public itk::ExceptionObject + : public itk::ExceptionObject { public: /** Run-time information. */ @@ -35,15 +35,15 @@ public: /** Constructor. */ RCC8GraphFileReaderException(const char *file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} /** Constructor. */ RCC8GraphFileReaderException(const std::string &file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} }; /** @@ -104,7 +104,7 @@ protected: /** PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** File name */ std::string m_FileName; }; diff --git a/Code/SpatialReasoning/otbRCC8GraphFileReader.txx b/Code/SpatialReasoning/otbRCC8GraphFileReader.txx index 0c21879a1639e3d73d9b6be47a5eee519a82a73c..485fdfb471034ce11e6ca3170e4f71c74dd71685 100644 --- a/Code/SpatialReasoning/otbRCC8GraphFileReader.txx +++ b/Code/SpatialReasoning/otbRCC8GraphFileReader.txx @@ -25,7 +25,8 @@ #include <iostream> #include <string> -namespace otb { +namespace otb +{ /** * Constructor */ @@ -61,7 +62,7 @@ RCC8GraphFileReader<TOutputGraph> typename std::string::size_type pos5 = line.find_first_of("\" ",pos4+1); RCC8ValueType value =static_cast<RCC8ValueType>(atoi(line.substr(pos4+1,pos5-pos4-1).c_str())); otbMsgDevMacro(<<"RCC8GraphFileReader: Edge line parsed: "<<source<<" -> " - <<target<<" "<<value); + <<target<<" "<<value); this->GetOutput()->AddEdge(source,target,value); } /** @@ -82,7 +83,7 @@ RCC8GraphFileReader<TOutputGraph> midPos=line.find_first_of("\"",pos+2); nextPos=line.find_first_of("\"",midPos+1); std::string key,value; - while((midPos!=std::string::npos)&&(nextPos!=std::string::npos)) + while ((midPos!=std::string::npos)&&(nextPos!=std::string::npos)) { key = line.substr(pos+2,midPos-pos-3); value = line.substr(midPos+1,nextPos-midPos-1); @@ -112,32 +113,32 @@ RCC8GraphFileReader<TOutputGraph> fin.open(m_FileName.c_str()); // Test if the file has been opened correctly - if(!fin) - { - RCC8GraphFileReaderException e(__FILE__, __LINE__); - itk::OStringStream msg; - msg << " Could not create IO object for file "; - msg<<m_FileName<<"."<<std::endl; - e.SetDescription(msg.str().c_str()); - throw e; - return; - } - - // if so, parse it - while(!fin.eof()) - { - std::getline(fin,line); - if(line.find("->")!=std::string::npos) + if (!fin) { - // edge line - this->ParseEdge(line); + RCC8GraphFileReaderException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg << " Could not create IO object for file "; + msg<<m_FileName<<"."<<std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; } - else if(line.find("[")!=std::string::npos) + + // if so, parse it + while (!fin.eof()) { - // vertex line - this->ParseVertex(line); - } + std::getline(fin,line); + if (line.find("->")!=std::string::npos) + { + // edge line + this->ParseEdge(line); } + else if (line.find("[")!=std::string::npos) + { + // vertex line + this->ParseVertex(line); + } + } fin.close(); } /** diff --git a/Code/SpatialReasoning/otbRCC8GraphFileWriter.h b/Code/SpatialReasoning/otbRCC8GraphFileWriter.h index 89b3833ac3da731bd58b2aa51899b03e084668c9..9f4eb8772038a1f4560639a056d8fffdda0ad693 100644 --- a/Code/SpatialReasoning/otbRCC8GraphFileWriter.h +++ b/Code/SpatialReasoning/otbRCC8GraphFileWriter.h @@ -28,7 +28,7 @@ namespace otb * \brief Base exception class for IO problems during writing. */ class ITK_EXPORT RCC8GraphFileWriterException - : public itk::ExceptionObject + : public itk::ExceptionObject { public: /** Run-time information. */ @@ -36,15 +36,15 @@ public: /** Constructor. */ RCC8GraphFileWriterException(const char *file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} /** Constructor. */ RCC8GraphFileWriterException(const std::string &file, unsigned int line, - const char* message = "Error in IO", - const char* loc = "Unknown" ) : - ExceptionObject(file, line, message, loc) + const char* message = "Error in IO", + const char* loc = "Unknown" ) : + ExceptionObject(file, line, message, loc) {} }; /** @@ -62,7 +62,7 @@ public: */ template <class TInputGraph> class ITK_EXPORT RCC8GraphFileWriter - : public itk::ProcessObject + : public itk::ProcessObject { public: /** Standards typedefs */ @@ -111,10 +111,10 @@ protected: * Main computation method. */ virtual void GenerateData(void); - /** - * Write Method. - * Performs checkings and invoke GenerateData(). - */ + /** + * Write Method. + * Performs checkings and invoke GenerateData(). + */ virtual void Write(void); /** * Write an edge to file. @@ -124,7 +124,7 @@ protected: * \param value The value of the edge. */ void WriteEdge(std::ofstream& of,VertexDescriptorType source, - VertexDescriptorType target, RCC8ValueType value); + VertexDescriptorType target, RCC8ValueType value); /** * Write a vertex to file. * \param of The output file stream. @@ -132,7 +132,7 @@ protected: * \param vertex The pointer to the vertex object. */ void WriteVertex(std::ofstream& of, VertexDescriptorType index, - VertexPointerType vertex); + VertexPointerType vertex); /** * PrintSelf method */ diff --git a/Code/SpatialReasoning/otbRCC8GraphFileWriter.txx b/Code/SpatialReasoning/otbRCC8GraphFileWriter.txx index be6643faf5f56fc2265645f3d6bc9822c341297b..11bfc6446859551cd10a14ecd23201e05f534e28 100644 --- a/Code/SpatialReasoning/otbRCC8GraphFileWriter.txx +++ b/Code/SpatialReasoning/otbRCC8GraphFileWriter.txx @@ -93,16 +93,16 @@ RCC8GraphFileWriter<TInputGraph> // Make sure input is available if ( input == 0 ) - { + { itkExceptionMacro(<< "No input to writer!"); - } + } // Make sure that we can write the file given the name // if ( m_FileName == "" ) - { + { itkExceptionMacro(<<"No filename was specified"); - } + } // Pipeline updating sequence input->UpdateOutputInformation(); @@ -134,35 +134,35 @@ RCC8GraphFileWriter<TInputGraph> out.open(m_FileName.c_str(), std::ios::out); // Test if the file has been opened correctly - if(!out) - { - RCC8GraphFileWriterException e(__FILE__, __LINE__); - itk::OStringStream msg; - msg << " Could not create IO object for file "; - msg<<m_FileName<<"."<<std::endl; - e.SetDescription(msg.str().c_str()); - throw e; - return; - } + if (!out) + { + RCC8GraphFileWriterException e(__FILE__, __LINE__); + itk::OStringStream msg; + msg << " Could not create IO object for file "; + msg<<m_FileName<<"."<<std::endl; + e.SetDescription(msg.str().c_str()); + throw e; + return; + } // Start writing the graph to file out<<"digraph G {"<<std::endl; // For each vertex in the graph VertexIteratorType vIt(input); - for(vIt.GoToBegin();!vIt.IsAtEnd();++vIt) - { - this->WriteVertex(out,vIt.GetIndex(),vIt.Get()); - } + for (vIt.GoToBegin();!vIt.IsAtEnd();++vIt) + { + this->WriteVertex(out,vIt.GetIndex(),vIt.Get()); + } // For each edge in the graph EdgeIteratorType eIt(input); - for(eIt.GoToBegin();!eIt.IsAtEnd();++eIt) - { - this->WriteEdge(out, eIt.GetSourceIndex(), - eIt.GetTargetIndex(), - eIt.GetValue()); - } + for (eIt.GoToBegin();!eIt.IsAtEnd();++eIt) + { + this->WriteEdge(out, eIt.GetSourceIndex(), + eIt.GetTargetIndex(), + eIt.GetValue()); + } // Ends the graph writing out<<"}"<<std::endl; @@ -177,11 +177,11 @@ RCC8GraphFileWriter<TInputGraph> * \param target The index of the target vertex. * \param value The value of the edge. */ - template <class TInputGraph> +template <class TInputGraph> void RCC8GraphFileWriter<TInputGraph> ::WriteEdge(std::ofstream& of,VertexDescriptorType source, - VertexDescriptorType target, RCC8ValueType value) + VertexDescriptorType target, RCC8ValueType value) { otbMsgDevMacro(<<"RCC8GraphFileWriter: WriteEdge call: "<<source<<" "<<target<<" "<<value); of<<source<<" -> "<<target<<" "; @@ -198,7 +198,7 @@ template <class TInputGraph> void RCC8GraphFileWriter<TInputGraph> ::WriteVertex(std::ofstream& of, VertexDescriptorType index, - VertexPointerType vertex) + VertexPointerType vertex) { typedef typename VertexType::AttributesMapType AttributesMapType; typedef typename AttributesMapType::iterator IteratorType; @@ -206,20 +206,20 @@ RCC8GraphFileWriter<TInputGraph> otbMsgDevMacro(<<"RCC8GraphFileWriter: WriteVertex call: "<<index); of<<index<<" ["; IteratorType it = attr.begin(); - while(it!=attr.end()) - { - of<<(*it).first<<"=\""; - of<<(*it).second<<"\""; - ++it; - if(it==attr.end()) + while (it!=attr.end()) { - of<<"];"<<std::endl; - } - else - { - of<<","; - } + of<<(*it).first<<"=\""; + of<<(*it).second<<"\""; + ++it; + if (it==attr.end()) + { + of<<"];"<<std::endl; } + else + { + of<<","; + } + } } /** * PrintSelf method diff --git a/Code/SpatialReasoning/otbRCC8GraphSource.h b/Code/SpatialReasoning/otbRCC8GraphSource.h index 05458d322f58c6f0f1e4483aa2161b75dfd0c168..e710c6c033f3291e7ba8de7a10ccc5de60246ca1 100644 --- a/Code/SpatialReasoning/otbRCC8GraphSource.h +++ b/Code/SpatialReasoning/otbRCC8GraphSource.h @@ -28,7 +28,7 @@ namespace otb */ template <class TOutputGraph> class ITK_EXPORT RCC8GraphSource - : public itk::ProcessObject + : public itk::ProcessObject { public: /** Standard typedefs */ @@ -45,7 +45,7 @@ public: /** Template parameter typedef*/ typedef TOutputGraph OutputGraphType; typedef typename OutputGraphType::Pointer OutputGraphPointerType; - /** Overiding of the GetOutput() method */ + /** Overiding of the GetOutput() method */ virtual OutputGraphType * GetOutput(void); protected: diff --git a/Code/SpatialReasoning/otbRCC8GraphSource.txx b/Code/SpatialReasoning/otbRCC8GraphSource.txx index 3db37c9f2abfd218bf2407646329cf838dc292a5..b278ea097bee82dec8828b351a9992b79b2aabbb 100644 --- a/Code/SpatialReasoning/otbRCC8GraphSource.txx +++ b/Code/SpatialReasoning/otbRCC8GraphSource.txx @@ -41,10 +41,10 @@ typename RCC8GraphSource<TOutputGraph>::OutputGraphType * RCC8GraphSource<TOutputGraph> ::GetOutput(void) { - if(this->GetNumberOfOutputs()<1) - { + if (this->GetNumberOfOutputs()<1) + { return 0; - } + } return static_cast<OutputGraphType *> (this->ProcessObject::GetOutput(0)); } /** diff --git a/Code/SpatialReasoning/otbRCC8InEdgeIterator.h b/Code/SpatialReasoning/otbRCC8InEdgeIterator.h index 95dbacae864014a6e34d5b472f12bde74df73e13..d97176895f4bf0e99022e05027ddb191579e86d4 100644 --- a/Code/SpatialReasoning/otbRCC8InEdgeIterator.h +++ b/Code/SpatialReasoning/otbRCC8InEdgeIterator.h @@ -29,7 +29,7 @@ namespace otb template <class TGraph> class ITK_EXPORT RCC8InEdgeIterator { - public: +public: /** self typedef */ typedef RCC8InEdgeIterator Self; @@ -48,34 +48,34 @@ class ITK_EXPORT RCC8InEdgeIterator /** Constructor */ RCC8InEdgeIterator(); - /** Copy constructor */ - RCC8InEdgeIterator(const Self& iter); - /** Constructor with input graph */ - RCC8InEdgeIterator(VertexDescriptorType vertex,GraphType * graph); + /** Copy constructor */ + RCC8InEdgeIterator(const Self& iter); + /** Constructor with input graph */ + RCC8InEdgeIterator(VertexDescriptorType vertex,GraphType * graph); /** * Get the current edge value. * \return The value of the current edge pointed by the iterator. */ RCC8ValueType GetValue(void); - /** - * Return the source vertex of the current edge. - * \return The source edge. - */ + /** + * Return the source vertex of the current edge. + * \return The source edge. + */ VertexPointerType GetSourceVertex(void); /** * Return the source vertex index of the current edge. * \return The souce vertex index. */ VertexDescriptorType GetSourceIndex(void); - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - bool IsAtEnd(void); - /** - * Go to the beginning. - */ - void GoToBegin(void); + /** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ + bool IsAtEnd(void); + /** + * Go to the beginning. + */ + void GoToBegin(void); /** * Increment. */ @@ -105,7 +105,7 @@ class ITK_EXPORT RCC8InEdgeIterator * Instantiation operator. */ Self& operator=(const Self& it); - private: +private: // End InternalIteratorType m_End; // Internal iterator. diff --git a/Code/SpatialReasoning/otbRCC8InEdgeIterator.txx b/Code/SpatialReasoning/otbRCC8InEdgeIterator.txx index 5c925e8896e0df109ae64d2e43b2770dc12f4051..a6c01a659b2956312e2a23bf6cba3bb49db50225 100644 --- a/Code/SpatialReasoning/otbRCC8InEdgeIterator.txx +++ b/Code/SpatialReasoning/otbRCC8InEdgeIterator.txx @@ -22,174 +22,174 @@ namespace otb { - /** Constructor */ - template <class TGraph> - RCC8InEdgeIterator<TGraph> - ::RCC8InEdgeIterator() - { +/** Constructor */ +template <class TGraph> +RCC8InEdgeIterator<TGraph> +::RCC8InEdgeIterator() +{ m_Graph = GraphType::New(); tie(m_Iter,m_End)=in_edges(0,*m_Graph->GetGraph()); - } - /** - * Copy operator. - */ - template <class TGraph> - RCC8InEdgeIterator<TGraph> - ::RCC8InEdgeIterator(const Self& iter) - { - m_Iter=iter.m_Iter; - m_Graph=iter.m_Graph; - m_VertexIndex = iter.m_VertexIndex; - m_End=iter.m_End; - } - /** - *Constructor with input graph - */ - template <class TGraph> - RCC8InEdgeIterator<TGraph> - ::RCC8InEdgeIterator(VertexDescriptorType vertex,GraphType * graph) - { - m_Graph=graph; - m_VertexIndex=vertex; - tie(m_Iter,m_End)=in_edges(vertex,*m_Graph->GetGraph()); - } - /** - * Get the current edge value. - * \return The value of the current edge pointed by the iterator. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::RCC8ValueType - RCC8InEdgeIterator<TGraph> - ::GetValue(void) - { - return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); - } - /** - * Return the source vertex of the current edge. - * \return The source edge. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::VertexPointerType - RCC8InEdgeIterator<TGraph> - ::GetSourceVertex(void) - { - return (*m_Graph->GetGraph())[source(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return the source vertex index of the current edge. - * \return The souce vertex index. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::VertexDescriptorType - RCC8InEdgeIterator<TGraph> - ::GetSourceIndex(void) - { - IndexMapType index = get(boost::vertex_index, (*m_Graph->GetGraph())); - return index[source(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - template <class TGraph> - bool - RCC8InEdgeIterator<TGraph> - ::IsAtEnd(void) - { - return (m_Iter==m_End); - } - /** - * Go to the beginning. - */ - template <class TGraph> - void - RCC8InEdgeIterator<TGraph> - ::GoToBegin(void) - { - tie(m_Iter,m_End)=in_edges(m_VertexIndex,*m_Graph->GetGraph()); - } - /** - * Increment. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::Self& - RCC8InEdgeIterator<TGraph> - ::operator++() - { - ++m_Iter; - return *this; - } - /** - * Decrement. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::Self& - RCC8InEdgeIterator<TGraph> - ::operator--() - { - --m_Iter; - return *this; - } - /** - * Add - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::Self& - RCC8InEdgeIterator<TGraph> - ::operator+(int i) - { - m_Iter=m_Iter+i; - return *this; - } - /** - * Remove - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::Self& - RCC8InEdgeIterator<TGraph> - ::operator-(int i) - { - m_Iter=m_Iter-i; - return *this; - } - /** - * Difference comparison operator. - */ - template <class TGraph> - bool - RCC8InEdgeIterator<TGraph> - ::operator!=(const Self& iter) - { - return (m_Iter != iter.m_Iter); - } - /** - * Equality comparison operator. - */ - template <class TGraph> - bool - RCC8InEdgeIterator<TGraph> - ::operator==(const Self& iter) - { - return (m_Iter == iter.m_Iter); - } - /** - * Instantiation operator. - */ - template <class TGraph> - typename RCC8InEdgeIterator<TGraph> - ::Self& - RCC8InEdgeIterator<TGraph> - ::operator=(const Self& iter) - { - m_Iter = iter.m_Iter; - return *this; - } +} +/** + * Copy operator. + */ +template <class TGraph> +RCC8InEdgeIterator<TGraph> +::RCC8InEdgeIterator(const Self& iter) +{ + m_Iter=iter.m_Iter; + m_Graph=iter.m_Graph; + m_VertexIndex = iter.m_VertexIndex; + m_End=iter.m_End; +} +/** + *Constructor with input graph + */ +template <class TGraph> +RCC8InEdgeIterator<TGraph> +::RCC8InEdgeIterator(VertexDescriptorType vertex,GraphType * graph) +{ + m_Graph=graph; + m_VertexIndex=vertex; + tie(m_Iter,m_End)=in_edges(vertex,*m_Graph->GetGraph()); +} +/** + * Get the current edge value. + * \return The value of the current edge pointed by the iterator. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::RCC8ValueType +RCC8InEdgeIterator<TGraph> +::GetValue(void) +{ + return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); +} +/** + * Return the source vertex of the current edge. + * \return The source edge. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::VertexPointerType +RCC8InEdgeIterator<TGraph> +::GetSourceVertex(void) +{ + return (*m_Graph->GetGraph())[source(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return the source vertex index of the current edge. + * \return The souce vertex index. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::VertexDescriptorType +RCC8InEdgeIterator<TGraph> +::GetSourceIndex(void) +{ + IndexMapType index = get(boost::vertex_index, (*m_Graph->GetGraph())); + return index[source(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ +template <class TGraph> +bool +RCC8InEdgeIterator<TGraph> +::IsAtEnd(void) +{ + return (m_Iter==m_End); +} +/** + * Go to the beginning. + */ +template <class TGraph> +void +RCC8InEdgeIterator<TGraph> +::GoToBegin(void) +{ + tie(m_Iter,m_End)=in_edges(m_VertexIndex,*m_Graph->GetGraph()); +} +/** + * Increment. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::Self& +RCC8InEdgeIterator<TGraph> +::operator++() +{ + ++m_Iter; + return *this; +} +/** + * Decrement. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::Self& +RCC8InEdgeIterator<TGraph> +::operator--() +{ + --m_Iter; + return *this; +} +/** + * Add + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::Self& +RCC8InEdgeIterator<TGraph> +::operator+(int i) +{ + m_Iter=m_Iter+i; + return *this; +} +/** + * Remove + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::Self& +RCC8InEdgeIterator<TGraph> +::operator-(int i) +{ + m_Iter=m_Iter-i; + return *this; +} +/** + * Difference comparison operator. + */ +template <class TGraph> +bool +RCC8InEdgeIterator<TGraph> +::operator!=(const Self& iter) +{ + return (m_Iter != iter.m_Iter); +} +/** + * Equality comparison operator. + */ +template <class TGraph> +bool +RCC8InEdgeIterator<TGraph> +::operator==(const Self& iter) +{ + return (m_Iter == iter.m_Iter); +} +/** + * Instantiation operator. + */ +template <class TGraph> +typename RCC8InEdgeIterator<TGraph> +::Self& +RCC8InEdgeIterator<TGraph> +::operator=(const Self& iter) +{ + m_Iter = iter.m_Iter; + return *this; +} } // End namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8OutEdgeIterator.h b/Code/SpatialReasoning/otbRCC8OutEdgeIterator.h index 4e6323f4310d16b140bd41021ececab81c53a9a8..3d6b801b820386d8dadfaaf8b5e3f524ca053945 100644 --- a/Code/SpatialReasoning/otbRCC8OutEdgeIterator.h +++ b/Code/SpatialReasoning/otbRCC8OutEdgeIterator.h @@ -29,7 +29,7 @@ namespace otb template <class TGraph> class ITK_EXPORT RCC8OutEdgeIterator { - public: +public: /** self typedef */ typedef RCC8OutEdgeIterator Self; @@ -48,10 +48,10 @@ class ITK_EXPORT RCC8OutEdgeIterator /** Constructor */ RCC8OutEdgeIterator(); - /** Copy constructor */ - RCC8OutEdgeIterator(const Self& iter); - /** Constructor with input graph */ - RCC8OutEdgeIterator(VertexDescriptorType vertex,TGraph * graph); + /** Copy constructor */ + RCC8OutEdgeIterator(const Self& iter); + /** Constructor with input graph */ + RCC8OutEdgeIterator(VertexDescriptorType vertex,TGraph * graph); /** * Get the current edge value. * \return The value of the current edge pointed by the iterator. @@ -68,15 +68,15 @@ class ITK_EXPORT RCC8OutEdgeIterator */ VertexDescriptorType GetTargetIndex(void); - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - bool IsAtEnd(void); - /** - * Go to the beginning. - */ - void GoToBegin(void); + /** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ + bool IsAtEnd(void); + /** + * Go to the beginning. + */ + void GoToBegin(void); /** * Increment. */ @@ -105,7 +105,7 @@ class ITK_EXPORT RCC8OutEdgeIterator * Instantiation operator. */ Self& operator=(const Self& it); - private: +private: // End InternalIteratorType m_End; // Internal iterator. diff --git a/Code/SpatialReasoning/otbRCC8OutEdgeIterator.txx b/Code/SpatialReasoning/otbRCC8OutEdgeIterator.txx index 4217dd385503837041b46e6bbc66592cfd9ce243..639f8139fabdf6afab718a78606f891c5dddbb8e 100644 --- a/Code/SpatialReasoning/otbRCC8OutEdgeIterator.txx +++ b/Code/SpatialReasoning/otbRCC8OutEdgeIterator.txx @@ -22,174 +22,174 @@ namespace otb { - /** Constructor */ - template <class TGraph> - RCC8OutEdgeIterator<TGraph> - ::RCC8OutEdgeIterator() - { +/** Constructor */ +template <class TGraph> +RCC8OutEdgeIterator<TGraph> +::RCC8OutEdgeIterator() +{ m_Graph = GraphType::New(); tie(m_Iter,m_End)=out_edges(0,*m_Graph->GetGraph()); - } - /** - * Copy operator. - */ - template <class TGraph> - RCC8OutEdgeIterator<TGraph> - ::RCC8OutEdgeIterator(const Self& iter) - { - m_Iter=iter.m_Iter; - m_Graph=iter.m_Graph; - m_VertexIndex = iter.m_VertexIndex; - m_End=iter.m_End; - } - /** - *Constructor with input graph - */ - template <class TGraph> - RCC8OutEdgeIterator<TGraph> - ::RCC8OutEdgeIterator(VertexDescriptorType vertex,TGraph * graph) - { - m_Graph=graph; - m_VertexIndex = vertex; - tie(m_Iter,m_End)=out_edges(vertex,*m_Graph->GetGraph()); - } - /** - * Get the current edge value. - * \return The value of the current edge pointed by the iterator. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::RCC8ValueType - RCC8OutEdgeIterator<TGraph> - ::GetValue(void) - { - return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); - } - /** - * Return the target vertex of the current edge. - * \return The target vertex. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::VertexPointerType - RCC8OutEdgeIterator<TGraph> - ::GetTargetVertex(void) - { - return (*m_Graph->GetGraph())[target(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return the target vertex index of the current edge. - * \return The target vertex index. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::VertexDescriptorType - RCC8OutEdgeIterator<TGraph> - ::GetTargetIndex(void) - { - IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); - return index[target(*m_Iter,(*m_Graph->GetGraph()))]; - } - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - template <class TGraph> - bool - RCC8OutEdgeIterator<TGraph> - ::IsAtEnd(void) - { - return (m_Iter==m_End); - } - /** - * Go to the beginning. - */ - template <class TGraph> - void - RCC8OutEdgeIterator<TGraph> - ::GoToBegin(void) - { - tie(m_Iter,m_End)=out_edges(m_VertexIndex,*m_Graph->GetGraph()); - } - /** - * Increment. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::Self& - RCC8OutEdgeIterator<TGraph> - ::operator++() - { - ++m_Iter; - return *this; - } - /** - * Decrement. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::Self& - RCC8OutEdgeIterator<TGraph> - ::operator--() - { - --m_Iter; - return *this; - } - /** - * Add - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::Self& - RCC8OutEdgeIterator<TGraph> - ::operator+(int i) - { - m_Iter=m_Iter+i; - return *this; - } - /** - * Remove - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::Self& - RCC8OutEdgeIterator<TGraph> - ::operator-(int i) - { - m_Iter=m_Iter-i; - return *this; - } - /** - * Difference comparison operator. - */ - template <class TGraph> - bool - RCC8OutEdgeIterator<TGraph> - ::operator!=(const Self& iter) - { - return (m_Iter != iter.m_Iter); - } - /** - * Equality comparison operator. - */ - template <class TGraph> - bool - RCC8OutEdgeIterator<TGraph> - ::operator==(const Self& iter) - { - return (m_Iter == iter.m_Iter); - } - /** - * Instantiation operator. - */ - template <class TGraph> - typename RCC8OutEdgeIterator<TGraph> - ::Self& - RCC8OutEdgeIterator<TGraph> - ::operator=(const Self& iter) - { - m_Iter = iter.m_Iter; - return *this; - } +} +/** + * Copy operator. + */ +template <class TGraph> +RCC8OutEdgeIterator<TGraph> +::RCC8OutEdgeIterator(const Self& iter) +{ + m_Iter=iter.m_Iter; + m_Graph=iter.m_Graph; + m_VertexIndex = iter.m_VertexIndex; + m_End=iter.m_End; +} +/** + *Constructor with input graph + */ +template <class TGraph> +RCC8OutEdgeIterator<TGraph> +::RCC8OutEdgeIterator(VertexDescriptorType vertex,TGraph * graph) +{ + m_Graph=graph; + m_VertexIndex = vertex; + tie(m_Iter,m_End)=out_edges(vertex,*m_Graph->GetGraph()); +} +/** + * Get the current edge value. + * \return The value of the current edge pointed by the iterator. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::RCC8ValueType +RCC8OutEdgeIterator<TGraph> +::GetValue(void) +{ + return (*m_Graph->GetGraph())[*m_Iter]->GetValue(); +} +/** + * Return the target vertex of the current edge. + * \return The target vertex. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::VertexPointerType +RCC8OutEdgeIterator<TGraph> +::GetTargetVertex(void) +{ + return (*m_Graph->GetGraph())[target(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return the target vertex index of the current edge. + * \return The target vertex index. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::VertexDescriptorType +RCC8OutEdgeIterator<TGraph> +::GetTargetIndex(void) +{ + IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); + return index[target(*m_Iter,(*m_Graph->GetGraph()))]; +} +/** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ +template <class TGraph> +bool +RCC8OutEdgeIterator<TGraph> +::IsAtEnd(void) +{ + return (m_Iter==m_End); +} +/** + * Go to the beginning. + */ +template <class TGraph> +void +RCC8OutEdgeIterator<TGraph> +::GoToBegin(void) +{ + tie(m_Iter,m_End)=out_edges(m_VertexIndex,*m_Graph->GetGraph()); +} +/** + * Increment. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::Self& +RCC8OutEdgeIterator<TGraph> +::operator++() +{ + ++m_Iter; + return *this; +} +/** + * Decrement. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::Self& +RCC8OutEdgeIterator<TGraph> +::operator--() +{ + --m_Iter; + return *this; +} +/** + * Add + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::Self& +RCC8OutEdgeIterator<TGraph> +::operator+(int i) +{ + m_Iter=m_Iter+i; + return *this; +} +/** + * Remove + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::Self& +RCC8OutEdgeIterator<TGraph> +::operator-(int i) +{ + m_Iter=m_Iter-i; + return *this; +} +/** + * Difference comparison operator. + */ +template <class TGraph> +bool +RCC8OutEdgeIterator<TGraph> +::operator!=(const Self& iter) +{ + return (m_Iter != iter.m_Iter); +} +/** + * Equality comparison operator. + */ +template <class TGraph> +bool +RCC8OutEdgeIterator<TGraph> +::operator==(const Self& iter) +{ + return (m_Iter == iter.m_Iter); +} +/** + * Instantiation operator. + */ +template <class TGraph> +typename RCC8OutEdgeIterator<TGraph> +::Self& +RCC8OutEdgeIterator<TGraph> +::operator=(const Self& iter) +{ + m_Iter = iter.m_Iter; + return *this; +} } // End namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8Value.h b/Code/SpatialReasoning/otbRCC8Value.h index 70e4d499462d499e5eb4bee2847967b35bca88e8..148fdf7a943e6ad530f933ae13da3edaf6adcd2d 100644 --- a/Code/SpatialReasoning/otbRCC8Value.h +++ b/Code/SpatialReasoning/otbRCC8Value.h @@ -20,16 +20,17 @@ namespace otb { - // Coding enum system to represent the RCC8 relation values. -typedef enum { -OTB_RCC8_DC, -OTB_RCC8_EC, -OTB_RCC8_PO, -OTB_RCC8_TPP, -OTB_RCC8_TPPI, -OTB_RCC8_NTPP, -OTB_RCC8_NTPPI, -OTB_RCC8_EQ +// Coding enum system to represent the RCC8 relation values. +typedef enum +{ + OTB_RCC8_DC, + OTB_RCC8_EC, + OTB_RCC8_PO, + OTB_RCC8_TPP, + OTB_RCC8_TPPI, + OTB_RCC8_NTPP, + OTB_RCC8_NTPPI, + OTB_RCC8_EQ } RCC8Value; }// End namespace otb diff --git a/Code/SpatialReasoning/otbRCC8VertexBase.h b/Code/SpatialReasoning/otbRCC8VertexBase.h index db59eb69651f183d96a1886181a353b866daf49d..324a3c340e4c809637c86868fdc17f5daa8553ba 100644 --- a/Code/SpatialReasoning/otbRCC8VertexBase.h +++ b/Code/SpatialReasoning/otbRCC8VertexBase.h @@ -34,9 +34,9 @@ namespace otb */ template <class TPath> class ITK_EXPORT RCC8VertexBase -: public itk::DataObject + : public itk::DataObject { - public: +public: /** Standard class typedefs */ typedef RCC8VertexBase Self; typedef itk::DataObject Superclass; @@ -57,7 +57,7 @@ class ITK_EXPORT RCC8VertexBase /** Segmentation image index accessors */ itkGetMacro(SegmentationLevel,unsigned int); itkSetMacro(SegmentationLevel,unsigned int); - itkGetMacro(SegmentationType,bool); + itkGetMacro(SegmentationType,bool); itkSetMacro(SegmentationType,bool); /** Object label in image accessor */ itkGetObjectMacro(Path,PathType); @@ -77,11 +77,11 @@ protected: /** Constructor */ RCC8VertexBase(); /** Desctructor */ - ~RCC8VertexBase(){}; -/** PrintSelf method */ + ~RCC8VertexBase() {}; + /** PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: +private: /** The segmentation level */ unsigned int m_SegmentationLevel; /** True if bright details, false otherwise */ diff --git a/Code/SpatialReasoning/otbRCC8VertexBase.txx b/Code/SpatialReasoning/otbRCC8VertexBase.txx index eb945317ef5ae980c9a8a3f308706d1096c377f9..9d2456e708b86e48504d036654a426179c81b653 100644 --- a/Code/SpatialReasoning/otbRCC8VertexBase.txx +++ b/Code/SpatialReasoning/otbRCC8VertexBase.txx @@ -52,17 +52,17 @@ RCC8VertexBase<TPath> m_Path = PathType::New(); m_Path->Initialize(); - for(unsigned int i = 0;i<nbPoints;++i) - { - ContinuousIndexType newPoint; - oss<<"P"<<i<<"x"; - newPoint[0]=atof(attributes[oss.str()].c_str()); - oss.str(""); - oss<<"P"<<i<<"y"; - newPoint[1]=atof(attributes[oss.str()].c_str()); - oss.str(""); - m_Path->AddVertex(newPoint); - } + for (unsigned int i = 0;i<nbPoints;++i) + { + ContinuousIndexType newPoint; + oss<<"P"<<i<<"x"; + newPoint[0]=atof(attributes[oss.str()].c_str()); + oss.str(""); + oss<<"P"<<i<<"y"; + newPoint[1]=atof(attributes[oss.str()].c_str()); + oss.str(""); + m_Path->AddVertex(newPoint); + } } /** * Get an attributes vector representing the VertexBase attributes. @@ -88,22 +88,22 @@ RCC8VertexBase<TPath> typename PathType::VertexListType::ConstIterator it; unsigned int index = 0; - for(it=m_Path->GetVertexList()->Begin();it!=m_Path->GetVertexList()->End();++it,++index) - { - ContinuousIndexType point = it.Value(); - oss<<"P"<<index<<"x"; - std::string key = oss.str(); - oss.str(""); - oss<<point[0]; - results[key]=oss.str(); - oss.str(""); - oss<<"P"<<index<<"y"; - key = oss.str(); - oss.str(""); - oss<<point[1]; - results[key]=oss.str(); - oss.str(""); - } + for (it=m_Path->GetVertexList()->Begin();it!=m_Path->GetVertexList()->End();++it,++index) + { + ContinuousIndexType point = it.Value(); + oss<<"P"<<index<<"x"; + std::string key = oss.str(); + oss.str(""); + oss<<point[0]; + results[key]=oss.str(); + oss.str(""); + oss<<"P"<<index<<"y"; + key = oss.str(); + oss.str(""); + oss<<point[1]; + results[key]=oss.str(); + oss.str(""); + } return results; } /** @@ -113,10 +113,10 @@ template <class TPath> void RCC8VertexBase<TPath> ::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"SegmentationLevel: "<<m_SegmentationLevel<<std::endl; - os<<indent<<"SegmentationType: "<<m_SegmentationType<<std::endl; - } +{ + Superclass::PrintSelf(os,indent); + os<<indent<<"SegmentationLevel: "<<m_SegmentationLevel<<std::endl; + os<<indent<<"SegmentationType: "<<m_SegmentationType<<std::endl; +} } // end namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8VertexIterator.h b/Code/SpatialReasoning/otbRCC8VertexIterator.h index 7dd4cace5352b820099797c19049e385401e1096..b4c2607444a6773af7415a808d78d4b21b4ee073 100644 --- a/Code/SpatialReasoning/otbRCC8VertexIterator.h +++ b/Code/SpatialReasoning/otbRCC8VertexIterator.h @@ -29,7 +29,7 @@ namespace otb template <class TGraph> class ITK_EXPORT RCC8VertexIterator { - public: +public: /** self typedef */ typedef RCC8VertexIterator Self; @@ -41,14 +41,14 @@ class ITK_EXPORT RCC8VertexIterator typedef typename GraphType::VertexDescriptorType VertexDescriptorType; /** typedef of the internal iterator */ typedef typename boost::graph_traits<InternalGraphType>::vertex_iterator InternalIteratorType; -/** Typedef of the index map */ + /** Typedef of the index map */ typedef typename boost::property_map<InternalGraphType, boost::vertex_index_t>::type IndexMapType; /** Constructor */ RCC8VertexIterator(); - /** Copy constructor */ - RCC8VertexIterator(const Self& iter); - /** Constructor with input graph */ - RCC8VertexIterator(TGraph * graph); + /** Copy constructor */ + RCC8VertexIterator(const Self& iter); + /** Constructor with input graph */ + RCC8VertexIterator(TGraph * graph); /** * Get the current vertex. * \return The current vertex pointed by the iterator. @@ -64,15 +64,15 @@ class ITK_EXPORT RCC8VertexIterator * \return The current vertex index. */ VertexDescriptorType GetIndex(void); - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - bool IsAtEnd(void); - /** - * Go to the beginning. - */ - void GoToBegin(void); + /** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. + */ + bool IsAtEnd(void); + /** + * Go to the beginning. + */ + void GoToBegin(void); /** * Increment. */ @@ -102,7 +102,7 @@ class ITK_EXPORT RCC8VertexIterator * Instantiation operator. */ Self& operator=(const Self& it); - private: +private: // End InternalIteratorType m_End; // Internal iterator. diff --git a/Code/SpatialReasoning/otbRCC8VertexIterator.txx b/Code/SpatialReasoning/otbRCC8VertexIterator.txx index 376780f6cdf50380c85ee69c4e7054acf1742d10..653d460c9f47b44754d9b62c3bd288e6f18d6a90 100644 --- a/Code/SpatialReasoning/otbRCC8VertexIterator.txx +++ b/Code/SpatialReasoning/otbRCC8VertexIterator.txx @@ -22,173 +22,173 @@ namespace otb { - /** - * Constructor +/** + * Constructor + */ +template <class TGraph> +RCC8VertexIterator<TGraph> +::RCC8VertexIterator() +{ + m_Graph = GraphType::New(); + tie(m_Iter,m_End)= vertices(*(m_Graph->GetGraph())); +} +/** + * Copy operator. + */ +template <class TGraph> +RCC8VertexIterator<TGraph> +::RCC8VertexIterator(const Self& iter) +{ + m_Iter=iter.m_Iter; + m_Graph=iter.m_Graph; + m_End=iter.m_End; +} +/** + *Constructor with input graph + */ +template <class TGraph> +RCC8VertexIterator<TGraph> +::RCC8VertexIterator(TGraph * graph) +{ + m_Graph=graph; + tie(m_Iter,m_End)=vertices(*(m_Graph->GetGraph())); +} +/** + * Get the current object. + * \return The current object pointed by the iterator. + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::VertexPointerType +RCC8VertexIterator<TGraph> +::Get(void) +{ + return (*(m_Graph->GetGraph()))[*m_Iter]; +} +/** + * Set the current vertex. + * \param vertex The vertex to set. + */ +template <class TGraph> +void +RCC8VertexIterator<TGraph> +::Set(VertexPointerType vertex) +{ + (*(m_Graph->GetGraph()))[*m_Iter]=vertex; +} +/** + * Get the current vertex index. + * \return The current vertex index. + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::VertexDescriptorType +RCC8VertexIterator<TGraph> +::GetIndex(void) +{ + IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); + return index[*m_Iter]; +} +/** + * Return true if the iterator is at the end. + * \return True if the iterator is at the end. */ - template <class TGraph> - RCC8VertexIterator<TGraph> - ::RCC8VertexIterator() - { - m_Graph = GraphType::New(); - tie(m_Iter,m_End)= vertices(*(m_Graph->GetGraph())); - } - /** - * Copy operator. - */ - template <class TGraph> - RCC8VertexIterator<TGraph> - ::RCC8VertexIterator(const Self& iter) - { - m_Iter=iter.m_Iter; - m_Graph=iter.m_Graph; - m_End=iter.m_End; - } - /** - *Constructor with input graph - */ - template <class TGraph> - RCC8VertexIterator<TGraph> - ::RCC8VertexIterator(TGraph * graph) - { - m_Graph=graph; - tie(m_Iter,m_End)=vertices(*(m_Graph->GetGraph())); - } - /** - * Get the current object. - * \return The current object pointed by the iterator. - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::VertexPointerType - RCC8VertexIterator<TGraph> - ::Get(void) - { - return (*(m_Graph->GetGraph()))[*m_Iter]; - } - /** - * Set the current vertex. - * \param vertex The vertex to set. - */ - template <class TGraph> - void - RCC8VertexIterator<TGraph> - ::Set(VertexPointerType vertex) - { - (*(m_Graph->GetGraph()))[*m_Iter]=vertex; - } - /** - * Get the current vertex index. - * \return The current vertex index. - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::VertexDescriptorType - RCC8VertexIterator<TGraph> - ::GetIndex(void) - { - IndexMapType index = get(boost::vertex_index,(*m_Graph->GetGraph())); - return index[*m_Iter]; - } - /** - * Return true if the iterator is at the end. - * \return True if the iterator is at the end. - */ - template <class TGraph> - bool - RCC8VertexIterator<TGraph> - ::IsAtEnd(void) - { - return (m_Iter==m_End); - } - /** - * Go to the beginning. - */ - template <class TGraph> - void - RCC8VertexIterator<TGraph> - ::GoToBegin(void) - { - tie(m_Iter,m_End)=vertices(*(m_Graph->GetGraph())); - } - /** - * Increment. - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::Self& - RCC8VertexIterator<TGraph> - ::operator++() - { - ++m_Iter; - return *this; - } - /** - * Decrement. - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::Self& - RCC8VertexIterator<TGraph> - ::operator--() - { - --m_Iter; - return *this; - } - /** - * Add - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::Self& - RCC8VertexIterator<TGraph> - ::operator+(int i) - { - m_Iter=m_Iter+i; - return *this; - } - /** - * Remove - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::Self& - RCC8VertexIterator<TGraph> - ::operator-(int i) - { - m_Iter=m_Iter-i; - return *this; - } - /** - * Difference comparison operator. - */ - template <class TGraph> - bool - RCC8VertexIterator<TGraph> - ::operator!=(const Self& iter) - { - return (m_Iter != iter.m_Iter); - } - /** - * Equality comparison operator. - */ - template <class TGraph> - bool - RCC8VertexIterator<TGraph> - ::operator==(const Self& iter) - { - return (m_Iter == iter.m_Iter); - } - /** - * Instantiation operator. - */ - template <class TGraph> - typename RCC8VertexIterator<TGraph> - ::Self& - RCC8VertexIterator<TGraph> - ::operator=(const Self& iter) - { - m_Iter = iter.m_Iter; - return *this; - } +template <class TGraph> +bool +RCC8VertexIterator<TGraph> +::IsAtEnd(void) +{ + return (m_Iter==m_End); +} +/** + * Go to the beginning. + */ +template <class TGraph> +void +RCC8VertexIterator<TGraph> +::GoToBegin(void) +{ + tie(m_Iter,m_End)=vertices(*(m_Graph->GetGraph())); +} +/** + * Increment. + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::Self& +RCC8VertexIterator<TGraph> +::operator++() +{ + ++m_Iter; + return *this; +} +/** + * Decrement. + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::Self& +RCC8VertexIterator<TGraph> +::operator--() +{ + --m_Iter; + return *this; +} +/** + * Add + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::Self& +RCC8VertexIterator<TGraph> +::operator+(int i) +{ + m_Iter=m_Iter+i; + return *this; +} +/** + * Remove + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::Self& +RCC8VertexIterator<TGraph> +::operator-(int i) +{ + m_Iter=m_Iter-i; + return *this; +} +/** + * Difference comparison operator. + */ +template <class TGraph> +bool +RCC8VertexIterator<TGraph> +::operator!=(const Self& iter) +{ + return (m_Iter != iter.m_Iter); +} +/** + * Equality comparison operator. + */ +template <class TGraph> +bool +RCC8VertexIterator<TGraph> +::operator==(const Self& iter) +{ + return (m_Iter == iter.m_Iter); +} +/** + * Instantiation operator. + */ +template <class TGraph> +typename RCC8VertexIterator<TGraph> +::Self& +RCC8VertexIterator<TGraph> +::operator=(const Self& iter) +{ + m_Iter = iter.m_Iter; + return *this; +} } // End namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8VertexWithCompacity.h b/Code/SpatialReasoning/otbRCC8VertexWithCompacity.h index 2502982efa583c239869d1ff7e0e49c5dceb085e..13887383f84be972762aafbe26f6dc681af7f655 100644 --- a/Code/SpatialReasoning/otbRCC8VertexWithCompacity.h +++ b/Code/SpatialReasoning/otbRCC8VertexWithCompacity.h @@ -23,59 +23,59 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class RCC8VertexWithCompacity - * \brief Class to represent a vertex in a RCC8 Graph with the compacity value of - * the represented region. - * - * \sa RCC8Graph, RCC8Edge, RCC8VertexBase - */ - template <class TPath, class TPrecision = float> - class ITK_EXPORT RCC8VertexWithCompacity - : public RCC8VertexBase<TPath> - { - public: - /** Standard class typedefs */ - typedef RCC8VertexWithCompacity Self; - typedef otb::RCC8VertexBase<TPath> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(RCC8VertexWithCompacity,RCC8VertexBase); - /** Input image associated typedefs*/ - typedef TPath PathType; - /** Precision typedef */ - typedef TPrecision PrecisionType; - /** char* vector attributes */ - typedef typename Superclass::AttributesMapType AttributesMapType; +/** \class RCC8VertexWithCompacity + * \brief Class to represent a vertex in a RCC8 Graph with the compacity value of + * the represented region. + * + * \sa RCC8Graph, RCC8Edge, RCC8VertexBase + */ +template <class TPath, class TPrecision = float> +class ITK_EXPORT RCC8VertexWithCompacity + : public RCC8VertexBase<TPath> +{ +public: + /** Standard class typedefs */ + typedef RCC8VertexWithCompacity Self; + typedef otb::RCC8VertexBase<TPath> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Method for creation through the object factory. */ + itkNewMacro(Self); + /** Run-time type information (and related methods). */ + itkTypeMacro(RCC8VertexWithCompacity,RCC8VertexBase); + /** Input image associated typedefs*/ + typedef TPath PathType; + /** Precision typedef */ + typedef TPrecision PrecisionType; + /** char* vector attributes */ + typedef typename Superclass::AttributesMapType AttributesMapType; - /** Segmentation image index accessors */ - itkGetMacro(Compacity,PrecisionType); - itkSetMacro(Compacity,PrecisionType); - /** - * Set the VertexWithCompacity attributes from the attributes vector. - * \param attributes The vector containing the parsed attributes. - */ - void SetAttributesMap(AttributesMapType attributes); - /** - * Get an attributes vector representing the VertexWithCompacity attributes. - * \return The attributes vector - */ - AttributesMapType GetAttributesMap(void); + /** Segmentation image index accessors */ + itkGetMacro(Compacity,PrecisionType); + itkSetMacro(Compacity,PrecisionType); + /** + * Set the VertexWithCompacity attributes from the attributes vector. + * \param attributes The vector containing the parsed attributes. + */ + void SetAttributesMap(AttributesMapType attributes); + /** + * Get an attributes vector representing the VertexWithCompacity attributes. + * \return The attributes vector + */ + AttributesMapType GetAttributesMap(void); - protected: - /** Constructor */ - RCC8VertexWithCompacity(); - /** Desctructor */ - ~RCC8VertexWithCompacity(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + /** Constructor */ + RCC8VertexWithCompacity(); + /** Desctructor */ + ~RCC8VertexWithCompacity() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: - /** The compacity */ - PrecisionType m_Compacity; - }; +private: + /** The compacity */ + PrecisionType m_Compacity; +}; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbRCC8VertexWithCompacity.txx" diff --git a/Code/SpatialReasoning/otbRCC8VertexWithCompacity.txx b/Code/SpatialReasoning/otbRCC8VertexWithCompacity.txx index 8ba8146c31c5fd0b3cd019cf86bfd546ca344273..e7d412ae81d9228e39a8931ede3d730db56fdc30 100644 --- a/Code/SpatialReasoning/otbRCC8VertexWithCompacity.txx +++ b/Code/SpatialReasoning/otbRCC8VertexWithCompacity.txx @@ -67,9 +67,9 @@ template <class TPath,class TPrecision> void RCC8VertexWithCompacity<TPath,TPrecision> ::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"Compacity: "<<m_Compacity<<std::endl; - } +{ + Superclass::PrintSelf(os,indent); + os<<indent<<"Compacity: "<<m_Compacity<<std::endl; +} } // end namespace otb #endif diff --git a/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.h b/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.h index 1db1946a53cfb955fb5d6c924b5d9ad7fdfbc76d..e40b479bdc7a637057a476162fd1fffb59d70178 100644 --- a/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.h +++ b/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.h @@ -23,62 +23,62 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class RCC8VertexWithRegionCenter - * \brief Class to represent a vertex in a RCC8 Graph with the compacity value of - * the represented region. - * - * \sa RCC8Graph, RCC8Edge, RCC8VertexBase - */ - template <class TLabel, class TPrecision = float> - class ITK_EXPORT RCC8VertexWithRegionCenter - : public RCC8VertexBase<TLabel> - { - public: - /** Standard class typedefs */ - typedef RCC8VertexWithRegionCenter Self; - typedef otb::RCC8VertexBase<TLabel> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - /** Method for creation through the object factory. */ - itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(RCC8VertexWithRegionCenter,RCC8VertexBase); - /** Input image associated typedefs*/ - typedef TLabel LabelType; - /** Precision typedef */ - typedef TPrecision PrecisionType; - /** char* vector attributes */ - typedef typename Superclass::AttributesMapType AttributesMapType; +/** \class RCC8VertexWithRegionCenter + * \brief Class to represent a vertex in a RCC8 Graph with the compacity value of + * the represented region. + * + * \sa RCC8Graph, RCC8Edge, RCC8VertexBase + */ +template <class TLabel, class TPrecision = float> +class ITK_EXPORT RCC8VertexWithRegionCenter + : public RCC8VertexBase<TLabel> +{ +public: + /** Standard class typedefs */ + typedef RCC8VertexWithRegionCenter Self; + typedef otb::RCC8VertexBase<TLabel> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + /** Method for creation through the object factory. */ + itkNewMacro(Self); + /** Run-time type information (and related methods). */ + itkTypeMacro(RCC8VertexWithRegionCenter,RCC8VertexBase); + /** Input image associated typedefs*/ + typedef TLabel LabelType; + /** Precision typedef */ + typedef TPrecision PrecisionType; + /** char* vector attributes */ + typedef typename Superclass::AttributesMapType AttributesMapType; - itkGetMacro(RegionCenterXCoordinate,PrecisionType); - itkSetMacro(RegionCenterXCoordinate,PrecisionType); - itkGetMacro(RegionCenterYCoordinate,PrecisionType); - itkSetMacro(RegionCenterYCoordinate,PrecisionType); - /** - * Set the VertexWithRegionCenter attributes from the attributes vector. - * \param attributes The vector containing the parsed attributes. - */ - void SetAttributesMap(AttributesMapType attributes); - /** - * Get an attributes vector representing the VertexWithRegionCenter attributes. - * \return The attributes vector - */ - AttributesMapType GetAttributesMap(void); + itkGetMacro(RegionCenterXCoordinate,PrecisionType); + itkSetMacro(RegionCenterXCoordinate,PrecisionType); + itkGetMacro(RegionCenterYCoordinate,PrecisionType); + itkSetMacro(RegionCenterYCoordinate,PrecisionType); + /** + * Set the VertexWithRegionCenter attributes from the attributes vector. + * \param attributes The vector containing the parsed attributes. + */ + void SetAttributesMap(AttributesMapType attributes); + /** + * Get an attributes vector representing the VertexWithRegionCenter attributes. + * \return The attributes vector + */ + AttributesMapType GetAttributesMap(void); - protected: - /** Constructor */ - RCC8VertexWithRegionCenter(); - /** Desctructor */ - ~RCC8VertexWithRegionCenter(){}; - /** PrintSelf method */ - void PrintSelf(std::ostream& os, itk::Indent indent) const; +protected: + /** Constructor */ + RCC8VertexWithRegionCenter(); + /** Desctructor */ + ~RCC8VertexWithRegionCenter() {}; + /** PrintSelf method */ + void PrintSelf(std::ostream& os, itk::Indent indent) const; - private: - /** The compacity */ - PrecisionType m_RegionCenterXCoordinate; - PrecisionType m_RegionCenterYCoordinate; - }; +private: + /** The compacity */ + PrecisionType m_RegionCenterXCoordinate; + PrecisionType m_RegionCenterYCoordinate; +}; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbRCC8VertexWithRegionCenter.txx" diff --git a/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.txx b/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.txx index e4f67820480b264eaaa9f5206ccedd05074de0f8..70e90d56b27bc3cffa169a1f8b0cb65b2c104017 100644 --- a/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.txx +++ b/Code/SpatialReasoning/otbRCC8VertexWithRegionCenter.txx @@ -72,10 +72,10 @@ template <class TLabel,class TPrecision> void RCC8VertexWithRegionCenter<TLabel,TPrecision> ::PrintSelf( std::ostream& os,itk::Indent indent ) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"RegionCenterXCoordinate: "<<m_RegionCenterXCoordinate<<std::endl; - os<<indent<<"RegionCenterXCoordinate: "<<m_RegionCenterYCoordinate<<std::endl; - } +{ + Superclass::PrintSelf(os,indent); + os<<indent<<"RegionCenterXCoordinate: "<<m_RegionCenterXCoordinate<<std::endl; + os<<indent<<"RegionCenterXCoordinate: "<<m_RegionCenterYCoordinate<<std::endl; +} } // end namespace otb #endif diff --git a/Code/Visu/otbFixedSizeFullImageWidget.h b/Code/Visu/otbFixedSizeFullImageWidget.h index 3d0d0b7599a465d3834d6708d41767bb385416aa..716edf78defd5f3fe92069479f94011fa5994154 100644 --- a/Code/Visu/otbFixedSizeFullImageWidget.h +++ b/Code/Visu/otbFixedSizeFullImageWidget.h @@ -22,85 +22,85 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class FixedSizeFullImageWidget - * \brief FixedSizeFullImageWidget - * - */ - template <class TPixel> - class FixedSizeFullImageWidget - : public ImageWidgetBase<TPixel> - { - public: - /** Standard class typedefs */ - typedef FixedSizeFullImageWidget Self; - typedef ImageWidgetBase<TPixel> Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory */ - itkNewMacro(Self); - - /** Runtime information */ - itkTypeMacro(FixedSizeFullImageWidget,ImageWidgetBase); - - /** Superclass typedefs */ - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::RegionType RegionType; - - itkSetMacro(WindowSize,SizeType); - itkGetMacro(WindowSize,SizeType); - - /** Unlarge OpenGlBuffer */ - virtual void UpdateOpenGlBufferedRegion(void); - /** Test if the buffer has to be enlarged */ - virtual bool UpdateOpenGlBufferedRegionRequested(void); - /** Initialize the widget */ - virtual void Init(int x, int y, int w, int h, const char * l); - /** Resize the widget */ - virtual void resize(int x, int y, int w, int h); - - protected: - /** Constructor. */ - FixedSizeFullImageWidget(); - /** Destructor. */ - ~FixedSizeFullImageWidget(); - - /** Return the width and heigh of the displayed image (overloaded for scroll)*/ - int wDisplayed() +/** \class FixedSizeFullImageWidget + * \brief FixedSizeFullImageWidget + * + */ +template <class TPixel> +class FixedSizeFullImageWidget + : public ImageWidgetBase<TPixel> +{ +public: + /** Standard class typedefs */ + typedef FixedSizeFullImageWidget Self; + typedef ImageWidgetBase<TPixel> Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory */ + itkNewMacro(Self); + + /** Runtime information */ + itkTypeMacro(FixedSizeFullImageWidget,ImageWidgetBase); + + /** Superclass typedefs */ + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::RegionType RegionType; + + itkSetMacro(WindowSize,SizeType); + itkGetMacro(WindowSize,SizeType); + + /** Unlarge OpenGlBuffer */ + virtual void UpdateOpenGlBufferedRegion(void); + /** Test if the buffer has to be enlarged */ + virtual bool UpdateOpenGlBufferedRegionRequested(void); + /** Initialize the widget */ + virtual void Init(int x, int y, int w, int h, const char * l); + /** Resize the widget */ + virtual void resize(int x, int y, int w, int h); + +protected: + /** Constructor. */ + FixedSizeFullImageWidget(); + /** Destructor. */ + ~FixedSizeFullImageWidget(); + + /** Return the width and heigh of the displayed image (overloaded for scroll)*/ + int wDisplayed() { if (this->GetViewedRegion().GetSize()[0] / static_cast<float>(this->GetViewedRegion().GetSize()[1]) > this->w() / static_cast<float>(this->h())) - { - return this->w(); - } + { + return this->w(); + } else - { - return this->h()*this->GetViewedRegion().GetSize()[0] / this->GetViewedRegion().GetSize()[1]; - } + { + return this->h()*this->GetViewedRegion().GetSize()[0] / this->GetViewedRegion().GetSize()[1]; + } } - int hDisplayed() + int hDisplayed() { if (this->GetViewedRegion().GetSize()[0] / static_cast<float>(this->GetViewedRegion().GetSize()[1]) > this->w() / static_cast<float>(this->h())) - { - return this->w()*this->GetViewedRegion().GetSize()[1] / this->GetViewedRegion().GetSize()[0]; - } + { + return this->w()*this->GetViewedRegion().GetSize()[1] / this->GetViewedRegion().GetSize()[0]; + } else - { - return this->h(); - } + { + return this->h(); + } } - - private: - FixedSizeFullImageWidget(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented - - SizeType m_WindowSize; - bool m_ImageLoaded; - bool m_ImageOverlayLoaded; - }; + +private: + FixedSizeFullImageWidget(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented + + SizeType m_WindowSize; + bool m_ImageLoaded; + bool m_ImageOverlayLoaded; +}; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION #include "otbFixedSizeFullImageWidget.txx" diff --git a/Code/Visu/otbFixedSizeFullImageWidget.txx b/Code/Visu/otbFixedSizeFullImageWidget.txx index 77143043202676bfd1553bac5e1c3186b2ac5459..b36c57e0b3c35513acdb02dec8680aa3f51f7376 100644 --- a/Code/Visu/otbFixedSizeFullImageWidget.txx +++ b/Code/Visu/otbFixedSizeFullImageWidget.txx @@ -59,17 +59,17 @@ FixedSizeFullImageWidget<TPixel> { m_ImageLoaded=false; m_ImageOverlayLoaded=false; - if(!this->GetInput()) - { - itkExceptionMacro("No input image!"); - } + if (!this->GetInput()) + { + itkExceptionMacro("No input image!"); + } else - { - Superclass::Init(x,y,w,h,l); - this->SetViewedRegion(this->GetInput()->GetLargestPossibleRegion()); - this->label(l); - this->resize(x, y, w, h); - } + { + Superclass::Init(x,y,w,h,l); + this->SetViewedRegion(this->GetInput()->GetLargestPossibleRegion()); + this->label(l); + this->resize(x, y, w, h); + } } /** @@ -102,15 +102,15 @@ bool FixedSizeFullImageWidget<TPixel> ::UpdateOpenGlBufferedRegionRequested(void) { - if(m_ImageLoaded && this->GetBufferedRegion().GetNumberOfPixels()!=0) - { - return false; - } + if (m_ImageLoaded && this->GetBufferedRegion().GetNumberOfPixels()!=0) + { + return false; + } else - { - m_ImageLoaded=true; - return true; - } + { + m_ImageLoaded=true; + return true; + } } /** * Update OpenGlBuffer. diff --git a/Code/Visu/otbFullResolutionImageWidget.h b/Code/Visu/otbFullResolutionImageWidget.h index f7e3f6597a058e5605f15e09f786fdad4c16d84f..05afa27928564e53aac131dd9be968ce5a1f9d22 100644 --- a/Code/Visu/otbFullResolutionImageWidget.h +++ b/Code/Visu/otbFullResolutionImageWidget.h @@ -28,9 +28,9 @@ namespace otb */ template <class TPixel> class FullResolutionImageWidget - : public ImageWidgetBase<TPixel> + : public ImageWidgetBase<TPixel> { - public: +public: /** Standard class typedefs */ typedef FullResolutionImageWidget Self; typedef ImageWidgetBase<TPixel> Superclass; @@ -65,17 +65,17 @@ class FullResolutionImageWidget virtual void SetUpperLeftCorner(IndexType index); itkGetMacro(UpperLeftCorner,IndexType); - protected: +protected: /** Constructor. */ - FullResolutionImageWidget(); - /** Destructor. */ - ~FullResolutionImageWidget(); + FullResolutionImageWidget(); + /** Destructor. */ + ~FullResolutionImageWidget(); - private: - FullResolutionImageWidget(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented +private: + FullResolutionImageWidget(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented - IndexType m_UpperLeftCorner; + IndexType m_UpperLeftCorner; }; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/Visu/otbFullResolutionImageWidget.txx b/Code/Visu/otbFullResolutionImageWidget.txx index b031ae23307d1afcab9b4ef4ac90bfe5a50eb2f7..c3ed569ece0e01b19d3e9443901101d2b050f700 100644 --- a/Code/Visu/otbFullResolutionImageWidget.txx +++ b/Code/Visu/otbFullResolutionImageWidget.txx @@ -56,23 +56,23 @@ FullResolutionImageWidget<TPixel> ::Init(int x, int y, int w, int h, const char * l) { - if(!this->GetInput()) - { - itkExceptionMacro("No input image!"); - } + if (!this->GetInput()) + { + itkExceptionMacro("No input image!"); + } else - { - Superclass::Init(x,y,w,h,l); - if(this->GetImageOverlayVisible()) { - if(!this->GetInputOverlay()) + Superclass::Init(x,y,w,h,l); + if (this->GetImageOverlayVisible()) + { + if (!this->GetInputOverlay()) { itkExceptionMacro("No input image overlay!"); } - } - this->label(l); - this->resize(x, y, w, h); } + this->label(l); + this->resize(x, y, w, h); + } } /** * Resize the widget. @@ -94,9 +94,9 @@ FullResolutionImageWidget<TPixel> this->SetViewedRegion(region); this->redraw(); this->Fl_Gl_Window::resize(x, - y, - region.GetSize()[0], - region.GetSize()[1]); + y, + region.GetSize()[0], + region.GetSize()[1]); } /** @@ -114,9 +114,9 @@ FullResolutionImageWidget<TPixel> IndexType viewedRDCorner = viewed.GetIndex()+viewed.GetSize(); IndexType bufferedRDCorner = buffered.GetIndex()+buffered.GetSize(); return ( viewedULCorner[0]<bufferedULCorner[0] - ||viewedULCorner[1]<bufferedULCorner[1] - ||viewedRDCorner[0]>bufferedRDCorner[0] - ||viewedRDCorner[1]>bufferedRDCorner[1]); + ||viewedULCorner[1]<bufferedULCorner[1] + ||viewedRDCorner[0]>bufferedRDCorner[0] + ||viewedRDCorner[1]>bufferedRDCorner[1]); } /** diff --git a/Code/Visu/otbGluPolygonDrawingHelper.cxx b/Code/Visu/otbGluPolygonDrawingHelper.cxx index 0e598214ac88f891e99251155a76a5be09bef7ec..e1d5c8501f9f73598de937b46a7d4d4b4b9c920f 100644 --- a/Code/Visu/otbGluPolygonDrawingHelper.cxx +++ b/Code/Visu/otbGluPolygonDrawingHelper.cxx @@ -26,31 +26,31 @@ PURPOSE. See the above copyright notices for more information. // There are function prototype conflits under cygwin between standard w32 API // and standard C ones #ifndef CALLBACK - #if defined(__CYGWIN__) - #define CALLBACK __stdcall - #else - #define CALLBACK - #endif +#if defined(__CYGWIN__) +#define CALLBACK __stdcall +#else +#define CALLBACK +#endif #endif extern "C" { - typedef void (CALLBACK * FunctionPointerType)(); - - void CombineCallback(GLdouble coords[3],GLdouble * data[4], GLfloat weights[4],GLdouble **dataOut) -{ - GLdouble * vertex = new GLdouble[3]; - vertex[0] = coords[0]; - vertex[1] = coords[1]; - vertex[2] = coords[2]; - *dataOut = vertex; -} - - void ErrorCallback(GLenum errorCode) -{ - const GLubyte * estring = gluErrorString(errorCode); - std::cout<<"Glu Tesselation error: "<<estring<<std::endl; -} + typedef void (CALLBACK * FunctionPointerType)(); + + void CombineCallback(GLdouble coords[3],GLdouble * data[4], GLfloat weights[4],GLdouble **dataOut) + { + GLdouble * vertex = new GLdouble[3]; + vertex[0] = coords[0]; + vertex[1] = coords[1]; + vertex[2] = coords[2]; + *dataOut = vertex; + } + + void ErrorCallback(GLenum errorCode) + { + const GLubyte * estring = gluErrorString(errorCode); + std::cout<<"Glu Tesselation error: "<<estring<<std::endl; + } } // end extern C namespace otb @@ -77,17 +77,17 @@ GluPolygonDrawingHelper::GluPolygonDrawingHelper() GluPolygonDrawingHelper::~GluPolygonDrawingHelper() { - gluDeleteTess(m_GluTesselator); + gluDeleteTess(m_GluTesselator); } void GluPolygonDrawingHelper::SetWindingRule(GLdouble windingRule) { - gluTessProperty(m_GluTesselator,GLU_TESS_WINDING_RULE,windingRule); + gluTessProperty(m_GluTesselator,GLU_TESS_WINDING_RULE,windingRule); } void GluPolygonDrawingHelper::SetBoundaryOnly(GLdouble boundaryOnly) { - gluTessProperty(m_GluTesselator,GLU_TESS_BOUNDARY_ONLY,boundaryOnly); + gluTessProperty(m_GluTesselator,GLU_TESS_BOUNDARY_ONLY,boundaryOnly); } void GluPolygonDrawingHelper::Color3d(double r, double g, double b) @@ -118,11 +118,11 @@ void GluPolygonDrawingHelper::Vertex2d(double x, double y) void GluPolygonDrawingHelper::Vertex3d(double x, double y, double z) { - PointType p; - p[0]=x; - p[1]=y; - p[2]=z; - m_PointVector.push_back(p); + PointType p; + p[0]=x; + p[1]=y; + p[2]=z; + m_PointVector.push_back(p); } void GluPolygonDrawingHelper::RenderPolygon() @@ -131,29 +131,29 @@ void GluPolygonDrawingHelper::RenderPolygon() GLdouble ** data = new GLdouble*[m_PointVector.size()]; unsigned int i = 0; PointVectorType::iterator it; - for(it = m_PointVector.begin();it!=m_PointVector.end();++i,++it) - { - data[i]= new GLdouble[3]; - data[i][0]=(*it)[0]; - data[i][1]=(*it)[1]; - data[i][2]=(*it)[2]; - } + for (it = m_PointVector.begin();it!=m_PointVector.end();++i,++it) + { + data[i]= new GLdouble[3]; + data[i][0]=(*it)[0]; + data[i][1]=(*it)[1]; + data[i][2]=(*it)[2]; + } // Set the color glColor4d(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); gluTessBeginPolygon(m_GluTesselator, NULL); gluTessBeginContour(m_GluTesselator); - for(i=0;i<m_PointVector.size();++i) - { - gluTessVertex(m_GluTesselator,data[i],data[i]); - } + for (i=0;i<m_PointVector.size();++i) + { + gluTessVertex(m_GluTesselator,data[i],data[i]); + } gluTessEndContour(m_GluTesselator); gluTessEndPolygon(m_GluTesselator); - for(i=0;i<m_PointVector.size();++i) - { - delete []data[i]; - } + for (i=0;i<m_PointVector.size();++i) + { + delete []data[i]; + } delete []data; m_PointVector.clear(); diff --git a/Code/Visu/otbGluPolygonDrawingHelper.h b/Code/Visu/otbGluPolygonDrawingHelper.h index a290bcad30776a5604780da70eeb5d5fde11327d..90ef91676c9796d438758e1911b228902f8ce888 100644 --- a/Code/Visu/otbGluPolygonDrawingHelper.h +++ b/Code/Visu/otbGluPolygonDrawingHelper.h @@ -32,100 +32,100 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class GluPolygonDrawingHelper - * \brief This class is a short helper class to render complex polygons in openGl. - * - * It uses the glu tesselator functionality. - */ +/** \class GluPolygonDrawingHelper + * \brief This class is a short helper class to render complex polygons in openGl. + * + * It uses the glu tesselator functionality. + */ class ITK_EXPORT GluPolygonDrawingHelper - : public itk::Object - { - public: - - typedef GluPolygonDrawingHelper Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef itk::Point<double,3> PointType; - typedef std::vector<PointType> PointVectorType; - - itkTypeMacro(GluPolygonDrawingHelper,Object); - - itkNewMacro(Self); - - - /** - * Set the current color. - * \param r red component - * \param g green component - * \param b blue component - * \param alpha component - */ - void Color4d(double r, double g, double b, double alpha); - - /** - * Set the current color. - * \param r red component - * \param g green component - * \param b blue component - */ - void Color3d(double r, double g, double b); - - /** - * Add a new 3d vertex. - * \param x position - * \param y position - * \param z position - */ - void Vertex3d(double x, double y, double z); - - /** - * Add a new 2d vertex. - * \param x position - * \param y position - */ - void Vertex2d(double x,double y); - - /** - * Set the the winding rule for the tesselator. - * \param windingRule the rule. - */ - void SetWindingRule(GLdouble windingRule); - - /** - * Set the the winding rule for the tesselator. - * \param boundaryOnly the flag. - */ - void SetBoundaryOnly(GLdouble boundaryOnly); - - /** - * Actually render the polygon. - * The list of temporary vertices. - */ - void RenderPolygon(); - - protected: - - /** - * Constructor. - */ - GluPolygonDrawingHelper(); - /** - * Destructor. - */ - ~GluPolygonDrawingHelper(); - - GluPolygonDrawingHelper(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented - - - private: - /** Store the point of the polygon */ - PointVectorType m_PointVector; - /** The glu tesselator object */ - GLUtesselator * m_GluTesselator; - /** Color of the polygon */ - GLdouble m_Color[4]; - }; + : public itk::Object +{ +public: + + typedef GluPolygonDrawingHelper Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef itk::Point<double,3> PointType; + typedef std::vector<PointType> PointVectorType; + + itkTypeMacro(GluPolygonDrawingHelper,Object); + + itkNewMacro(Self); + + + /** + * Set the current color. + * \param r red component + * \param g green component + * \param b blue component + * \param alpha component + */ + void Color4d(double r, double g, double b, double alpha); + + /** + * Set the current color. + * \param r red component + * \param g green component + * \param b blue component + */ + void Color3d(double r, double g, double b); + + /** + * Add a new 3d vertex. + * \param x position + * \param y position + * \param z position + */ + void Vertex3d(double x, double y, double z); + + /** + * Add a new 2d vertex. + * \param x position + * \param y position + */ + void Vertex2d(double x,double y); + + /** + * Set the the winding rule for the tesselator. + * \param windingRule the rule. + */ + void SetWindingRule(GLdouble windingRule); + + /** + * Set the the winding rule for the tesselator. + * \param boundaryOnly the flag. + */ + void SetBoundaryOnly(GLdouble boundaryOnly); + + /** + * Actually render the polygon. + * The list of temporary vertices. + */ + void RenderPolygon(); + +protected: + + /** + * Constructor. + */ + GluPolygonDrawingHelper(); + /** + * Destructor. + */ + ~GluPolygonDrawingHelper(); + + GluPolygonDrawingHelper(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented + + +private: + /** Store the point of the polygon */ + PointVectorType m_PointVector; + /** The glu tesselator object */ + GLUtesselator * m_GluTesselator; + /** Color of the polygon */ + GLdouble m_Color[4]; +}; } // end namespace otb #endif diff --git a/Code/Visu/otbHistogramAndTransferFunctionWidget.h b/Code/Visu/otbHistogramAndTransferFunctionWidget.h index 5eddebc0d269b78b6ad7af9ef0e40d0fbc6d817b..d39f29ba57d50d624d62a08688f60f10b47a7a1e 100644 --- a/Code/Visu/otbHistogramAndTransferFunctionWidget.h +++ b/Code/Visu/otbHistogramAndTransferFunctionWidget.h @@ -34,9 +34,9 @@ namespace otb */ template <class THistogram, class TPixel> class ITK_EXPORT HistogramAndTransferFunctionWidget - : public Fl_Gl_Window, public itk::ProcessObject + : public Fl_Gl_Window, public itk::ProcessObject { - public: +public: /** Standard typedefs */ typedef HistogramAndTransferFunctionWidget Self; typedef itk::ProcessObject Superclass; @@ -68,10 +68,10 @@ class ITK_EXPORT HistogramAndTransferFunctionWidget itkGetMacro(TransferFunction,TransferFunctionPointerType); virtual void SetTransferFunction(TransferFunctionType * function) - { - m_TransferFunction = function; - this->Modified(); - } + { + m_TransferFunction = function; + this->Modified(); + } itkSetMacro(HistogramColor,ColorType); itkGetMacro(HistogramColor,ColorType); @@ -106,7 +106,7 @@ protected: HistogramAndTransferFunctionWidget(); /** Destructor */ virtual ~HistogramAndTransferFunctionWidget() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Draw the histogram */ @@ -161,7 +161,7 @@ private: bool m_Updating; /** Label of the histogram */ std::string m_Label; -/** Label of the histogram */ + /** Label of the histogram */ std::string m_TransferFunctionLabel; }; diff --git a/Code/Visu/otbHistogramAndTransferFunctionWidget.txx b/Code/Visu/otbHistogramAndTransferFunctionWidget.txx index 97aa953528e7cf0025583910ddae333633473d2a..f906ea4d2780d54cc0dbb093360082ecb03459ac 100644 --- a/Code/Visu/otbHistogramAndTransferFunctionWidget.txx +++ b/Code/Visu/otbHistogramAndTransferFunctionWidget.txx @@ -28,7 +28,7 @@ namespace otb template <class THistogram, class TPixel> HistogramAndTransferFunctionWidget<THistogram,TPixel> ::HistogramAndTransferFunctionWidget() - : Fl_Gl_Window(0,0,0,0,0) + : Fl_Gl_Window(0,0,0,0,0) { m_Label = "Default label"; m_TransferFunctionLabel = "Function label"; @@ -71,15 +71,15 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> ::OpenGlSetup() { if (!this->valid()) - { - valid(1); - glLoadIdentity(); - glViewport(0,0,w(),h()); - glClearColor(m_BackgroundColor[0], - m_BackgroundColor[1], - m_BackgroundColor[2], - 1); - } + { + valid(1); + glLoadIdentity(); + glViewport(0,0,w(),h()); + glClearColor(m_BackgroundColor[0], + m_BackgroundColor[1], + m_BackgroundColor[2], + 1); + } glShadeModel(GL_FLAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black @@ -99,23 +99,23 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> // Rendering grid glBegin(GL_LINES); glColor3d(m_GridColor[0],m_GridColor[1],m_GridColor[2]); - for(unsigned int i=1;i<m_GridSizeX;++i) - { - x=static_cast<double>(i)*gridXSpacing+m_MarginX; - y=m_MarginY; - glVertex2d(x,y); - y = static_cast<double>(this->h())-m_MarginY; - glVertex2d(x,y); - } + for (unsigned int i=1;i<m_GridSizeX;++i) + { + x=static_cast<double>(i)*gridXSpacing+m_MarginX; + y=m_MarginY; + glVertex2d(x,y); + y = static_cast<double>(this->h())-m_MarginY; + glVertex2d(x,y); + } - for(unsigned int i=1;i<m_GridSizeY;++i) - { - y=static_cast<double>(i)*gridYSpacing+m_MarginY; - x=m_MarginX; - glVertex2d(x,y); - x = static_cast<double>(this->w())-m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w()); - glVertex2d(x,y); - } + for (unsigned int i=1;i<m_GridSizeY;++i) + { + y=static_cast<double>(i)*gridYSpacing+m_MarginY; + x=m_MarginX; + glVertex2d(x,y); + x = static_cast<double>(this->w())-m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w()); + glVertex2d(x,y); + } glEnd(); } @@ -143,23 +143,23 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> // Temporary vertex coordinates double x,y; // Rendering histogram - for(it=m_Histogram->Begin();it!=m_Histogram->End();++it,startx+=binWidth) - { - - glBegin(GL_POLYGON); - glColor3d(m_HistogramColor[0],m_HistogramColor[1],m_HistogramColor[2]); + for (it=m_Histogram->Begin();it!=m_Histogram->End();++it,startx+=binWidth) + { - x =startx; - y = m_MarginY; - glVertex2d(x,y); - y += binHeightRatio*static_cast<double>((it.GetFrequency()>maxFrequency/m_HistogramClamping ? maxFrequency/m_HistogramClamping : it.GetFrequency())); - glVertex2d(x,y); - x += binWidth; - glVertex2d(x,y); - y=m_MarginY; - glVertex2d(x,y); - glEnd(); - } + glBegin(GL_POLYGON); + glColor3d(m_HistogramColor[0],m_HistogramColor[1],m_HistogramColor[2]); + + x =startx; + y = m_MarginY; + glVertex2d(x,y); + y += binHeightRatio*static_cast<double>((it.GetFrequency()>maxFrequency/m_HistogramClamping ? maxFrequency/m_HistogramClamping : it.GetFrequency())); + glVertex2d(x,y); + x += binWidth; + glVertex2d(x,y); + y=m_MarginY; + glVertex2d(x,y); + glEnd(); + } } @@ -174,7 +174,7 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> glBegin(GL_LINES); double factor = (m_Histogram->Quantile(0,1.)-m_Histogram->Quantile(0,0.)) - /(static_cast<double>(this->w())-2*m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w())); + /(static_cast<double>(this->w())-2*m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w())); x = m_MarginX + static_cast<double>(m_TransferFunction->GetLowerBound()-m_Histogram->Quantile(0,0.))/factor; @@ -201,31 +201,31 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> glColor3d(m_TextColor[0],m_TextColor[1],m_TextColor[2]); gl_font(FL_COURIER_BOLD,10); double step = (m_Histogram->Quantile(0,1.)-m_Histogram->Quantile(0,0.)) - /static_cast<double>(m_GridSizeX); - for(unsigned int i=0;i<m_GridSizeX;++i) - { - ValueType value = static_cast<ValueType>(m_Histogram->Quantile(0,0.) - +static_cast<double>(i)*step); + /static_cast<double>(m_GridSizeX); + for (unsigned int i=0;i<m_GridSizeX;++i) + { + ValueType value = static_cast<ValueType>(m_Histogram->Quantile(0,0.) + +static_cast<double>(i)*step); // oss<<(int)value; - oss<<value; - x=static_cast<double>(i)*gridXSpacing+m_MarginX; - y=m_MarginY/2; - gl_draw(oss.str().c_str(),(float)x,(float)y); - oss.str(""); - } - for(unsigned int i=0;i<m_GridSizeY;++i) - { - unsigned int value = static_cast<unsigned int>(i - *maxFrequency/(m_HistogramClamping*static_cast<double>(m_GridSizeY))); - oss<<value; - y=static_cast<double>(i)*gridYSpacing+m_MarginY; - x=0; - gl_draw(oss.str().c_str(),(float)x,(float)y); - oss.str(""); - } - //rendering label - gl_font(FL_COURIER_BOLD,12); - gl_draw(m_Label.c_str(),static_cast<float>(3*this->w())/8,static_cast<float>(static_cast<double>(this->h())-m_MarginY/2)); + oss<<value; + x=static_cast<double>(i)*gridXSpacing+m_MarginX; + y=m_MarginY/2; + gl_draw(oss.str().c_str(),(float)x,(float)y); + oss.str(""); + } + for (unsigned int i=0;i<m_GridSizeY;++i) + { + unsigned int value = static_cast<unsigned int>(i + *maxFrequency/(m_HistogramClamping*static_cast<double>(m_GridSizeY))); + oss<<value; + y=static_cast<double>(i)*gridYSpacing+m_MarginY; + x=0; + gl_draw(oss.str().c_str(),(float)x,(float)y); + oss.str(""); + } +//rendering label + gl_font(FL_COURIER_BOLD,12); + gl_draw(m_Label.c_str(),static_cast<float>(3*this->w())/8,static_cast<float>(static_cast<double>(this->h())-m_MarginY/2)); } @@ -238,18 +238,18 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> glBegin(GL_LINE_STRIP); double x,y; double step = (m_Histogram->Quantile(0,1.)-m_Histogram->Quantile(0,0.)) - /static_cast<double>(m_Histogram->GetSize()[0]); + /static_cast<double>(m_Histogram->GetSize()[0]); double xscale = (static_cast<double>(this->w())-2*m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w()))/static_cast<double>(m_Histogram->GetSize()[0]); double yscale = (static_cast<double>(this->h())-2*m_MarginY)/255.; - for(unsigned int i=0;i<m_Histogram->Size()+1;++i) - { - PixelType value = static_cast<PixelType>(m_Histogram->Quantile(0,0.) - +static_cast<double>(i)*step); + for (unsigned int i=0;i<m_Histogram->Size()+1;++i) + { + PixelType value = static_cast<PixelType>(m_Histogram->Quantile(0,0.) + +static_cast<double>(i)*step); - x = m_MarginX + static_cast<double>(i)*xscale; - y = m_MarginY + yscale * static_cast<double>(m_TransferFunction->Map(value)); - glVertex2d(x,y); - } + x = m_MarginX + static_cast<double>(i)*xscale; + y = m_MarginY + yscale * static_cast<double>(m_TransferFunction->Map(value)); + glVertex2d(x,y); + } glEnd(); } @@ -261,62 +261,62 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> std::vector<unsigned int> outputHistogram(256,0); HistogramIteratorType it; - for(it=m_Histogram->Begin();it!=m_Histogram->End();++it) - { - outputHistogram[m_TransferFunction->Map(static_cast<PixelType>(it.GetMeasurementVector()[0]))]+=static_cast<unsigned int>(it.GetFrequency()); - } + for (it=m_Histogram->Begin();it!=m_Histogram->End();++it) + { + outputHistogram[m_TransferFunction->Map(static_cast<PixelType>(it.GetMeasurementVector()[0]))]+=static_cast<unsigned int>(it.GetFrequency()); + } // Setting the extremity to 0 to avoid sides effect outputHistogram[0]=0; outputHistogram[255]=0; std::vector<unsigned int>::iterator vit; unsigned int maxFrequency = 0; - for(vit=outputHistogram.begin();vit!=outputHistogram.end();++vit) - { - if(maxFrequency<(*vit)) + for (vit=outputHistogram.begin();vit!=outputHistogram.end();++vit) { - maxFrequency=(*vit); - } + if (maxFrequency<(*vit)) + { + maxFrequency=(*vit); } + } // Temporary vertex coordinates double x,y; - if(maxFrequency>0) - { - double binWidth = (static_cast<double>(this->h())-2*m_MarginY)/255.; - double binLengthRatio = m_HistogramClamping*m_OutputHistogramMargin*static_cast<double>(this->w())/static_cast<double>(maxFrequency); - double starty = m_MarginY; - - - // Rendering histogram - for(vit=outputHistogram.begin();vit!=outputHistogram.end();++vit,starty+=binWidth) - { - glBegin(GL_POLYGON); - glColor3d(m_TransferFunctionColor[0],m_TransferFunctionColor[1],m_TransferFunctionColor[2]); - - x =static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; - y = starty; - glVertex2d(x,y); - x += binLengthRatio*static_cast<double>((*vit)> maxFrequency/m_HistogramClamping ? maxFrequency/m_HistogramClamping : (*vit)); - glVertex2d(x,y); - y += binWidth; - glVertex2d(x,y); - x =static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; - glVertex2d(x,y); - glEnd(); - } - } - glBegin(GL_LINE_LOOP); - x = static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; - y = m_MarginY; - glVertex2d(x,y); - x+=m_OutputHistogramMargin*static_cast<double>(this->w()); - glVertex2d(x,y); - y = static_cast<double>(this->h())-m_MarginY; - glVertex2d(x,y); - x = static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; - glVertex2d(x,y); - glEnd(); + if (maxFrequency>0) + { + double binWidth = (static_cast<double>(this->h())-2*m_MarginY)/255.; + double binLengthRatio = m_HistogramClamping*m_OutputHistogramMargin*static_cast<double>(this->w())/static_cast<double>(maxFrequency); + double starty = m_MarginY; + + + // Rendering histogram + for (vit=outputHistogram.begin();vit!=outputHistogram.end();++vit,starty+=binWidth) + { + glBegin(GL_POLYGON); + glColor3d(m_TransferFunctionColor[0],m_TransferFunctionColor[1],m_TransferFunctionColor[2]); + + x =static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; + y = starty; + glVertex2d(x,y); + x += binLengthRatio*static_cast<double>((*vit)> maxFrequency/m_HistogramClamping ? maxFrequency/m_HistogramClamping : (*vit)); + glVertex2d(x,y); + y += binWidth; + glVertex2d(x,y); + x =static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; + glVertex2d(x,y); + glEnd(); + } + } + glBegin(GL_LINE_LOOP); + x = static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; + y = m_MarginY; + glVertex2d(x,y); + x+=m_OutputHistogramMargin*static_cast<double>(this->w()); + glVertex2d(x,y); + y = static_cast<double>(this->h())-m_MarginY; + glVertex2d(x,y); + x = static_cast<double>(this->w())-m_OutputHistogramMargin*static_cast<double>(this->w())-m_MarginX/2; + glVertex2d(x,y); + glEnd(); } @@ -325,9 +325,9 @@ void HistogramAndTransferFunctionWidget<THistogram,TPixel> ::TransferFunctionLabelRendering(void) { - //rendering label - gl_font(FL_COURIER_BOLD,12); - gl_draw(m_TransferFunctionLabel.c_str(),static_cast<float>(this->w()-m_MarginX/2-m_OutputHistogramMargin*static_cast<double>(this->w())),static_cast<float>(m_MarginY/2)); +//rendering label + gl_font(FL_COURIER_BOLD,12); + gl_draw(m_TransferFunctionLabel.c_str(),static_cast<float>(this->w()-m_MarginX/2-m_OutputHistogramMargin*static_cast<double>(this->w())),static_cast<float>(m_MarginY/2)); } @@ -337,12 +337,12 @@ void HistogramAndTransferFunctionWidget<THistogram,TPixel> ::draw() { - if(!m_Histogram) - { - return; - } + if (!m_Histogram) + { + return; + } - if(m_Updating) + if (m_Updating) return; m_Updating = true; @@ -351,13 +351,13 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> HistogramIteratorType it; // Computing histogram max frequency - for(it=m_Histogram->Begin();it!=m_Histogram->End();++it) - { - if(it.GetFrequency()>maxFrequency) + for (it=m_Histogram->Begin();it!=m_Histogram->End();++it) { - maxFrequency = it.GetFrequency(); - } + if (it.GetFrequency()>maxFrequency) + { + maxFrequency = it.GetFrequency(); } + } double binWidth = static_cast<double>(this->w()-2*m_MarginX-m_OutputHistogramMargin*static_cast<double>(this->w()))/static_cast<double>(m_Histogram->GetSize()[0]); double binHeightRatio = m_HistogramClamping*static_cast<double>(this->h()-2*m_MarginY)/static_cast<double>(maxFrequency); @@ -371,13 +371,13 @@ HistogramAndTransferFunctionWidget<THistogram,TPixel> LegendRendering(gridXSpacing,gridYSpacing,maxFrequency); - if(m_TransferFunction) - { - BoundRendering(); - TransferFunctionRendering(); - OutputHistogramRendering(); - TransferFunctionLabelRendering(); - } + if (m_TransferFunction) + { + BoundRendering(); + TransferFunctionRendering(); + OutputHistogramRendering(); + TransferFunctionLabelRendering(); + } m_Updating = false; } diff --git a/Code/Visu/otbImageAlternateViewer.h b/Code/Visu/otbImageAlternateViewer.h index 7ffc800e8baa668a331cc2c2d72b610350af93c2..ecd55f7440b88689cbabca2efc995302ea3b1e1f 100644 --- a/Code/Visu/otbImageAlternateViewer.h +++ b/Code/Visu/otbImageAlternateViewer.h @@ -40,9 +40,9 @@ namespace otb */ template <class TPixel> class ITK_EXPORT ImageAlternateViewer - : public Fl_Gl_Window, public itk::Object + : public Fl_Gl_Window, public itk::Object { - public: +public: /** Standard typedefs */ typedef ImageAlternateViewer Self; typedef itk::Object Superclass; @@ -56,95 +56,95 @@ class ITK_EXPORT ImageAlternateViewer itkTypeMacro(ImageAlternateViewer,Object); /** Template related typedef */ - typedef TPixel PixelType; - typedef otb::VectorImage<PixelType,2> ImageType; - typedef otb::Image<PixelType,2> SingleImageType; - typedef typename ImageType::PixelType VectorPixelType; - typedef typename ImageType::Pointer ImagePointerType; - typedef typename ImageType::SizeType SizeType; - typedef typename ImageType::IndexType IndexType; - typedef typename ImageType::RegionType RegionType; - typedef typename ImageType::SpacingType SpacingType; - typedef typename ImageType::PointType PointType; + typedef TPixel PixelType; + typedef otb::VectorImage<PixelType,2> ImageType; + typedef otb::Image<PixelType,2> SingleImageType; + typedef typename ImageType::PixelType VectorPixelType; + typedef typename ImageType::Pointer ImagePointerType; + typedef typename ImageType::SizeType SizeType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::RegionType RegionType; + typedef typename ImageType::SpacingType SpacingType; + typedef typename ImageType::PointType PointType; - typedef otb::ImageList<SingleImageType> ImageListType; - typedef otb::VectorImageToImageListFilter<ImageType,ImageListType> VectorImageDecompositionFilterType; - typedef typename VectorImageDecompositionFilterType::Pointer VectorImageDecompositionFilterPointerType; + typedef otb::ImageList<SingleImageType> ImageListType; + typedef otb::VectorImageToImageListFilter<ImageType,ImageListType> VectorImageDecompositionFilterType; + typedef typename VectorImageDecompositionFilterType::Pointer VectorImageDecompositionFilterPointerType; - typedef itk::InterpolateImageFunction<SingleImageType,double> InterpolatorType; - typedef typename InterpolatorType::Pointer InterpolatorPointerType; - typedef itk::LinearInterpolateImageFunction<SingleImageType,double> DefaultInterpolatorType; + typedef itk::InterpolateImageFunction<SingleImageType,double> InterpolatorType; + typedef typename InterpolatorType::Pointer InterpolatorPointerType; + typedef itk::LinearInterpolateImageFunction<SingleImageType,double> DefaultInterpolatorType; - typedef itk::ImageRegionSplitter<2> SplitterType; - typedef typename SplitterType::Pointer SplitterPointerType; + typedef itk::ImageRegionSplitter<2> SplitterType; + typedef typename SplitterType::Pointer SplitterPointerType; - itkSetMacro(RedChannelIndex,unsigned int); - itkGetMacro(RedChannelIndex,unsigned int); + itkSetMacro(RedChannelIndex,unsigned int); + itkGetMacro(RedChannelIndex,unsigned int); - itkSetMacro(GreenChannelIndex,unsigned int); - itkGetMacro(GreenChannelIndex,unsigned int); + itkSetMacro(GreenChannelIndex,unsigned int); + itkGetMacro(GreenChannelIndex,unsigned int); - itkSetMacro(BlueChannelIndex,unsigned int); - itkGetMacro(BlueChannelIndex,unsigned int); + itkSetMacro(BlueChannelIndex,unsigned int); + itkGetMacro(BlueChannelIndex,unsigned int); - itkSetMacro(MaxComponentValues,VectorPixelType); - itkGetMacro(MaxComponentValues,VectorPixelType); + itkSetMacro(MaxComponentValues,VectorPixelType); + itkGetMacro(MaxComponentValues,VectorPixelType); - itkSetMacro(MinComponentValues,VectorPixelType); - itkGetMacro(MinComponentValues,VectorPixelType); + itkSetMacro(MinComponentValues,VectorPixelType); + itkGetMacro(MinComponentValues,VectorPixelType); - itkSetMacro(SpacingZoomFactor,double); - itkGetMacro(SpacingZoomFactor,double); + itkSetMacro(SpacingZoomFactor,double); + itkGetMacro(SpacingZoomFactor,double); - itkSetMacro(OpenGlIsotropicZoom,double); - itkGetMacro(OpenGlIsotropicZoom,double); + itkSetMacro(OpenGlIsotropicZoom,double); + itkGetMacro(OpenGlIsotropicZoom,double); - void SetViewedRegionCenter(const IndexType & index); - itkGetMacro(ViewedRegionCenter,IndexType); + void SetViewedRegionCenter(const IndexType & index); + itkGetMacro(ViewedRegionCenter,IndexType); - itkSetObjectMacro(Image,ImageType); - itkGetObjectMacro(Image,ImageType); + itkSetObjectMacro(Image,ImageType); + itkGetObjectMacro(Image,ImageType); - itkSetObjectMacro(SecondImage,ImageType); - itkGetObjectMacro(SecondImage,ImageType); + itkSetObjectMacro(SecondImage,ImageType); + itkGetObjectMacro(SecondImage,ImageType); - itkSetMacro(DisplayExtent,RegionType); - itkGetMacro(DisplayExtent,RegionType); + itkSetMacro(DisplayExtent,RegionType); + itkGetMacro(DisplayExtent,RegionType); - itkGetObjectMacro(ZoomInInterpolator,InterpolatorType); - itkSetObjectMacro(ZoomInInterpolator,InterpolatorType); - itkGetObjectMacro(ZoomOutInterpolator,InterpolatorType); - itkSetObjectMacro(ZoomOutInterpolator,InterpolatorType); + itkGetObjectMacro(ZoomInInterpolator,InterpolatorType); + itkSetObjectMacro(ZoomInInterpolator,InterpolatorType); + itkGetObjectMacro(ZoomOutInterpolator,InterpolatorType); + itkSetObjectMacro(ZoomOutInterpolator,InterpolatorType); - /** - * Set view mode to RGB. - */ - void SetViewModelToRGB(void); - /** - * Set view mode to Grayscale. - */ - void SetViewModelToGrayscale(void); + /** + * Set view mode to RGB. + */ + void SetViewModelToRGB(void); + /** + * Set view mode to Grayscale. + */ + void SetViewModelToGrayscale(void); - /** - * Set insight view model to RGB - */ - void SetInsightViewModelToRGB(void); + /** + * Set insight view model to RGB + */ + void SetInsightViewModelToRGB(void); - /** - * Set insight view model to grayscale - */ - void SetInsightViewModelToGrayscale(void); + /** + * Set insight view model to grayscale + */ + void SetInsightViewModelToGrayscale(void); - /** Normalization function */ - unsigned char Normalize(PixelType value, unsigned int channelIndex); + /** Normalization function */ + unsigned char Normalize(PixelType value, unsigned int channelIndex); - void Show(void); + void Show(void); - void Reset(void); + void Reset(void); - /** Initialize the widget */ - virtual void Init(int x, int y, int w, int h, const char * l); + /** Initialize the widget */ + virtual void Init(int x, int y, int w, int h, const char * l); /** Resize the widget */ virtual void resize(int x, int y, int w, int h); @@ -167,8 +167,8 @@ protected: /** Handle */ virtual int handle(int event); - /* /\** Rebuild opengl buffer *\/ */ -/* virtual void RebuildOpenGlBuffer(void); */ + /* /\** Rebuild opengl buffer *\/ */ + /* virtual void RebuildOpenGlBuffer(void); */ @@ -179,7 +179,7 @@ protected: unsigned char * CreateAdditionalBuffer(RegionType region,ImagePointerType image,bool rgb); virtual void MergeBuffersAndFreeMemory(std::vector<unsigned char *> bufferList, - std::vector<RegionType> bufferRegionList); + std::vector<RegionType> bufferRegionList); virtual void AdditionalRedraw(void); @@ -190,7 +190,7 @@ protected: virtual long IndexInOldGrid(PointType point, PointType oldUpperLeft, SpacingType spacing, SizeType size); RegionType ComputeRequestedRegion(RegionType ®ion); - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; private: @@ -269,7 +269,7 @@ private: RegionType m_SubWindowRegion; /** subwindow mode switch */ bool m_SubWindowMode; -/** subwindow mode switch */ + /** subwindow mode switch */ bool m_SubWindowMove; }; diff --git a/Code/Visu/otbImageAlternateViewer.txx b/Code/Visu/otbImageAlternateViewer.txx index 5b82def1a1c6c644d36b7b5a81c2e38588055560..7cb84bd13d2bc3eaae8f2cfb3c5494b6ae872f4f 100644 --- a/Code/Visu/otbImageAlternateViewer.txx +++ b/Code/Visu/otbImageAlternateViewer.txx @@ -27,1240 +27,1240 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor - */ - template <class TPixel> - ImageAlternateViewer<TPixel> - ::ImageAlternateViewer() +/** + * Constructor + */ +template <class TPixel> +ImageAlternateViewer<TPixel> +::ImageAlternateViewer() : Fl_Gl_Window(0,0,0,0,0) - { - m_Image = NULL; - m_OpenGlIsotropicZoom = 1.0; - m_OpenGlBuffer = NULL; - m_ViewModelIsRGB=true; - m_InsightViewModelIsRGB =true; - m_RedChannelIndex = 0; - m_GreenChannelIndex = 1; - m_BlueChannelIndex = 2; - - m_MinComponentValues.SetSize(1); - m_MaxComponentValues.SetSize(1); - m_MinComponentValues.Fill(0); - m_MaxComponentValues.Fill(255); - - m_DecompositionFilter = VectorImageDecompositionFilterType::New(); - - typename DefaultInterpolatorType::Pointer defaultInterpolator = DefaultInterpolatorType::New(); - m_ZoomInInterpolator=defaultInterpolator; - m_ZoomOutInterpolator = defaultInterpolator; - - m_SpacingZoomFactor=1; - m_Updating = false; - m_Drag = false; - m_DragEventCounter = 0; - m_OldMousePos.Fill(0); - m_ZoomState = 0; - m_SubWindowMode = false; - } - - /** - * Destructor - */ - template <class TPixel> - ImageAlternateViewer<TPixel> - ::~ImageAlternateViewer() - { - if(m_OpenGlBuffer != NULL) - { - delete [] m_OpenGlBuffer; - } - } +{ + m_Image = NULL; + m_OpenGlIsotropicZoom = 1.0; + m_OpenGlBuffer = NULL; + m_ViewModelIsRGB=true; + m_InsightViewModelIsRGB =true; + m_RedChannelIndex = 0; + m_GreenChannelIndex = 1; + m_BlueChannelIndex = 2; + + m_MinComponentValues.SetSize(1); + m_MaxComponentValues.SetSize(1); + m_MinComponentValues.Fill(0); + m_MaxComponentValues.Fill(255); + + m_DecompositionFilter = VectorImageDecompositionFilterType::New(); + + typename DefaultInterpolatorType::Pointer defaultInterpolator = DefaultInterpolatorType::New(); + m_ZoomInInterpolator=defaultInterpolator; + m_ZoomOutInterpolator = defaultInterpolator; + + m_SpacingZoomFactor=1; + m_Updating = false; + m_Drag = false; + m_DragEventCounter = 0; + m_OldMousePos.Fill(0); + m_ZoomState = 0; + m_SubWindowMode = false; +} - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::SetViewedRegionCenter(const IndexType & index) +/** + * Destructor + */ +template <class TPixel> +ImageAlternateViewer<TPixel> +::~ImageAlternateViewer() +{ + if (m_OpenGlBuffer != NULL) { - m_OldViewedRegionCenter = m_ViewedRegionCenter; - m_ViewedRegionCenter = index; + delete [] m_OpenGlBuffer; } +} - /** - * Reset the viewer - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::Reset(void) - { - const char * label = this->label(); - Init(this->x(),this->y(),this->w(),this->h(),label); - } +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::SetViewedRegionCenter(const IndexType & index) +{ + m_OldViewedRegionCenter = m_ViewedRegionCenter; + m_ViewedRegionCenter = index; +} +/** + * Reset the viewer + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::Reset(void) +{ + const char * label = this->label(); + Init(this->x(),this->y(),this->w(),this->h(),label); +} - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::Init(int x, int y, int w, int h, const char * l) - { - IndexType index; - SizeType size; - index[0]=0; - index[1]=0; - size[0]=w; - size[1]=h; +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::Init(int x, int y, int w, int h, const char * l) +{ + IndexType index; + SizeType size; - SizeType nullSize; - nullSize.Fill(0); + index[0]=0; + index[1]=0; + size[0]=w; + size[1]=h; - m_RequestedRegion.SetSize(nullSize); - m_RequestedRegion.SetIndex(index); - m_BufferedRegion=m_RequestedRegion; - m_OldBufferedRegion=m_BufferedRegion; + SizeType nullSize; + nullSize.Fill(0); - RegionType newRegion; - m_DisplayExtent.SetIndex(index); - m_DisplayExtent.SetSize(size); - m_OldDisplayExtent=m_DisplayExtent; + m_RequestedRegion.SetSize(nullSize); + m_RequestedRegion.SetIndex(index); + m_BufferedRegion=m_RequestedRegion; + m_OldBufferedRegion=m_BufferedRegion; - m_OldSpacingZoomFactor=m_SpacingZoomFactor; + RegionType newRegion; + m_DisplayExtent.SetIndex(index); + m_DisplayExtent.SetSize(size); + m_OldDisplayExtent=m_DisplayExtent; - m_Splitter=SplitterType::New(); + m_OldSpacingZoomFactor=m_SpacingZoomFactor; - m_SubWindowRegion.SetIndex(index); - m_SubWindowRegion.SetSize(nullSize); + m_Splitter=SplitterType::New(); - m_Image->UpdateOutputInformation(); - m_DecompositionFilter->SetInput(m_Image); - m_OldViewedRegionCenter = m_ViewedRegionCenter; + m_SubWindowRegion.SetIndex(index); + m_SubWindowRegion.SetSize(nullSize); - typename ImageListType::Pointer bandList = m_DecompositionFilter->GetOutput(); - bandList->UpdateOutputInformation(); - bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); + m_Image->UpdateOutputInformation(); + m_DecompositionFilter->SetInput(m_Image); + m_OldViewedRegionCenter = m_ViewedRegionCenter; - if(m_ViewModelIsRGB) - { - bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); - bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); - } - bandList->PropagateRequestedRegion(); + typename ImageListType::Pointer bandList = m_DecompositionFilter->GetOutput(); + bandList->UpdateOutputInformation(); + bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); - if(!this->GetImage()) - { - itkExceptionMacro("No input image!"); - } - this->label(l); - this->resize(x, - y, - m_DisplayExtent.GetSize()[0], - m_DisplayExtent.GetSize()[1]); - } - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::resize(int x, int y, int w, int h) + if (m_ViewModelIsRGB) { - if(m_Updating) - return; - // avoid odd sizes - if(w%2==1) - w+=1; - if(h%2==1) - h+=1; - - IndexType index; - SizeType size; - m_OldDisplayExtent=m_DisplayExtent; - index[0]=0; - index[1]=0; - size[0]=w; - size[1]=h; - - m_DisplayExtent.SetIndex(index); - m_DisplayExtent.SetSize(size); - - this->Fl_Gl_Window::resize(x,y,w,h); - this->redraw(); + bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); + bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); } - /** - * Set view mode to RGB. - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::SetViewModelToRGB(void) - { - m_ViewModelIsRGB=true; - } - /** - * Set view mode to Grayscale. - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::SetViewModelToGrayscale(void) + bandList->PropagateRequestedRegion(); + + if (!this->GetImage()) { - m_ViewModelIsRGB=false; + itkExceptionMacro("No input image!"); } + this->label(l); + this->resize(x, + y, + m_DisplayExtent.GetSize()[0], + m_DisplayExtent.GetSize()[1]); +} +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::resize(int x, int y, int w, int h) +{ + if (m_Updating) + return; + // avoid odd sizes + if (w%2==1) + w+=1; + if (h%2==1) + h+=1; + + IndexType index; + SizeType size; + m_OldDisplayExtent=m_DisplayExtent; + index[0]=0; + index[1]=0; + size[0]=w; + size[1]=h; + + m_DisplayExtent.SetIndex(index); + m_DisplayExtent.SetSize(size); + + this->Fl_Gl_Window::resize(x,y,w,h); + this->redraw(); +} +/** + * Set view mode to RGB. + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::SetViewModelToRGB(void) +{ + m_ViewModelIsRGB=true; +} +/** + * Set view mode to Grayscale. + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::SetViewModelToGrayscale(void) +{ + m_ViewModelIsRGB=false; +} - /** - * Set view mode to RGB. - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::SetInsightViewModelToRGB(void) +/** + * Set view mode to RGB. + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::SetInsightViewModelToRGB(void) +{ + m_InsightViewModelIsRGB=true; +} +/** + * Set view mode to Grayscale. + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::SetInsightViewModelToGrayscale(void) +{ + m_InsightViewModelIsRGB=false; +} + +/** + * Show The widget. + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::Show(void) +{ + if (!m_Image) { - m_InsightViewModelIsRGB=true; + itkExceptionMacro(<<"No input image !"); } - /** - * Set view mode to Grayscale. - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::SetInsightViewModelToGrayscale(void) + else { - m_InsightViewModelIsRGB=false; + this->show(); + this->redraw(); } +} - /** - * Show The widget. - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::Show(void) +/** + * Draw the widget + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::draw(void) +{ + if (!m_Updating) { - if(!m_Image) - { - itkExceptionMacro(<<"No input image !"); - } - else - { - this->show(); - this->redraw(); - } - } + m_Updating = true; + IncrementalOpenGlBufferUpdate(); + ResetOpenGlContext(); + this->Draw(m_OpenGlBuffer,m_BufferedRegion); - /** - * Draw the widget - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::draw(void) - { - if(!m_Updating) - { - m_Updating = true; - IncrementalOpenGlBufferUpdate(); - ResetOpenGlContext(); - this->Draw(m_OpenGlBuffer,m_BufferedRegion); - - if(!m_Drag) - { - AdditionalRedraw(); - } - m_Updating = false; - } + if (!m_Drag) + { + AdditionalRedraw(); + } + m_Updating = false; } +} - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::AdditionalRedraw(void) - { - std::vector<unsigned char *> bufferList; - std::vector<RegionType> bufferRegionList; +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::AdditionalRedraw(void) +{ + std::vector<unsigned char *> bufferList; + std::vector<RegionType> bufferRegionList; - if(m_BufferedRegion!=m_DisplayExtent) - { - for(unsigned int i = 0;i<8;++i) - { - RegionType additionalBufferRegion = GetAdditionalBufferRegion(i); - unsigned char * additionalBuffer = CreateAdditionalBuffer(additionalBufferRegion,m_Image,m_ViewModelIsRGB); - this->Draw(additionalBuffer,additionalBufferRegion); - bufferList.push_back(additionalBuffer); - bufferRegionList.push_back(additionalBufferRegion); - } - DecorationRedraw(); - MergeBuffersAndFreeMemory(bufferList,bufferRegionList); - } - if(m_SubWindowMode) - { - unsigned char * subWindowBuffer = CreateAdditionalBuffer(m_SubWindowRegion,m_SecondImage,m_InsightViewModelIsRGB); - this->Draw(subWindowBuffer,m_SubWindowRegion); - delete [] subWindowBuffer; - } + if (m_BufferedRegion!=m_DisplayExtent) + { + for (unsigned int i = 0;i<8;++i) + { + RegionType additionalBufferRegion = GetAdditionalBufferRegion(i); + unsigned char * additionalBuffer = CreateAdditionalBuffer(additionalBufferRegion,m_Image,m_ViewModelIsRGB); + this->Draw(additionalBuffer,additionalBufferRegion); + bufferList.push_back(additionalBuffer); + bufferRegionList.push_back(additionalBufferRegion); + } DecorationRedraw(); + MergeBuffersAndFreeMemory(bufferList,bufferRegionList); } - - - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::DecorationRedraw(void) + if (m_SubWindowMode) { - if(m_SubWindowMode) - { - this->DrawRegionBoundary(m_SubWindowRegion); - } - swap_buffers(); - glFlush(); + unsigned char * subWindowBuffer = CreateAdditionalBuffer(m_SubWindowRegion,m_SecondImage,m_InsightViewModelIsRGB); + this->Draw(subWindowBuffer,m_SubWindowRegion); + delete [] subWindowBuffer; } + DecorationRedraw(); +} - template <class TPixel> - long - ImageAlternateViewer<TPixel> - ::IndexInOldGrid(PointType point, PointType oldUpperLeft, SpacingType spacing, SizeType size) - { - long resp; - double x = (point[0]-oldUpperLeft[0])/spacing[0]; - double y = (point[1]-oldUpperLeft[1])/spacing[1]; - if ((vcl_floor(x)!=x)||(vcl_floor(y)!=y)) - { - resp=-1; - } - else if(x<0||x>size[0]||y<0||y>size[1]) - { - resp = -1; - } - else - { - resp = 3*(static_cast<long>(y)*size[0]+static_cast<long>(x)); - } - - return resp; +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::DecorationRedraw(void) +{ + if (m_SubWindowMode) + { + this->DrawRegionBoundary(m_SubWindowRegion); } + swap_buffers(); + glFlush(); +} +template <class TPixel> +long +ImageAlternateViewer<TPixel> +::IndexInOldGrid(PointType point, PointType oldUpperLeft, SpacingType spacing, SizeType size) +{ + long resp; + double x = (point[0]-oldUpperLeft[0])/spacing[0]; + double y = (point[1]-oldUpperLeft[1])/spacing[1]; - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::IncrementalOpenGlBufferUpdate() + if ((vcl_floor(x)!=x)||(vcl_floor(y)!=y)) { - IndexType focusOffset; - focusOffset[0]=static_cast<long>(static_cast<double>(m_ViewedRegionCenter[0]-m_OldViewedRegionCenter[0])/m_SpacingZoomFactor); - focusOffset[1]=static_cast<long>(static_cast<double>(m_ViewedRegionCenter[1]-m_OldViewedRegionCenter[1])/m_SpacingZoomFactor); - - IndexType newBufferedRegionIndex; - - SizeType newBufferedRegionSize; - - newBufferedRegionSize[0]=static_cast<unsigned long>(static_cast<double>((m_BufferedRegion.GetSize()[0])*m_OldSpacingZoomFactor/m_SpacingZoomFactor)); - newBufferedRegionSize[1]=static_cast<unsigned long>(static_cast<double>((m_BufferedRegion.GetSize()[1])*m_OldSpacingZoomFactor/m_SpacingZoomFactor)); - - m_OldBufferedRegion = m_BufferedRegion; - - m_BufferedRegion.SetSize(newBufferedRegionSize); - - newBufferedRegionIndex[0]=(static_cast<long>(m_DisplayExtent.GetSize()[0]) - -static_cast<long>(m_BufferedRegion.GetSize()[0]))/2; - newBufferedRegionIndex[1]=(static_cast<long>(m_DisplayExtent.GetSize()[1]) - -static_cast<long>(m_BufferedRegion.GetSize()[1]))/2; - newBufferedRegionIndex[0]-=focusOffset[0]; - newBufferedRegionIndex[1]-=focusOffset[1]; - m_BufferedRegion.SetIndex(newBufferedRegionIndex); - - PointType center; - m_Image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); - - if(m_SpacingZoomFactor != m_OldSpacingZoomFactor) - { - m_BufferedRegion.Crop(m_DisplayExtent); - - SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; - SpacingType oldSpacing = m_Image->GetSpacing()*m_OldSpacingZoomFactor; - - PointType origin; - origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; - origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; - - PointType oldOrigin; - oldOrigin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*oldSpacing[0]; - oldOrigin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*oldSpacing[1]; - - PointType oldBufferedUpperLeft; - oldBufferedUpperLeft[0]=oldOrigin[0]+static_cast<double>(m_OldBufferedRegion.GetIndex()[0])*oldSpacing[0]; - oldBufferedUpperLeft[1]=oldOrigin[1]+static_cast<double>(m_OldBufferedRegion.GetIndex()[1])*oldSpacing[1]; - - PointType bufferedUpperLeft; - bufferedUpperLeft[0]=origin[0]+static_cast<double>(m_BufferedRegion.GetIndex()[0])*spacing[0]; - bufferedUpperLeft[1]=origin[1]+static_cast<double>(m_BufferedRegion.GetIndex()[1])*spacing[1]; - - unsigned char * newBuffer = NULL; - unsigned int bufferLenght = 3*m_BufferedRegion.GetSize()[0]*m_BufferedRegion.GetSize()[1]; - - newBuffer = new unsigned char[bufferLenght]; - typename ImageListType::Pointer bandList; - unsigned int index = 0; - PixelType interpolatedValue = 0; - PointType interpolatedPos; - interpolatedPos.Fill(0); - unsigned int numberOfSplits=1; - - unsigned int optiCount = 0; - InterpolatorPointerType interpolator; - if(m_SpacingZoomFactor>1) - { - numberOfSplits=max((static_cast<unsigned int>(m_SpacingZoomFactor))*(static_cast<unsigned int>(m_SpacingZoomFactor)),1U); - interpolator = m_ZoomOutInterpolator; - } - else - { - interpolator = m_ZoomInInterpolator; - } - - unsigned int splitterNumberOfSplits = m_Splitter->GetNumberOfSplits(m_BufferedRegion,numberOfSplits); - - for(unsigned int splitIndex = 0;splitIndex<splitterNumberOfSplits;++splitIndex) - { - RegionType splitRegion = m_Splitter->GetSplit(splitIndex,splitterNumberOfSplits,m_BufferedRegion); - m_RequestedRegion = ComputeRequestedRegion(splitRegion); - if(! m_RequestedRegion.Crop(m_Image->GetLargestPossibleRegion())) - { - SizeType nullSize; - nullSize.Fill(0); - IndexType nullIndex; - nullIndex.Fill(0); - m_RequestedRegion.SetSize(nullSize); - m_RequestedRegion.SetIndex(nullIndex); - } - m_DecompositionFilter = VectorImageDecompositionFilterType::New(); - m_DecompositionFilter->SetInput(m_Image); - bandList = m_DecompositionFilter->GetOutput(); - bandList->UpdateOutputInformation(); - bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); - if(m_ViewModelIsRGB) - { - bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); - bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); - } - bandList->PropagateRequestedRegion(); - bandList->UpdateOutputData(); - - - PointType upperLeft; - upperLeft[0]=origin[0]+static_cast<double>(splitRegion.GetIndex()[0])*spacing[0]; - upperLeft[1]=origin[1]+static_cast<double>(splitRegion.GetIndex()[1])*spacing[1]; - - - interpolatedPos[1]=upperLeft[1]; - for(unsigned int j = 0;j<splitRegion.GetSize()[1];++j) - { - interpolatedPos[0]=upperLeft[0]; - for(unsigned int i = 0;i<splitRegion.GetSize()[0];++i) - { - - long indexInOldBuffer = IndexInOldGrid(interpolatedPos,oldBufferedUpperLeft,oldSpacing,m_OldBufferedRegion.GetSize()); - if(indexInOldBuffer>0) - { - newBuffer[index] = m_OpenGlBuffer[indexInOldBuffer]; - newBuffer[index+1] = m_OpenGlBuffer[indexInOldBuffer+1]; - newBuffer[index+2] = m_OpenGlBuffer[indexInOldBuffer+2]; - index+=3; - optiCount++; - } - else - { - interpolator->SetInputImage(bandList->GetNthElement(m_RedChannelIndex)); - if(interpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>(m_ZoomInInterpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - newBuffer[index] = Normalize(interpolatedValue,m_RedChannelIndex); - if(m_ViewModelIsRGB) - { - m_ZoomInInterpolator->SetInputImage(bandList->GetNthElement(m_GreenChannelIndex)); - if( m_ZoomInInterpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - newBuffer[index+1] = Normalize(interpolatedValue,m_GreenChannelIndex); - interpolator->SetInputImage(bandList->GetNthElement(m_BlueChannelIndex)); - if( interpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - newBuffer[index+2] = Normalize(interpolatedValue,m_BlueChannelIndex); - index+=3; - } - else - { - newBuffer[index+1] = Normalize(interpolatedValue,m_RedChannelIndex); - newBuffer[index+2] = Normalize(interpolatedValue,m_RedChannelIndex); - index+=3; - } - } - interpolatedPos[0] +=spacing[0]; - } - interpolatedPos[1] +=spacing[1]; - } - } - if(m_OpenGlBuffer!=NULL) - { - delete [] m_OpenGlBuffer; - } - m_OpenGlBuffer = newBuffer; - - m_OldSpacingZoomFactor = m_SpacingZoomFactor; + resp=-1; } -} - - template <class TPixel> - typename ImageAlternateViewer<TPixel> - ::RegionType - ImageAlternateViewer<TPixel> - ::GetAdditionalBufferRegion(unsigned int part) + else if (x<0||x>size[0]||y<0||y>size[1]) { - RegionType region; - SizeType size; - IndexType index; - - size.Fill(0); - index.Fill(0); - - SizeType deSize = m_DisplayExtent.GetSize(); - IndexType deUL =m_DisplayExtent.GetIndex(); - IndexType deLR; - deLR[0] = deSize[0] + deUL[0]; - deLR[1] = deSize[1] + deUL[1]; - - SizeType bufSize = m_BufferedRegion.GetSize(); - IndexType bufUL = m_BufferedRegion.GetIndex(); - IndexType bufLR; - bufLR[0] = bufUL[0] + bufSize[0]; - bufLR[1] = bufUL[1] + bufSize[1]; - - switch(part) - { - case 0: - index = deUL; - size[0] = max(bufUL[0]-deUL[0],0L); - size[1] = max(bufUL[1]-deUL[1],0L); - break; - - case 1: - index[0] = max(deUL[0],bufUL[0]); - index[1] = deUL[1]; - size[0] = min(bufLR[0]-max(bufUL[0],0L),deLR[0]-index[0]); - size[1] = max(bufUL[1]-deUL[1],0L); - break; - - case 2: - index[0] = min(bufLR[0],deLR[0]); - index[1] = deUL[1]; - size[0] = max(deLR[0]-bufLR[0],0L); - size[1] = max(bufUL[1]-deUL[1],0L); - break; - - case 3: - index[0] = deUL[0]; - index[1] = max(bufUL[1],0L); - size[0] = max(bufUL[0]-deUL[0],0L); - size[1] = min(bufLR[1]-max(bufUL[1],0L),deLR[1]-index[1]); - break; - - case 4: - index[0] = min(bufLR[0],deLR[0]); - index[1] = max(bufUL[1],deUL[0]); - size[0] = max(deLR[0]-bufLR[0],0L); - size[1] = min(bufLR[1]-max(bufUL[1],0L),deLR[1]-index[1]); - break; - - case 5: - index[0] = deUL[0]; - index[1] = min(deLR[1],bufLR[1]); - size[0] = max(bufUL[0]-deUL[0],0L); - size[1] = max(deLR[1]-bufLR[1],0L); - break; - - case 6: - index[0] = max(deUL[0],bufUL[0]); - index[1] = min(deLR[1],bufLR[1]); - size[0] = min(bufLR[0]-max(bufUL[0],0L),deLR[0]-index[0]); - size[1] = max(deLR[1]-bufLR[1],0L); - break; - - case 7: - index[0] = min(bufLR[0],deLR[0]); - index[1] = min(deLR[1],bufLR[1]); - size[0] = max(deLR[0]-bufLR[0],0L); - size[1] = max(deLR[1]-bufLR[1],0L); - } - region.SetSize(size); - region.SetIndex(index); - return region; + resp = -1; } - - template <class TPixel> - typename ImageAlternateViewer<TPixel> - ::RegionType - ImageAlternateViewer<TPixel> - ::ComputeRequestedRegion(RegionType ®ion) + else { - RegionType outputRegion; - - SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; + resp = 3*(static_cast<long>(y)*size[0]+static_cast<long>(x)); + } - PointType center; - m_Image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); - PointType origin; - origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; - origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; + return resp; +} - PointType oldOrigin; - oldOrigin[0]=center[0]-(static_cast<double>(this->m_OldDisplayExtent.GetSize()[0])/2-1)*spacing[0]; - oldOrigin[1]=center[1]-(static_cast<double>(this->m_OldDisplayExtent.GetSize()[1])/2-1)*spacing[1]; - PointType upperLeft; - upperLeft[0]=origin[0]+(static_cast<double>(region.GetIndex()[0]))*spacing[0]; - upperLeft[1]=origin[1]+(static_cast<double>(region.GetIndex()[1]))*spacing[1]; +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::IncrementalOpenGlBufferUpdate() +{ + IndexType focusOffset; + focusOffset[0]=static_cast<long>(static_cast<double>(m_ViewedRegionCenter[0]-m_OldViewedRegionCenter[0])/m_SpacingZoomFactor); + focusOffset[1]=static_cast<long>(static_cast<double>(m_ViewedRegionCenter[1]-m_OldViewedRegionCenter[1])/m_SpacingZoomFactor); - PointType lowerRight; - lowerRight[0]=upperLeft[0]+(static_cast<double>(region.GetSize()[0])-1)*spacing[0]; - lowerRight[1]=upperLeft[1]+(static_cast<double>(region.GetSize()[1])-1)*spacing[1]; + IndexType newBufferedRegionIndex; + SizeType newBufferedRegionSize; - PointType bufferedUpperLeft; - bufferedUpperLeft[0]=origin[0]+static_cast<double>(m_BufferedRegion.GetIndex()[0])*spacing[0]; - bufferedUpperLeft[1]=origin[1]+static_cast<double>(m_BufferedRegion.GetIndex()[1])*spacing[1]; + newBufferedRegionSize[0]=static_cast<unsigned long>(static_cast<double>((m_BufferedRegion.GetSize()[0])*m_OldSpacingZoomFactor/m_SpacingZoomFactor)); + newBufferedRegionSize[1]=static_cast<unsigned long>(static_cast<double>((m_BufferedRegion.GetSize()[1])*m_OldSpacingZoomFactor/m_SpacingZoomFactor)); - PointType bufferedLowerRight; - bufferedLowerRight[0]=bufferedUpperLeft[0]+static_cast<double>(m_BufferedRegion.GetSize()[0]-1)*spacing[0]; - bufferedLowerRight[1]=bufferedUpperLeft[1]+static_cast<double>(m_BufferedRegion.GetSize()[1]-1)*spacing[1]; + m_OldBufferedRegion = m_BufferedRegion; - IndexType lowerRightIndex; - IndexType requestedIndex; - SizeType requestedSize; - m_Image->TransformPhysicalPointToIndex(upperLeft,requestedIndex); - m_Image->TransformPhysicalPointToIndex(lowerRight,lowerRightIndex); - requestedSize[0]=lowerRightIndex[0]-requestedIndex[0]+1; - requestedSize[1]=lowerRightIndex[1]-requestedIndex[1]+1; + m_BufferedRegion.SetSize(newBufferedRegionSize); - outputRegion.SetIndex(requestedIndex); - outputRegion.SetSize(requestedSize); - outputRegion.PadByRadius(2); + newBufferedRegionIndex[0]=(static_cast<long>(m_DisplayExtent.GetSize()[0]) + -static_cast<long>(m_BufferedRegion.GetSize()[0]))/2; + newBufferedRegionIndex[1]=(static_cast<long>(m_DisplayExtent.GetSize()[1]) + -static_cast<long>(m_BufferedRegion.GetSize()[1]))/2; + newBufferedRegionIndex[0]-=focusOffset[0]; + newBufferedRegionIndex[1]-=focusOffset[1]; + m_BufferedRegion.SetIndex(newBufferedRegionIndex); - return outputRegion; + PointType center; + m_Image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); - } + if (m_SpacingZoomFactor != m_OldSpacingZoomFactor) + { + m_BufferedRegion.Crop(m_DisplayExtent); + SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; + SpacingType oldSpacing = m_Image->GetSpacing()*m_OldSpacingZoomFactor; - template <class TPixel> - unsigned char * - ImageAlternateViewer<TPixel> - ::CreateAdditionalBuffer(RegionType region,ImagePointerType image, bool rgb) - { - itk::TimeProbe total,filter,interpolation; - total.Start(); - unsigned char * result = NULL; + PointType origin; + origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; + origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; - unsigned int bufferLenght = 3*region.GetSize()[0]*region.GetSize()[1]; + PointType oldOrigin; + oldOrigin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*oldSpacing[0]; + oldOrigin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*oldSpacing[1]; - if(bufferLenght == 0) - { - return result; - } + PointType oldBufferedUpperLeft; + oldBufferedUpperLeft[0]=oldOrigin[0]+static_cast<double>(m_OldBufferedRegion.GetIndex()[0])*oldSpacing[0]; + oldBufferedUpperLeft[1]=oldOrigin[1]+static_cast<double>(m_OldBufferedRegion.GetIndex()[1])*oldSpacing[1]; - result = new unsigned char[bufferLenght]; + PointType bufferedUpperLeft; + bufferedUpperLeft[0]=origin[0]+static_cast<double>(m_BufferedRegion.GetIndex()[0])*spacing[0]; + bufferedUpperLeft[1]=origin[1]+static_cast<double>(m_BufferedRegion.GetIndex()[1])*spacing[1]; - filter.Start(); - typename ImageListType::Pointer bandList = m_DecompositionFilter->GetOutput(); - bandList->UpdateOutputInformation(); + unsigned char * newBuffer = NULL; + unsigned int bufferLenght = 3*m_BufferedRegion.GetSize()[0]*m_BufferedRegion.GetSize()[1]; + newBuffer = new unsigned char[bufferLenght]; + typename ImageListType::Pointer bandList; unsigned int index = 0; PixelType interpolatedValue = 0; PointType interpolatedPos; interpolatedPos.Fill(0); unsigned int numberOfSplits=1; + unsigned int optiCount = 0; InterpolatorPointerType interpolator; - if(m_SpacingZoomFactor>1) + if (m_SpacingZoomFactor>1) + { + numberOfSplits=max((static_cast<unsigned int>(m_SpacingZoomFactor))*(static_cast<unsigned int>(m_SpacingZoomFactor)),1U); + interpolator = m_ZoomOutInterpolator; + } + else + { + interpolator = m_ZoomInInterpolator; + } + + unsigned int splitterNumberOfSplits = m_Splitter->GetNumberOfSplits(m_BufferedRegion,numberOfSplits); + + for (unsigned int splitIndex = 0;splitIndex<splitterNumberOfSplits;++splitIndex) + { + RegionType splitRegion = m_Splitter->GetSplit(splitIndex,splitterNumberOfSplits,m_BufferedRegion); + m_RequestedRegion = ComputeRequestedRegion(splitRegion); + if (! m_RequestedRegion.Crop(m_Image->GetLargestPossibleRegion())) { - numberOfSplits=max((static_cast<unsigned int>(m_SpacingZoomFactor))*(static_cast<unsigned int>(m_SpacingZoomFactor)),1U); - interpolator = m_ZoomOutInterpolator; + SizeType nullSize; + nullSize.Fill(0); + IndexType nullIndex; + nullIndex.Fill(0); + m_RequestedRegion.SetSize(nullSize); + m_RequestedRegion.SetIndex(nullIndex); } - else + m_DecompositionFilter = VectorImageDecompositionFilterType::New(); + m_DecompositionFilter->SetInput(m_Image); + bandList = m_DecompositionFilter->GetOutput(); + bandList->UpdateOutputInformation(); + bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); + if (m_ViewModelIsRGB) { - interpolator = m_ZoomInInterpolator; + bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); + bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); } + bandList->PropagateRequestedRegion(); + bandList->UpdateOutputData(); - unsigned int splitterNumberOfSplits = m_Splitter->GetNumberOfSplits(region,numberOfSplits); - SpacingType spacing = image->GetSpacing()*m_SpacingZoomFactor; + PointType upperLeft; + upperLeft[0]=origin[0]+static_cast<double>(splitRegion.GetIndex()[0])*spacing[0]; + upperLeft[1]=origin[1]+static_cast<double>(splitRegion.GetIndex()[1])*spacing[1]; - PointType center; - image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); - PointType origin; - origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; - origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; - for(unsigned int splitIndex = 0;splitIndex<splitterNumberOfSplits;++splitIndex) + interpolatedPos[1]=upperLeft[1]; + for (unsigned int j = 0;j<splitRegion.GetSize()[1];++j) { - RegionType splitRegion = m_Splitter->GetSplit(splitIndex,splitterNumberOfSplits,region); - - PointType upperLeft; - upperLeft[0]=origin[0]+(static_cast<double>(splitRegion.GetIndex()[0]))*spacing[0]; - upperLeft[1]=origin[1]+(static_cast<double>(splitRegion.GetIndex()[1]))*spacing[1]; - m_RequestedRegion = ComputeRequestedRegion(splitRegion); - if(!m_RequestedRegion.Crop(image->GetLargestPossibleRegion())) - { - SizeType nullSize; - nullSize.Fill(0); - IndexType nullIndex; - nullIndex.Fill(0); - m_RequestedRegion.SetSize(nullSize); - m_RequestedRegion.SetIndex(nullIndex); - } - m_DecompositionFilter = VectorImageDecompositionFilterType::New(); - m_DecompositionFilter->SetInput(image); - bandList = m_DecompositionFilter->GetOutput(); - - bandList->UpdateOutputInformation(); - bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); - if(rgb) - { - bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); - bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); - } - bandList->PropagateRequestedRegion(); - bandList->UpdateOutputData(); - - filter.Stop(); - - interpolation.Start(); - interpolatedPos[1]=upperLeft[1]; - for(unsigned int j = 0;j<splitRegion.GetSize()[1];++j) - { - interpolatedPos[0]=upperLeft[0]; - for(unsigned int i = 0;i<splitRegion.GetSize()[0];++i) - { - interpolator->SetInputImage(bandList->GetNthElement(m_RedChannelIndex)); - if( interpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - result[index] = Normalize(interpolatedValue,m_RedChannelIndex); - if(rgb) - { - interpolator->SetInputImage(bandList->GetNthElement(m_GreenChannelIndex)); - if( interpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>( interpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - result[index+1] = Normalize(interpolatedValue,m_GreenChannelIndex); - interpolator->SetInputImage(bandList->GetNthElement(m_BlueChannelIndex)); - if( interpolator->IsInsideBuffer(interpolatedPos)) - { - interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); - } - else - { - interpolatedValue = 0; - } - result[index+2] = Normalize(interpolatedValue,m_BlueChannelIndex); - index+=3; - } - else - { - result[index+1] = Normalize(interpolatedValue,m_RedChannelIndex); - result[index+2] = Normalize(interpolatedValue,m_RedChannelIndex); - index+=3; - } - interpolatedPos[0] +=spacing[0]; - } - interpolatedPos[1] +=spacing[1]; - } + interpolatedPos[0]=upperLeft[0]; + for (unsigned int i = 0;i<splitRegion.GetSize()[0];++i) + { + + long indexInOldBuffer = IndexInOldGrid(interpolatedPos,oldBufferedUpperLeft,oldSpacing,m_OldBufferedRegion.GetSize()); + if (indexInOldBuffer>0) + { + newBuffer[index] = m_OpenGlBuffer[indexInOldBuffer]; + newBuffer[index+1] = m_OpenGlBuffer[indexInOldBuffer+1]; + newBuffer[index+2] = m_OpenGlBuffer[indexInOldBuffer+2]; + index+=3; + optiCount++; + } + else + { + interpolator->SetInputImage(bandList->GetNthElement(m_RedChannelIndex)); + if (interpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>(m_ZoomInInterpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + newBuffer[index] = Normalize(interpolatedValue,m_RedChannelIndex); + if (m_ViewModelIsRGB) + { + m_ZoomInInterpolator->SetInputImage(bandList->GetNthElement(m_GreenChannelIndex)); + if ( m_ZoomInInterpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + newBuffer[index+1] = Normalize(interpolatedValue,m_GreenChannelIndex); + interpolator->SetInputImage(bandList->GetNthElement(m_BlueChannelIndex)); + if ( interpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + newBuffer[index+2] = Normalize(interpolatedValue,m_BlueChannelIndex); + index+=3; + } + else + { + newBuffer[index+1] = Normalize(interpolatedValue,m_RedChannelIndex); + newBuffer[index+2] = Normalize(interpolatedValue,m_RedChannelIndex); + index+=3; + } + } + interpolatedPos[0] +=spacing[0]; + } + interpolatedPos[1] +=spacing[1]; } + } + if (m_OpenGlBuffer!=NULL) + { + delete [] m_OpenGlBuffer; + } + m_OpenGlBuffer = newBuffer; + + m_OldSpacingZoomFactor = m_SpacingZoomFactor; + } +} +template <class TPixel> +typename ImageAlternateViewer<TPixel> +::RegionType +ImageAlternateViewer<TPixel> +::GetAdditionalBufferRegion(unsigned int part) +{ + RegionType region; + SizeType size; + IndexType index; + + size.Fill(0); + index.Fill(0); + + SizeType deSize = m_DisplayExtent.GetSize(); + IndexType deUL =m_DisplayExtent.GetIndex(); + IndexType deLR; + deLR[0] = deSize[0] + deUL[0]; + deLR[1] = deSize[1] + deUL[1]; + + SizeType bufSize = m_BufferedRegion.GetSize(); + IndexType bufUL = m_BufferedRegion.GetIndex(); + IndexType bufLR; + bufLR[0] = bufUL[0] + bufSize[0]; + bufLR[1] = bufUL[1] + bufSize[1]; + + switch (part) + { + case 0: + index = deUL; + size[0] = max(bufUL[0]-deUL[0],0L); + size[1] = max(bufUL[1]-deUL[1],0L); + break; + + case 1: + index[0] = max(deUL[0],bufUL[0]); + index[1] = deUL[1]; + size[0] = min(bufLR[0]-max(bufUL[0],0L),deLR[0]-index[0]); + size[1] = max(bufUL[1]-deUL[1],0L); + break; + + case 2: + index[0] = min(bufLR[0],deLR[0]); + index[1] = deUL[1]; + size[0] = max(deLR[0]-bufLR[0],0L); + size[1] = max(bufUL[1]-deUL[1],0L); + break; + + case 3: + index[0] = deUL[0]; + index[1] = max(bufUL[1],0L); + size[0] = max(bufUL[0]-deUL[0],0L); + size[1] = min(bufLR[1]-max(bufUL[1],0L),deLR[1]-index[1]); + break; + + case 4: + index[0] = min(bufLR[0],deLR[0]); + index[1] = max(bufUL[1],deUL[0]); + size[0] = max(deLR[0]-bufLR[0],0L); + size[1] = min(bufLR[1]-max(bufUL[1],0L),deLR[1]-index[1]); + break; + + case 5: + index[0] = deUL[0]; + index[1] = min(deLR[1],bufLR[1]); + size[0] = max(bufUL[0]-deUL[0],0L); + size[1] = max(deLR[1]-bufLR[1],0L); + break; + + case 6: + index[0] = max(deUL[0],bufUL[0]); + index[1] = min(deLR[1],bufLR[1]); + size[0] = min(bufLR[0]-max(bufUL[0],0L),deLR[0]-index[0]); + size[1] = max(deLR[1]-bufLR[1],0L); + break; + + case 7: + index[0] = min(bufLR[0],deLR[0]); + index[1] = min(deLR[1],bufLR[1]); + size[0] = max(deLR[0]-bufLR[0],0L); + size[1] = max(deLR[1]-bufLR[1],0L); + } + region.SetSize(size); + region.SetIndex(index); + return region; +} + +template <class TPixel> +typename ImageAlternateViewer<TPixel> +::RegionType +ImageAlternateViewer<TPixel> +::ComputeRequestedRegion(RegionType ®ion) +{ + RegionType outputRegion; + + SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; + + PointType center; + m_Image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); + PointType origin; + origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; + origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; + + PointType oldOrigin; + oldOrigin[0]=center[0]-(static_cast<double>(this->m_OldDisplayExtent.GetSize()[0])/2-1)*spacing[0]; + oldOrigin[1]=center[1]-(static_cast<double>(this->m_OldDisplayExtent.GetSize()[1])/2-1)*spacing[1]; + + PointType upperLeft; + upperLeft[0]=origin[0]+(static_cast<double>(region.GetIndex()[0]))*spacing[0]; + upperLeft[1]=origin[1]+(static_cast<double>(region.GetIndex()[1]))*spacing[1]; + + PointType lowerRight; + lowerRight[0]=upperLeft[0]+(static_cast<double>(region.GetSize()[0])-1)*spacing[0]; + lowerRight[1]=upperLeft[1]+(static_cast<double>(region.GetSize()[1])-1)*spacing[1]; + PointType bufferedUpperLeft; + bufferedUpperLeft[0]=origin[0]+static_cast<double>(m_BufferedRegion.GetIndex()[0])*spacing[0]; + bufferedUpperLeft[1]=origin[1]+static_cast<double>(m_BufferedRegion.GetIndex()[1])*spacing[1]; + + PointType bufferedLowerRight; + bufferedLowerRight[0]=bufferedUpperLeft[0]+static_cast<double>(m_BufferedRegion.GetSize()[0]-1)*spacing[0]; + bufferedLowerRight[1]=bufferedUpperLeft[1]+static_cast<double>(m_BufferedRegion.GetSize()[1]-1)*spacing[1]; + + IndexType lowerRightIndex; + IndexType requestedIndex; + SizeType requestedSize; + m_Image->TransformPhysicalPointToIndex(upperLeft,requestedIndex); + m_Image->TransformPhysicalPointToIndex(lowerRight,lowerRightIndex); + requestedSize[0]=lowerRightIndex[0]-requestedIndex[0]+1; + requestedSize[1]=lowerRightIndex[1]-requestedIndex[1]+1; + + outputRegion.SetIndex(requestedIndex); + outputRegion.SetSize(requestedSize); + outputRegion.PadByRadius(2); + + return outputRegion; + +} + + +template <class TPixel> +unsigned char * +ImageAlternateViewer<TPixel> +::CreateAdditionalBuffer(RegionType region,ImagePointerType image, bool rgb) +{ + itk::TimeProbe total,filter,interpolation; + total.Start(); + unsigned char * result = NULL; + + unsigned int bufferLenght = 3*region.GetSize()[0]*region.GetSize()[1]; - interpolation.Stop(); - total.Stop(); + if (bufferLenght == 0) + { return result; } - template <class TPixel> - int - ImageAlternateViewer<TPixel> - ::handle(int event) + result = new unsigned char[bufferLenght]; + + filter.Start(); + typename ImageListType::Pointer bandList = m_DecompositionFilter->GetOutput(); + bandList->UpdateOutputInformation(); + + unsigned int index = 0; + PixelType interpolatedValue = 0; + PointType interpolatedPos; + interpolatedPos.Fill(0); + unsigned int numberOfSplits=1; + + InterpolatorPointerType interpolator; + if (m_SpacingZoomFactor>1) + { + numberOfSplits=max((static_cast<unsigned int>(m_SpacingZoomFactor))*(static_cast<unsigned int>(m_SpacingZoomFactor)),1U); + interpolator = m_ZoomOutInterpolator; + } + else { - if(m_Updating) - return 0; - switch(event) + interpolator = m_ZoomInInterpolator; + } + + unsigned int splitterNumberOfSplits = m_Splitter->GetNumberOfSplits(region,numberOfSplits); + + SpacingType spacing = image->GetSpacing()*m_SpacingZoomFactor; + + PointType center; + image->TransformIndexToPhysicalPoint(m_ViewedRegionCenter,center); + PointType origin; + origin[0]=center[0]-(static_cast<double>(this->m_DisplayExtent.GetSize()[0])/2-1)*spacing[0]; + origin[1]=center[1]-(static_cast<double>(this->m_DisplayExtent.GetSize()[1])/2-1)*spacing[1]; + + for (unsigned int splitIndex = 0;splitIndex<splitterNumberOfSplits;++splitIndex) + { + RegionType splitRegion = m_Splitter->GetSplit(splitIndex,splitterNumberOfSplits,region); + + PointType upperLeft; + upperLeft[0]=origin[0]+(static_cast<double>(splitRegion.GetIndex()[0]))*spacing[0]; + upperLeft[1]=origin[1]+(static_cast<double>(splitRegion.GetIndex()[1]))*spacing[1]; + m_RequestedRegion = ComputeRequestedRegion(splitRegion); + if (!m_RequestedRegion.Crop(image->GetLargestPossibleRegion())) + { + SizeType nullSize; + nullSize.Fill(0); + IndexType nullIndex; + nullIndex.Fill(0); + m_RequestedRegion.SetSize(nullSize); + m_RequestedRegion.SetIndex(nullIndex); + } + m_DecompositionFilter = VectorImageDecompositionFilterType::New(); + m_DecompositionFilter->SetInput(image); + bandList = m_DecompositionFilter->GetOutput(); + + bandList->UpdateOutputInformation(); + bandList->GetNthElement(m_RedChannelIndex)->SetRequestedRegion(m_RequestedRegion); + if (rgb) + { + bandList->GetNthElement(m_GreenChannelIndex)->SetRequestedRegion(m_RequestedRegion); + bandList->GetNthElement(m_BlueChannelIndex)->SetRequestedRegion(m_RequestedRegion); + } + bandList->PropagateRequestedRegion(); + bandList->UpdateOutputData(); + + filter.Stop(); + + interpolation.Start(); + interpolatedPos[1]=upperLeft[1]; + for (unsigned int j = 0;j<splitRegion.GetSize()[1];++j) + { + interpolatedPos[0]=upperLeft[0]; + for (unsigned int i = 0;i<splitRegion.GetSize()[0];++i) { - case FL_PUSH: - { - if(!m_Drag) - { - m_OldMousePos[0]= static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[0]/2) - +(static_cast<double>(Fl::event_x())-static_cast<double>(m_DisplayExtent.GetSize()[0]/2))/m_OpenGlIsotropicZoom); - m_OldMousePos[1]= static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[1]/2) - +(static_cast<double>(Fl::event_y())-static_cast<double>(m_DisplayExtent.GetSize()[1]/2))/m_OpenGlIsotropicZoom); - m_Drag=true; - m_DragEventCounter=0; - - if(m_SubWindowRegion.IsInside(m_OldMousePos)) - { - m_SubWindowMove = true; - } - else - { - m_OldViewedRegionCenter = m_ViewedRegionCenter; - } - } - return 1; - } - - case FL_DRAG: - { - m_Drag=true; - - int x =static_cast<int>(static_cast<double>(m_DisplayExtent.GetSize()[0]/2) - +(Fl::event_x()-static_cast<double>(m_DisplayExtent.GetSize()[0]/2))/m_OpenGlIsotropicZoom); - int y = static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[1]/2) - +(Fl::event_y()-static_cast<double>(m_DisplayExtent.GetSize()[1]/2))/m_OpenGlIsotropicZoom); - if(Fl::event_button()==FL_MIDDLE_MOUSE) - { - if(!m_SubWindowMode) - m_SubWindowMode = true; - IndexType newIndex; - SizeType newSize; - - newIndex[0]=(x>m_OldMousePos[0] ? m_OldMousePos[0] : x); - newIndex[1]=(y>m_OldMousePos[1] ? m_OldMousePos[1] : y); - newSize[0]=vcl_abs(x-m_OldMousePos[0]); - newSize[1]=vcl_abs(y-m_OldMousePos[1]); - m_SubWindowRegion.SetIndex(newIndex); - m_SubWindowRegion.SetSize(newSize); - this->redraw(); - m_DragEventCounter++; - } - else if(m_SubWindowMove) - { - IndexType index = m_SubWindowRegion.GetIndex(); - index[0]+=(x-m_OldMousePos[0]); - index[1]+=(y-m_OldMousePos[1]); - m_SubWindowRegion.SetIndex(index); - m_OldMousePos[0]=x; - m_OldMousePos[1]=y; - this->redraw(); - m_DragEventCounter++; - } - - else - { - SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; - PointType origin; - origin[0]=static_cast<double>(m_OldViewedRegionCenter[0])-static_cast<double>(this->m_DisplayExtent.GetSize()[0]/2)*spacing[0]; - origin[1]=static_cast<double>(m_OldViewedRegionCenter[1])-static_cast<double>(this->m_DisplayExtent.GetSize()[1]/2)*spacing[1]; - PointType newCenter; - newCenter[0]=origin[0]+static_cast<double>(m_OldMousePos[0]-x+static_cast<long>(this->m_DisplayExtent.GetSize()[0])/2)*spacing[0]; - newCenter[1]=origin[1]+static_cast<double>(m_OldMousePos[1]-y+static_cast<long>(this->m_DisplayExtent.GetSize()[1])/2)*spacing[1]; - m_Image->TransformPhysicalPointToIndex(newCenter,m_ViewedRegionCenter); - this->redraw(); - m_DragEventCounter++; - } - - DecorationRedraw(); - return 1; - } - - case FL_RELEASE: - { - m_OldViewedRegionCenter = m_ViewedRegionCenter; - m_Drag=false; - AdditionalRedraw(); - m_SubWindowMove = false; - return 1; - } - case FL_FOCUS: - { - return 1; - } - case FL_UNFOCUS: - { - return 1; - } - case FL_KEYDOWN: - { - if(Fl::event_key()==116) // T key - { - m_SubWindowMode = !m_SubWindowMode; - this->redraw(); - } - return 1; - } + interpolator->SetInputImage(bandList->GetNthElement(m_RedChannelIndex)); + if ( interpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + result[index] = Normalize(interpolatedValue,m_RedChannelIndex); + if (rgb) + { + interpolator->SetInputImage(bandList->GetNthElement(m_GreenChannelIndex)); + if ( interpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>( interpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + result[index+1] = Normalize(interpolatedValue,m_GreenChannelIndex); + interpolator->SetInputImage(bandList->GetNthElement(m_BlueChannelIndex)); + if ( interpolator->IsInsideBuffer(interpolatedPos)) + { + interpolatedValue = static_cast<PixelType>(interpolator->Evaluate(interpolatedPos)); + } + else + { + interpolatedValue = 0; + } + result[index+2] = Normalize(interpolatedValue,m_BlueChannelIndex); + index+=3; + } + else + { + result[index+1] = Normalize(interpolatedValue,m_RedChannelIndex); + result[index+2] = Normalize(interpolatedValue,m_RedChannelIndex); + index+=3; + } + interpolatedPos[0] +=spacing[0]; } - return 0; + interpolatedPos[1] +=spacing[1]; + } } - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::MergeBuffersAndFreeMemory(std::vector<unsigned char *> bufferList, std::vector<RegionType> bufferRegionList) + + + + interpolation.Stop(); + total.Stop(); + return result; +} + +template <class TPixel> +int +ImageAlternateViewer<TPixel> +::handle(int event) +{ + if (m_Updating) + return 0; + switch (event) { - if(bufferList.size()!=8 || bufferRegionList.size()!=8) + case FL_PUSH: + { + if (!m_Drag) + { + m_OldMousePos[0]= static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[0]/2) + +(static_cast<double>(Fl::event_x())-static_cast<double>(m_DisplayExtent.GetSize()[0]/2))/m_OpenGlIsotropicZoom); + m_OldMousePos[1]= static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[1]/2) + +(static_cast<double>(Fl::event_y())-static_cast<double>(m_DisplayExtent.GetSize()[1]/2))/m_OpenGlIsotropicZoom); + m_Drag=true; + m_DragEventCounter=0; + + if (m_SubWindowRegion.IsInside(m_OldMousePos)) { - itkExceptionMacro("Invalid number of additionnal buffers"); + m_SubWindowMove = true; } - - if(bufferRegionList[0].GetNumberOfPixels()==0 - &&bufferRegionList[1].GetNumberOfPixels()==0 - &&bufferRegionList[2].GetNumberOfPixels()==0 - &&bufferRegionList[3].GetNumberOfPixels()==0 - &&bufferRegionList[4].GetNumberOfPixels()==0 - &&bufferRegionList[5].GetNumberOfPixels()==0 - &&bufferRegionList[6].GetNumberOfPixels()==0 - &&bufferRegionList[7].GetNumberOfPixels()==0) + else { - return; + m_OldViewedRegionCenter = m_ViewedRegionCenter; } + } + return 1; + } + + case FL_DRAG: + { + m_Drag=true; + int x =static_cast<int>(static_cast<double>(m_DisplayExtent.GetSize()[0]/2) + +(Fl::event_x()-static_cast<double>(m_DisplayExtent.GetSize()[0]/2))/m_OpenGlIsotropicZoom); + int y = static_cast<long int>(static_cast<double>(m_DisplayExtent.GetSize()[1]/2) + +(Fl::event_y()-static_cast<double>(m_DisplayExtent.GetSize()[1]/2))/m_OpenGlIsotropicZoom); + if (Fl::event_button()==FL_MIDDLE_MOUSE) + { + if (!m_SubWindowMode) + m_SubWindowMode = true; + IndexType newIndex; + SizeType newSize; + + newIndex[0]=(x>m_OldMousePos[0] ? m_OldMousePos[0] : x); + newIndex[1]=(y>m_OldMousePos[1] ? m_OldMousePos[1] : y); + newSize[0]=vcl_abs(x-m_OldMousePos[0]); + newSize[1]=vcl_abs(y-m_OldMousePos[1]); + m_SubWindowRegion.SetIndex(newIndex); + m_SubWindowRegion.SetSize(newSize); + this->redraw(); + m_DragEventCounter++; + } + else if (m_SubWindowMove) + { + IndexType index = m_SubWindowRegion.GetIndex(); + index[0]+=(x-m_OldMousePos[0]); + index[1]+=(y-m_OldMousePos[1]); + m_SubWindowRegion.SetIndex(index); + m_OldMousePos[0]=x; + m_OldMousePos[1]=y; + this->redraw(); + m_DragEventCounter++; + } - // malloc new buffer - unsigned char * newBuffer = new unsigned char[3*m_DisplayExtent.GetNumberOfPixels()]; + else + { + SpacingType spacing = m_Image->GetSpacing()*m_SpacingZoomFactor; + PointType origin; + origin[0]=static_cast<double>(m_OldViewedRegionCenter[0])-static_cast<double>(this->m_DisplayExtent.GetSize()[0]/2)*spacing[0]; + origin[1]=static_cast<double>(m_OldViewedRegionCenter[1])-static_cast<double>(this->m_DisplayExtent.GetSize()[1]/2)*spacing[1]; + PointType newCenter; + newCenter[0]=origin[0]+static_cast<double>(m_OldMousePos[0]-x+static_cast<long>(this->m_DisplayExtent.GetSize()[0])/2)*spacing[0]; + newCenter[1]=origin[1]+static_cast<double>(m_OldMousePos[1]-y+static_cast<long>(this->m_DisplayExtent.GetSize()[1])/2)*spacing[1]; + m_Image->TransformPhysicalPointToIndex(newCenter,m_ViewedRegionCenter); + this->redraw(); + m_DragEventCounter++; + } - // fill the new buffer - unsigned int indexInNewBuffer = 0; + DecorationRedraw(); + return 1; + } + case FL_RELEASE: + { + m_OldViewedRegionCenter = m_ViewedRegionCenter; + m_Drag=false; + AdditionalRedraw(); + m_SubWindowMove = false; + return 1; + } + case FL_FOCUS: + { + return 1; + } + case FL_UNFOCUS: + { + return 1; + } + case FL_KEYDOWN: + { + if (Fl::event_key()==116) // T key + { + m_SubWindowMode = !m_SubWindowMode; + this->redraw(); + } + return 1; + } + } + return 0; +} - unsigned int indexInBuffer1=0; - unsigned int indexInBuffer2=0; - unsigned int indexInBuffer3=0; - unsigned int indexInBuffer4=0; - unsigned int indexInBuffer5=0; - unsigned int indexInBuffer6=0; - unsigned int indexInBuffer7=0; - unsigned int indexInBuffer8=0; - unsigned int indexInCentralBuffer = 0; +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::MergeBuffersAndFreeMemory(std::vector<unsigned char *> bufferList, std::vector<RegionType> bufferRegionList) +{ + if (bufferList.size()!=8 || bufferRegionList.size()!=8) + { + itkExceptionMacro("Invalid number of additionnal buffers"); + } - if(bufferRegionList[0].GetSize()[1]!=bufferRegionList[1].GetSize()[1] - ||bufferRegionList[2].GetSize()[1]!=bufferRegionList[1].GetSize()[1] - ||bufferRegionList[2].GetSize()[1]!=bufferRegionList[0].GetSize()[1] - ||bufferRegionList[0].GetIndex()[1]!=bufferRegionList[1].GetIndex()[1] - ||bufferRegionList[2].GetIndex()[1]!=bufferRegionList[1].GetIndex()[1] - ||bufferRegionList[2].GetIndex()[1]!=bufferRegionList[0].GetIndex()[1] - ) - { - itkExceptionMacro("Additional buffers misaligned."); - } + if (bufferRegionList[0].GetNumberOfPixels()==0 + &&bufferRegionList[1].GetNumberOfPixels()==0 + &&bufferRegionList[2].GetNumberOfPixels()==0 + &&bufferRegionList[3].GetNumberOfPixels()==0 + &&bufferRegionList[4].GetNumberOfPixels()==0 + &&bufferRegionList[5].GetNumberOfPixels()==0 + &&bufferRegionList[6].GetNumberOfPixels()==0 + &&bufferRegionList[7].GetNumberOfPixels()==0) + { + return; + } - // Fill region 1 + // malloc new buffer + unsigned char * newBuffer = new unsigned char[3*m_DisplayExtent.GetNumberOfPixels()]; - for(unsigned int j = 0;j<bufferRegionList[0].GetSize()[1];++j) - { - if(bufferList[0]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[0].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[0][indexInBuffer1]; - ++indexInNewBuffer; - ++indexInBuffer1; - } - } - // Fill region 2 - if(bufferList[1]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[1].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[1][indexInBuffer2]; - ++indexInNewBuffer; - ++indexInBuffer2; - } - } - // Fill region 3 - if(bufferList[2]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[2].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[2][indexInBuffer3]; - ++indexInNewBuffer; - ++indexInBuffer3; - } - } - } + // fill the new buffer + unsigned int indexInNewBuffer = 0; - unsigned int lineOffset = static_cast<unsigned int>(-min(0L,m_BufferedRegion.GetIndex()[0])); - unsigned int lineOffsetEnd = static_cast<unsigned int>(-min(0L,static_cast<long>(m_DisplayExtent.GetSize()[0])-m_BufferedRegion.GetIndex()[0]-static_cast<long>(m_BufferedRegion.GetSize()[0]))); - unsigned int columnOffset = static_cast<unsigned int>(-min(0L,m_BufferedRegion.GetIndex()[1])); - unsigned int offsety= columnOffset*(static_cast<int>(m_BufferedRegion.GetSize()[0]))*3; - unsigned int offsetx = lineOffset*3; - indexInCentralBuffer+=offsety; + unsigned int indexInBuffer1=0; + unsigned int indexInBuffer2=0; + unsigned int indexInBuffer3=0; + unsigned int indexInBuffer4=0; + unsigned int indexInBuffer5=0; + unsigned int indexInBuffer6=0; + unsigned int indexInBuffer7=0; + unsigned int indexInBuffer8=0; + unsigned int indexInCentralBuffer = 0; - // For each line - for(unsigned int j = 0;j<bufferRegionList[3].GetSize()[1];++j) - { - //Fill line from region 4 - if(bufferList[3]!=NULL) - { - for(unsigned int i = 0;i<3*bufferRegionList[3].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[3][indexInBuffer4]; - ++indexInNewBuffer; - ++indexInBuffer4; - } - } - // Fill line from central region - if(m_OpenGlBuffer!=NULL) - { - - indexInCentralBuffer+=offsetx; - for(unsigned int i = 0;i<3*bufferRegionList[1].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=m_OpenGlBuffer[indexInCentralBuffer]; - ++indexInNewBuffer; - ++indexInCentralBuffer; - } - indexInCentralBuffer+=lineOffsetEnd*3; - } - // Fill line from region 5 - if(bufferList[4]!=NULL) - { - for(unsigned int i = 0;i<3*bufferRegionList[4].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[4][indexInBuffer5]; - ++indexInNewBuffer; - ++indexInBuffer5; - } - } - } + if (bufferRegionList[0].GetSize()[1]!=bufferRegionList[1].GetSize()[1] + ||bufferRegionList[2].GetSize()[1]!=bufferRegionList[1].GetSize()[1] + ||bufferRegionList[2].GetSize()[1]!=bufferRegionList[0].GetSize()[1] + ||bufferRegionList[0].GetIndex()[1]!=bufferRegionList[1].GetIndex()[1] + ||bufferRegionList[2].GetIndex()[1]!=bufferRegionList[1].GetIndex()[1] + ||bufferRegionList[2].GetIndex()[1]!=bufferRegionList[0].GetIndex()[1] + ) + { + itkExceptionMacro("Additional buffers misaligned."); + } + // Fill region 1 - if(bufferRegionList[5].GetSize()[1]!=bufferRegionList[6].GetSize()[1] - ||bufferRegionList[6].GetSize()[1]!=bufferRegionList[7].GetSize()[1] - ||bufferRegionList[7].GetSize()[1]!=bufferRegionList[5].GetSize()[1] - ||bufferRegionList[5].GetIndex()[1]!=bufferRegionList[6].GetIndex()[1] - ||bufferRegionList[6].GetIndex()[1]!=bufferRegionList[7].GetIndex()[1] - ||bufferRegionList[7].GetIndex()[1]!=bufferRegionList[5].GetIndex()[1] - ) + for (unsigned int j = 0;j<bufferRegionList[0].GetSize()[1];++j) + { + if (bufferList[0]!=NULL) + { + for (unsigned int i = 0; i<3*bufferRegionList[0].GetSize()[0];++i) + { + newBuffer[indexInNewBuffer]=bufferList[0][indexInBuffer1]; + ++indexInNewBuffer; + ++indexInBuffer1; + } + } + // Fill region 2 + if (bufferList[1]!=NULL) + { + for (unsigned int i = 0; i<3*bufferRegionList[1].GetSize()[0];++i) + { + newBuffer[indexInNewBuffer]=bufferList[1][indexInBuffer2]; + ++indexInNewBuffer; + ++indexInBuffer2; + } + } + // Fill region 3 + if (bufferList[2]!=NULL) + { + for (unsigned int i = 0; i<3*bufferRegionList[2].GetSize()[0];++i) { - itkExceptionMacro("Additional buffers misaligned."); + newBuffer[indexInNewBuffer]=bufferList[2][indexInBuffer3]; + ++indexInNewBuffer; + ++indexInBuffer3; } + } + } + unsigned int lineOffset = static_cast<unsigned int>(-min(0L,m_BufferedRegion.GetIndex()[0])); + unsigned int lineOffsetEnd = static_cast<unsigned int>(-min(0L,static_cast<long>(m_DisplayExtent.GetSize()[0])-m_BufferedRegion.GetIndex()[0]-static_cast<long>(m_BufferedRegion.GetSize()[0]))); + unsigned int columnOffset = static_cast<unsigned int>(-min(0L,m_BufferedRegion.GetIndex()[1])); + unsigned int offsety= columnOffset*(static_cast<int>(m_BufferedRegion.GetSize()[0]))*3; + unsigned int offsetx = lineOffset*3; - // Fill region 6 + indexInCentralBuffer+=offsety; - for(unsigned int j = 0;j<bufferRegionList[5].GetSize()[1];++j) + // For each line + for (unsigned int j = 0;j<bufferRegionList[3].GetSize()[1];++j) + { + //Fill line from region 4 + if (bufferList[3]!=NULL) + { + for (unsigned int i = 0;i<3*bufferRegionList[3].GetSize()[0];++i) { - if(bufferList[5]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[5].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[5][indexInBuffer6]; - ++indexInNewBuffer; - ++indexInBuffer6; - } - } - // Fill region 2 - if(bufferList[6]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[6].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[6][indexInBuffer7]; - ++indexInNewBuffer; - ++indexInBuffer7; - } - } - // Fill region 3 - if(bufferList[7]!=NULL) - { - for(unsigned int i = 0; i<3*bufferRegionList[7].GetSize()[0];++i) - { - newBuffer[indexInNewBuffer]=bufferList[7][indexInBuffer8]; - ++indexInNewBuffer; - ++indexInBuffer8; - } - } + newBuffer[indexInNewBuffer]=bufferList[3][indexInBuffer4]; + ++indexInNewBuffer; + ++indexInBuffer4; } + } + // Fill line from central region + if (m_OpenGlBuffer!=NULL) + { - // Free all intermediate buffers - typename std::vector<unsigned char *>::iterator it; - for(it=bufferList.begin();it!=bufferList.end();++it) + indexInCentralBuffer+=offsetx; + for (unsigned int i = 0;i<3*bufferRegionList[1].GetSize()[0];++i) { - if((*it)!=NULL) - { - delete [] (*it); - }; + newBuffer[indexInNewBuffer]=m_OpenGlBuffer[indexInCentralBuffer]; + ++indexInNewBuffer; + ++indexInCentralBuffer; } - - // update buffered region - m_OldBufferedRegion = m_BufferedRegion; - m_BufferedRegion=m_DisplayExtent; - // delete previous buffer - if (m_OpenGlBuffer!=NULL) + indexInCentralBuffer+=lineOffsetEnd*3; + } + // Fill line from region 5 + if (bufferList[4]!=NULL) + { + for (unsigned int i = 0;i<3*bufferRegionList[4].GetSize()[0];++i) { - delete [] m_OpenGlBuffer; + newBuffer[indexInNewBuffer]=bufferList[4][indexInBuffer5]; + ++indexInNewBuffer; + ++indexInBuffer5; } - // replace by current buffer - m_OpenGlBuffer = newBuffer; + } + } + - //std::cout<<"Buffers merged and freed"<<std::endl; + if (bufferRegionList[5].GetSize()[1]!=bufferRegionList[6].GetSize()[1] + ||bufferRegionList[6].GetSize()[1]!=bufferRegionList[7].GetSize()[1] + ||bufferRegionList[7].GetSize()[1]!=bufferRegionList[5].GetSize()[1] + ||bufferRegionList[5].GetIndex()[1]!=bufferRegionList[6].GetIndex()[1] + ||bufferRegionList[6].GetIndex()[1]!=bufferRegionList[7].GetIndex()[1] + ||bufferRegionList[7].GetIndex()[1]!=bufferRegionList[5].GetIndex()[1] + ) + { + itkExceptionMacro("Additional buffers misaligned."); } - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::Draw(unsigned char * buffer, RegionType& region) + + // Fill region 6 + + for (unsigned int j = 0;j<bufferRegionList[5].GetSize()[1];++j) { - itk::TimeProbe total; - total.Start(); - if(buffer!=NULL) + if (bufferList[5]!=NULL) { - // This enable negative raster pos - glRasterPos3d(0,0,0); - - double zoomOffsetX = 0; - double zoomOffsetY = 0; - - zoomOffsetX = (1-m_OpenGlIsotropicZoom)*(static_cast<double>(m_DisplayExtent.GetSize()[0]/2)-static_cast<double>(region.GetIndex()[0])); - zoomOffsetY = (1-m_OpenGlIsotropicZoom)*( static_cast<double>(m_DisplayExtent.GetSize()[1]/2)-static_cast<double>(region.GetIndex()[1])); - - double movex = static_cast<double>(region.GetIndex()[0])+zoomOffsetX; - double movey = static_cast<double>(m_DisplayExtent.GetSize()[1])-static_cast<double>(region.GetIndex()[1])-zoomOffsetY; - glBitmap(0,0,0,0,movex,movey,NULL); - glPixelZoom(m_OpenGlIsotropicZoom,-m_OpenGlIsotropicZoom); - - - // display the image - glDrawPixels(region.GetSize()[0], - region.GetSize()[1], - GL_RGB, - GL_UNSIGNED_BYTE, - buffer); - glEnd(); - swap_buffers(); - glFlush(); + for (unsigned int i = 0; i<3*bufferRegionList[5].GetSize()[0];++i) + { + newBuffer[indexInNewBuffer]=bufferList[5][indexInBuffer6]; + ++indexInNewBuffer; + ++indexInBuffer6; + } + } + // Fill region 2 + if (bufferList[6]!=NULL) + { + for (unsigned int i = 0; i<3*bufferRegionList[6].GetSize()[0];++i) + { + newBuffer[indexInNewBuffer]=bufferList[6][indexInBuffer7]; + ++indexInNewBuffer; + ++indexInBuffer7; + } + } + // Fill region 3 + if (bufferList[7]!=NULL) + { + for (unsigned int i = 0; i<3*bufferRegionList[7].GetSize()[0];++i) + { + newBuffer[indexInNewBuffer]=bufferList[7][indexInBuffer8]; + ++indexInNewBuffer; + ++indexInBuffer8; + } } - total.Stop(); } + // Free all intermediate buffers + typename std::vector<unsigned char *>::iterator it; + for (it=bufferList.begin();it!=bufferList.end();++it) + { + if ((*it)!=NULL) + { + delete [] (*it); + }; + } + + // update buffered region + m_OldBufferedRegion = m_BufferedRegion; + m_BufferedRegion=m_DisplayExtent; + // delete previous buffer + if (m_OpenGlBuffer!=NULL) + { + delete [] m_OpenGlBuffer; + } + // replace by current buffer + m_OpenGlBuffer = newBuffer; - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::DrawRegionBoundary(RegionType& region) + + //std::cout<<"Buffers merged and freed"<<std::endl; +} + +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::Draw(unsigned char * buffer, RegionType& region) +{ + itk::TimeProbe total; + total.Start(); + if (buffer!=NULL) { + // This enable negative raster pos + glRasterPos3d(0,0,0); + double zoomOffsetX = 0; double zoomOffsetY = 0; zoomOffsetX = (1-m_OpenGlIsotropicZoom)*(static_cast<double>(m_DisplayExtent.GetSize()[0]/2)-static_cast<double>(region.GetIndex()[0])); zoomOffsetY = (1-m_OpenGlIsotropicZoom)*( static_cast<double>(m_DisplayExtent.GetSize()[1]/2)-static_cast<double>(region.GetIndex()[1])); - double minx,maxx,miny,maxy; - - minx = static_cast<double>(region.GetIndex()[0])/**m_OpenGlIsotropicZoom*/+zoomOffsetX; - maxx = minx + static_cast<double>(region.GetSize()[0])*m_OpenGlIsotropicZoom; - miny = static_cast<double>(m_DisplayExtent.GetSize()[1])-static_cast<double>(region.GetIndex()[1])/**m_OpenGlIsotropicZoom*/-zoomOffsetY; - maxy = miny-static_cast<double>(region.GetSize()[1])*m_OpenGlIsotropicZoom; - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor3f(1,0,0); - glBegin(GL_LINE_LOOP); - glVertex2f(minx,miny); - glVertex2f(minx,maxy); - glVertex2f(maxx,maxy); - glVertex2f(maxx,miny); - glEnd(); - glDisable(GL_BLEND); + double movex = static_cast<double>(region.GetIndex()[0])+zoomOffsetX; + double movey = static_cast<double>(m_DisplayExtent.GetSize()[1])-static_cast<double>(region.GetIndex()[1])-zoomOffsetY; + glBitmap(0,0,0,0,movex,movey,NULL); + glPixelZoom(m_OpenGlIsotropicZoom,-m_OpenGlIsotropicZoom); + + + // display the image + glDrawPixels(region.GetSize()[0], + region.GetSize()[1], + GL_RGB, + GL_UNSIGNED_BYTE, + buffer); + glEnd(); + swap_buffers(); + glFlush(); } - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::ResetOpenGlContext(void) - { - if (!this->valid()) - { - valid(1); - glLoadIdentity(); - glViewport(0,0,m_DisplayExtent.GetSize()[0],m_DisplayExtent.GetSize()[1]); - glClearColor((float)0.0, (float)0.0, (float)0.0, (float)0.0); - glShadeModel(GL_SMOOTH); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - } + total.Stop(); +} - glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black - glMatrixMode(GL_PROJECTION); - this->ortho(); - glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params - glLoadIdentity(); - glDisable(GL_BLEND); +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::DrawRegionBoundary(RegionType& region) +{ + double zoomOffsetX = 0; + double zoomOffsetY = 0; + + zoomOffsetX = (1-m_OpenGlIsotropicZoom)*(static_cast<double>(m_DisplayExtent.GetSize()[0]/2)-static_cast<double>(region.GetIndex()[0])); + zoomOffsetY = (1-m_OpenGlIsotropicZoom)*( static_cast<double>(m_DisplayExtent.GetSize()[1]/2)-static_cast<double>(region.GetIndex()[1])); + double minx,maxx,miny,maxy; + + minx = static_cast<double>(region.GetIndex()[0])/**m_OpenGlIsotropicZoom*/+zoomOffsetX; + maxx = minx + static_cast<double>(region.GetSize()[0])*m_OpenGlIsotropicZoom; + miny = static_cast<double>(m_DisplayExtent.GetSize()[1])-static_cast<double>(region.GetIndex()[1])/**m_OpenGlIsotropicZoom*/-zoomOffsetY; + maxy = miny-static_cast<double>(region.GetSize()[1])*m_OpenGlIsotropicZoom; + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor3f(1,0,0); + glBegin(GL_LINE_LOOP); + glVertex2f(minx,miny); + glVertex2f(minx,maxy); + glVertex2f(maxx,maxy); + glVertex2f(maxx,miny); + glEnd(); + glDisable(GL_BLEND); + +} +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::ResetOpenGlContext(void) +{ + if (!this->valid()) + { + valid(1); + glLoadIdentity(); + glViewport(0,0,m_DisplayExtent.GetSize()[0],m_DisplayExtent.GetSize()[1]); + glClearColor((float)0.0, (float)0.0, (float)0.0, (float)0.0); glShadeModel(GL_SMOOTH); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } + glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black + glMatrixMode(GL_PROJECTION); + this->ortho(); + glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params + glLoadIdentity(); + glDisable(GL_BLEND); + + glShadeModel(GL_SMOOTH); +} - template <class TPixel> - unsigned char - ImageAlternateViewer<TPixel> - ::Normalize(PixelType value, unsigned int channelIndex) + +template <class TPixel> +unsigned char +ImageAlternateViewer<TPixel> +::Normalize(PixelType value, unsigned int channelIndex) +{ + PixelType max = 255; + PixelType min = 0; + if (channelIndex<m_MaxComponentValues.GetSize()) { - PixelType max = 255; - PixelType min = 0; - if(channelIndex<m_MaxComponentValues.GetSize()) - { - max = m_MaxComponentValues[channelIndex]; - } - if(channelIndex<m_MinComponentValues.GetSize()) - { - min = m_MinComponentValues[channelIndex]; - } - if(value>=max) - { - return 255; - } + max = m_MaxComponentValues[channelIndex]; + } + if (channelIndex<m_MinComponentValues.GetSize()) + { + min = m_MinComponentValues[channelIndex]; + } + if (value>=max) + { + return 255; + } - else if(value<=min) - { - return 0; - } - else - { - return static_cast<unsigned char>(255.*static_cast<double>(value-min) - /static_cast<double>(max-min)); - } + else if (value<=min) + { + return 0; } - /** - * PrintSelf Method - */ - template <class TPixel> - void - ImageAlternateViewer<TPixel> - ::PrintSelf(std::ostream& os, itk::Indent indent) const + else { - Superclass::PrintSelf(os, indent); + return static_cast<unsigned char>(255.*static_cast<double>(value-min) + /static_cast<double>(max-min)); } +} +/** + * PrintSelf Method + */ +template <class TPixel> +void +ImageAlternateViewer<TPixel> +::PrintSelf(std::ostream& os, itk::Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} } // End namespace otb #endif diff --git a/Code/Visu/otbImageToGrayscaleAnaglyphImageFilter.h b/Code/Visu/otbImageToGrayscaleAnaglyphImageFilter.h index 6e5e381e260074f7f9ce14c4ff922df15015b156..72a7433dd31fce077330d057cec70ee84060921a 100644 --- a/Code/Visu/otbImageToGrayscaleAnaglyphImageFilter.h +++ b/Code/Visu/otbImageToGrayscaleAnaglyphImageFilter.h @@ -24,61 +24,61 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class GrayscaleAnaglyphFunctor - * \brief This functor implements the pixel-wise grayscale anaglyph composition. - * The output pixel is a vector pixel of size 3, where the first component contains the - * value of the first input pixel, and the two last components contain the value of the - * second input pixel. - */ - template <class TInputPixel1,class TInputPixel2,class TOutputPixel> - class GrayscaleAnaglyphFunctor - { - public: +{ +/** \class GrayscaleAnaglyphFunctor + * \brief This functor implements the pixel-wise grayscale anaglyph composition. + * The output pixel is a vector pixel of size 3, where the first component contains the + * value of the first input pixel, and the two last components contain the value of the + * second input pixel. + */ +template <class TInputPixel1,class TInputPixel2,class TOutputPixel> +class GrayscaleAnaglyphFunctor +{ +public: /// Constructor - GrayscaleAnaglyphFunctor(){}; + GrayscaleAnaglyphFunctor() {}; /// Destructor - ~GrayscaleAnaglyphFunctor(){}; + ~GrayscaleAnaglyphFunctor() {}; inline TOutputPixel operator()(const TInputPixel1& pixel1, const TInputPixel2& pixel2) - { - TOutputPixel result(3); - result[0]=static_cast<typename TOutputPixel::ValueType>(pixel1); - result[1]=static_cast<typename TOutputPixel::ValueType>(pixel2); - result[2]=static_cast<typename TOutputPixel::ValueType>(pixel2); - return result; - } - }; + { + TOutputPixel result(3); + result[0]=static_cast<typename TOutputPixel::ValueType>(pixel1); + result[1]=static_cast<typename TOutputPixel::ValueType>(pixel2); + result[2]=static_cast<typename TOutputPixel::ValueType>(pixel2); + return result; } - /** \class ImageToGrayscaleAnaglyphImageFilter - * \brief This filter implements the synthesis of a grayscale anaglyph image from - * a pair of stereoscopic images. - * The output image is a VectorImage with 3 channels, where the first channel is the first - * input image, and the two last channels are the second input image. - * \note TOutputImage is supposed to be of type VectorImage. - */ +}; +} +/** \class ImageToGrayscaleAnaglyphImageFilter + * \brief This filter implements the synthesis of a grayscale anaglyph image from + * a pair of stereoscopic images. + * The output image is a VectorImage with 3 channels, where the first channel is the first + * input image, and the two last channels are the second input image. + * \note TOutputImage is supposed to be of type VectorImage. + */ template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT ImageToGrayscaleAnaglyphImageFilter - : public itk::BinaryFunctorImageFilter - < TInputImage1,TInputImage2,TOutputImage, - Functor::GrayscaleAnaglyphFunctor< - typename TInputImage1::PixelType, - typename TInputImage2::PixelType, - typename TOutputImage::PixelType - > > - { - public: + : public itk::BinaryFunctorImageFilter + < TInputImage1,TInputImage2,TOutputImage, + Functor::GrayscaleAnaglyphFunctor< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType + > > +{ +public: /** Standard typedefs */ typedef ImageToGrayscaleAnaglyphImageFilter Self; typedef itk::BinaryFunctorImageFilter < TInputImage1,TInputImage2,TOutputImage, - Functor::GrayscaleAnaglyphFunctor< - typename TInputImage1::PixelType, - typename TInputImage2::PixelType, - typename TOutputImage::PixelType - > > Superclass; + Functor::GrayscaleAnaglyphFunctor< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType + > > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -89,20 +89,20 @@ class ITK_EXPORT ImageToGrayscaleAnaglyphImageFilter itkTypeMacro(ImageToGrayscaleAnaglyphImageFilter, BinaryFunctorImageFilter); virtual void GenerateOutputInformation(void) - { - Superclass::GenerateOutputInformation(); - this->GetOutput()->SetNumberOfComponentsPerPixel(3); - } + { + Superclass::GenerateOutputInformation(); + this->GetOutput()->SetNumberOfComponentsPerPixel(3); + } protected: /** Constructor */ - ImageToGrayscaleAnaglyphImageFilter(){}; + ImageToGrayscaleAnaglyphImageFilter() {}; /** Destructor */ virtual ~ImageToGrayscaleAnaglyphImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: ImageToGrayscaleAnaglyphImageFilter(const Self&); //purposely not implemented diff --git a/Code/Visu/otbImageViewer.h b/Code/Visu/otbImageViewer.h index dd08948bfa6bfba251adac1dffae4c55fe82549f..3dbba8c5ef5759fb8a3cd2621a3a0d404acb9c8b 100644 --- a/Code/Visu/otbImageViewer.h +++ b/Code/Visu/otbImageViewer.h @@ -23,43 +23,43 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * \class ImageViewer - * - * \brief Simple image viewer. - * - * This class is a simple image viewer using fltk gui and opengl drawing. - * It is divided into four parts : - * - The full window that display a part of the image at full resolution, - * - If necessary, a scroll window to allow the user to navigate through the whole image, - * - A zoom window whose zoom can be adjusted with mouse scroll, - * - a Pixel/value window to display information about the pointed pixel. - * - * The viewer uses the StreamingShrinkImageFilter to generate a quicklook of possibly very large image - * without flooding the memory. - * - * Channel index and other various parameters can be set. - * - * To use the viewer, setup it with all your parameters, then call the Build(), Show() and the Update() methods. - * A call to Fl::run() is mandatory to hang the program execution until the viewer is closed. - * - * Unkike most OTB filters, ImageViewer is templated over the input pixel type and will take as input an otb::VectorImage<PixelType>. - * Be aware of that. - * - * \sa ImageViewerFullWidget, ImageViewerScrollWidget, ImageViewerZoomWidget - */ +/** + * \class ImageViewer + * + * \brief Simple image viewer. + * + * This class is a simple image viewer using fltk gui and opengl drawing. + * It is divided into four parts : + * - The full window that display a part of the image at full resolution, + * - If necessary, a scroll window to allow the user to navigate through the whole image, + * - A zoom window whose zoom can be adjusted with mouse scroll, + * - a Pixel/value window to display information about the pointed pixel. + * + * The viewer uses the StreamingShrinkImageFilter to generate a quicklook of possibly very large image + * without flooding the memory. + * + * Channel index and other various parameters can be set. + * + * To use the viewer, setup it with all your parameters, then call the Build(), Show() and the Update() methods. + * A call to Fl::run() is mandatory to hang the program execution until the viewer is closed. + * + * Unkike most OTB filters, ImageViewer is templated over the input pixel type and will take as input an otb::VectorImage<PixelType>. + * Be aware of that. + * + * \sa ImageViewerFullWidget, ImageViewerScrollWidget, ImageViewerZoomWidget + */ template <class TPixel, class TLabel = double> class ITK_EXPORT ImageViewer - : public ImageViewerBase<TPixel,TLabel> + : public ImageViewerBase<TPixel,TLabel> { - public: +public: /** Standard class typedefs */ typedef ImageViewer Self; typedef ImageViewerBase<TPixel,TLabel> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - typedef typename Superclass::ViewModelType ViewModelType; + typedef typename Superclass::ViewModelType ViewModelType; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -68,20 +68,20 @@ class ITK_EXPORT ImageViewer /** Show the viewer */ virtual void Show(void); - /** Hide all Image View Windows */ + /** Hide all Image View Windows */ virtual void Hide(void); /** Build the interfaces */ virtual void Build(void); /** Update */ virtual void Update(void); - protected: +protected: /**Constructor */ ImageViewer(); /** Destructor */ ~ImageViewer(); - private: +private: ImageViewer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/Visu/otbImageViewer.txx b/Code/Visu/otbImageViewer.txx index 7a4b8228f5bd902d3048b26af3943f9863b26f9c..cb26c72f13852b3bf6825f98d7b575dedf4ac79d 100644 --- a/Code/Visu/otbImageViewer.txx +++ b/Code/Visu/otbImageViewer.txx @@ -21,75 +21,75 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /// Constructor - template <class TPixel, class TLabel> - ImageViewer<TPixel,TLabel> - ::ImageViewer() - { - m_FullWindow=NULL; - m_ZoomWindow=NULL; - m_ScrollWindow=NULL; - m_HistogramWindow=NULL; - m_PixLocWindow=NULL; - m_PixLocOutput=NULL; - } - /// Destructor - template <class TPixel, class TLabel> - ImageViewer<TPixel,TLabel> - ::~ImageViewer() +/// Constructor +template <class TPixel, class TLabel> +ImageViewer<TPixel,TLabel> +::ImageViewer() +{ + m_FullWindow=NULL; + m_ZoomWindow=NULL; + m_ScrollWindow=NULL; + m_HistogramWindow=NULL; + m_PixLocWindow=NULL; + m_PixLocOutput=NULL; +} +/// Destructor +template <class TPixel, class TLabel> +ImageViewer<TPixel,TLabel> +::~ImageViewer() +{ + if (m_HistogramWindow!=NULL) { - if(m_HistogramWindow!=NULL) - { - m_HistogramWindow->remove(this->GetRedHistogramWidget()); - if(this->GetFullWidget()->GetViewModel() == Superclass::ScrollWidgetType::RGB) + m_HistogramWindow->remove(this->GetRedHistogramWidget()); + if (this->GetFullWidget()->GetViewModel() == Superclass::ScrollWidgetType::RGB) { m_HistogramWindow->remove(this->GetGreenHistogramWidget()); m_HistogramWindow->remove(this->GetBlueHistogramWidget()); } - delete m_HistogramWindow; - m_HistogramWindow = NULL; - } - - if (m_FullWindow!=NULL) - { - m_FullWindow->remove(this->GetFullWidget()); - delete m_FullWindow; - m_FullWindow = NULL; - } - if(m_ZoomWindow!=NULL) - { - m_ZoomWindow->remove(this->GetZoomWidget()); - delete m_ZoomWindow; - m_ZoomWindow = NULL; - } - if(m_ScrollWindow!=NULL) - { - m_ScrollWindow->remove(this->GetScrollWidget()); - delete m_ScrollWindow; - m_ScrollWindow = NULL; - } - - if(m_PixLocWindow!=NULL) - { - m_PixLocWindow->remove(m_PixLocOutput); - delete m_PixLocWindow; - m_PixLocWindow = NULL; - } - if(m_PixLocOutput!=NULL) - { - delete m_PixLocOutput; - m_PixLocOutput = NULL; - } + delete m_HistogramWindow; + m_HistogramWindow = NULL; + } + + if (m_FullWindow!=NULL) + { + m_FullWindow->remove(this->GetFullWidget()); + delete m_FullWindow; + m_FullWindow = NULL; + } + if (m_ZoomWindow!=NULL) + { + m_ZoomWindow->remove(this->GetZoomWidget()); + delete m_ZoomWindow; + m_ZoomWindow = NULL; + } + if (m_ScrollWindow!=NULL) + { + m_ScrollWindow->remove(this->GetScrollWidget()); + delete m_ScrollWindow; + m_ScrollWindow = NULL; } - /// Build the HMI - template <class TPixel, class TLabel> - void - ImageViewer<TPixel,TLabel> - ::Build(void) + if (m_PixLocWindow!=NULL) { - Superclass::Build(); - itk::OStringStream oss; + m_PixLocWindow->remove(m_PixLocOutput); + delete m_PixLocWindow; + m_PixLocWindow = NULL; + } + if (m_PixLocOutput!=NULL) + { + delete m_PixLocOutput; + m_PixLocOutput = NULL; + } +} + +/// Build the HMI +template <class TPixel, class TLabel> +void +ImageViewer<TPixel,TLabel> +::Build(void) +{ + Superclass::Build(); + itk::OStringStream oss; int wfull = this->GetFullWidget()->w(); int hfull = this->GetFullWidget()->h(); @@ -105,20 +105,20 @@ namespace otb oss.str(""); oss<<this->GetLabel()<<" - Histograms and transfer functions"; - if(this->GetViewModel() == Superclass::ScrollWidgetType::RGB) + if (this->GetViewModel() == Superclass::ScrollWidgetType::RGB) { m_HistogramWindow = new Fl_Window(0,hfull,3*this->GetRedHistogramWidget()->w(),this->GetRedHistogramWidget()->h()); m_HistogramWindow->add(this->GetRedHistogramWidget()); m_HistogramWindow->add(this->GetGreenHistogramWidget()); m_HistogramWindow->add(this->GetBlueHistogramWidget()); this->GetGreenHistogramWidget()->resize(this->GetRedHistogramWidget()->w(), - 0, - this->GetGreenHistogramWidget()->w(), - this->GetGreenHistogramWidget()->h()); + 0, + this->GetGreenHistogramWidget()->w(), + this->GetGreenHistogramWidget()->h()); this->GetBlueHistogramWidget()->resize(2*this->GetRedHistogramWidget()->w(), - 0, - this->GetBlueHistogramWidget()->w(), - this->GetBlueHistogramWidget()->h()); + 0, + this->GetBlueHistogramWidget()->w(), + this->GetBlueHistogramWidget()->h()); m_HistogramWindow->resizable(m_HistogramWindow); m_HistogramWindow->end(); @@ -136,7 +136,7 @@ namespace otb int hscroll = 0; int wscroll = 0; - if(this->GetUseScroll()) + if (this->GetUseScroll()) { // Create the scroll windows @@ -171,7 +171,7 @@ namespace otb m_PixLocOutput->box(FL_EMBOSSED_BOX ); m_PixLocWindow->end(); this->SetPixLocOutput(m_PixLocOutput); - } +} /// Show the app template <class TPixel, class TLabel> @@ -179,14 +179,14 @@ void ImageViewer<TPixel,TLabel> ::Show(void) { - if(!this->GetBuilt()) - { - this->Build(); - } - if(this->GetUseScroll()) - { - m_ScrollWindow->show(); - } + if (!this->GetBuilt()) + { + this->Build(); + } + if (this->GetUseScroll()) + { + m_ScrollWindow->show(); + } m_FullWindow->show(); m_ZoomWindow->show(); m_PixLocWindow->show(); @@ -203,10 +203,10 @@ ImageViewer<TPixel,TLabel> ::Hide(void) { Superclass::Hide(); - if(this->GetUseScroll()) - { - m_ScrollWindow->hide(); - } + if (this->GetUseScroll()) + { + m_ScrollWindow->hide(); + } m_FullWindow->hide(); m_ZoomWindow->hide(); m_PixLocWindow->hide(); @@ -222,10 +222,10 @@ ImageViewer<TPixel,TLabel> { itk::OStringStream oss; oss<<this->GetLabel()<<" - Zoom Window (X"<<this->GetZoomWidget()->GetOpenGlIsotropicZoom()<<")"; - if(oss.good()) - { - m_ZoomWindow->copy_label(oss.str().c_str()); - } + if (oss.good()) + { + m_ZoomWindow->copy_label(oss.str().c_str()); + } m_ZoomWindow->redraw(); Superclass::Update(); } diff --git a/Code/Visu/otbImageViewerBase.h b/Code/Visu/otbImageViewerBase.h index 13b941bee422011c3ffba6d437d3fed71bc1d11f..7758d0fe5932cb60fc16b9f01d74b97e4b379fb9 100644 --- a/Code/Visu/otbImageViewerBase.h +++ b/Code/Visu/otbImageViewerBase.h @@ -42,481 +42,481 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** \class ImageViewerBase - * \brief Simple image viewer base class. - * - * This class is a simple image viewer using fltk gui and opengl drawing. - * It is divided into four parts : - * - The full window that display a part of the image at full resolution, - * - If necessary, a scroll window to allow the user to navigate through the whole image, - * - A zoom window whose zoom can be adjusted with mouse scroll, - * - a Pixel/value window to display information about the pointed pixel. - * - * The viewer uses the StreamingShrinkImageFilter to generate a quicklook of possibly very large image - * without flooding the memory. - * - * Channel index and other various parameters can be set. - * - * To use the viewer, setup it with all your parameters, then call the Build(), Show() and the Update() methods. - * A call to Fl::run() is mandatory to hang the program execution until the viewer is closed. - * - * Unkike most OTB filters, ImageViewerBase is templated over the input pixel type and will take as input an otb::VectorImage<PixelType>. - * Be aware of that. - * - * \sa ImageViewerFullWidget, ImageViewerScrollWidget, ImageViewerZoomWidget +/** \class ImageViewerBase + * \brief Simple image viewer base class. + * + * This class is a simple image viewer using fltk gui and opengl drawing. + * It is divided into four parts : + * - The full window that display a part of the image at full resolution, + * - If necessary, a scroll window to allow the user to navigate through the whole image, + * - A zoom window whose zoom can be adjusted with mouse scroll, + * - a Pixel/value window to display information about the pointed pixel. + * + * The viewer uses the StreamingShrinkImageFilter to generate a quicklook of possibly very large image + * without flooding the memory. + * + * Channel index and other various parameters can be set. + * + * To use the viewer, setup it with all your parameters, then call the Build(), Show() and the Update() methods. + * A call to Fl::run() is mandatory to hang the program execution until the viewer is closed. + * + * Unkike most OTB filters, ImageViewerBase is templated over the input pixel type and will take as input an otb::VectorImage<PixelType>. + * Be aware of that. + * + * \sa ImageViewerFullWidget, ImageViewerScrollWidget, ImageViewerZoomWidget + */ +template <class TPixel, class TLabel = double> +class ITK_EXPORT ImageViewerBase + : public itk::ProcessObject +{ +public: + /** Standard class typedefs */ + typedef ImageViewerBase Self; + typedef itk::ProcessObject Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageViewerBase,itk::ProcessObject); + + /// Template pixel type + typedef TPixel InputPixelType; + typedef TLabel LabelType; + typedef otb::ImageViewerScrollWidget<InputPixelType,LabelType> ScrollWidgetType; + typedef otb::ImageViewerZoomWidget<InputPixelType,LabelType> ZoomWidgetType; + typedef otb::ImageViewerFullWidget<InputPixelType,LabelType> FullWidgetType; + typedef Fl_Output * FlOutputPointerType; + + typedef typename ScrollWidgetType::ImageType ImageType; + typedef typename ScrollWidgetType::OverlayImageType OverlayImageType; + typedef typename ScrollWidgetType::TransferFunctionListType TransferFunctionListType; + typedef typename TransferFunctionListType::Pointer TransferFunctionListPointerType; + typedef typename ScrollWidgetType::AffineTransferFunctionType AffineTransferFunctionType; + typedef typename ImageType::Pointer ImagePointerType; + typedef typename OverlayImageType::Pointer OverlayImagePointerType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::PointType PointType; + typedef typename ImageType::SizeType SizeType; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::RegionType RegionType; + typedef typename ImageType::OffsetType OffsetType; + typedef typename ScrollWidgetType::VectorPixelType VectorPixelType; + typedef typename ScrollWidgetType::ViewModelType ViewModelType; + typedef typename ScrollWidgetType::Pointer ScrollWidgetPointerType; + typedef typename ZoomWidgetType::Pointer ZoomWidgetPointerType; + typedef typename FullWidgetType::Pointer FullWidgetPointerType; + itkStaticConstMacro(ImageDimension,unsigned int,ImageType::ImageDimension); + + + typedef itk::ImageRegionConstIterator< ImageType > InputIteratorType; + typedef itk::Vector<typename itk::NumericTraits<InputPixelType>::RealType,1> MeasurementVectorType; + typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; + typedef float HistogramMeasurementType; + typedef itk::Statistics::ListSampleToHistogramGenerator<ListSampleType,HistogramMeasurementType, + itk::Statistics::DenseFrequencyContainer,1> HistogramGeneratorType; + typedef otb::ObjectList<ListSampleType> ListSampleListType; + typedef otb::ObjectList<HistogramGeneratorType> HistogramGeneratorListType; + typedef typename HistogramGeneratorListType::Pointer HistogramGeneratorListPointerType; + typedef typename HistogramGeneratorType::HistogramType HistogramType; + typedef otb::ImageViewerHistogramAndTransferFunctionWidget<HistogramType,InputPixelType,LabelType> HistogramWidgetType; + typedef typename HistogramWidgetType::Pointer HistogramWidgetPointerType; + + /// Support for conversion from otb::Image to otb::VectorImage + typedef typename PixelType::ValueType ValueType; + typedef otb::Image<ValueType,ImageDimension> SingleImageType; + typedef typename SingleImageType::Pointer SingleImagePointerType; + typedef otb::ImageToVectorImageCastFilter<SingleImageType,ImageType> VectorCastFilterType; + typedef typename VectorCastFilterType::Pointer VectorCastFilterPointerType; + + /// Definition of streaming shrink image filter + typedef otb::StreamingShrinkImageFilter<ImageType,ImageType> ShrinkFilterType; + typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; + typedef otb::StreamingShrinkImageFilter<OverlayImageType,OverlayImageType> OverlayShrinkFilterType; + typedef typename OverlayShrinkFilterType::Pointer OverlayShrinkFilterPointerType; + + /// Definition of box form to represent displayed regions. + typedef otb::ImageWidgetBoxForm BoxType; + typedef typename BoxType::Pointer BoxPointerType; + + /// List of linked viewer typedef + typedef otb::ObjectList<Self> ViewerListType; + typedef typename ViewerListType::Pointer ViewerListPointerType; + + /// Linked viewer offset list + typedef std::vector<OffsetType> OffsetListType; + + /// Type for the overlay list + typedef typename FullWidgetType::FormListType FormListType; + typedef typename FormListType::Pointer FormListPointerType; + typedef typename FormListType::Iterator FormListIteratorType; + + /// type for the list of the polygon ROI + typedef otb::Polygon<LabelType> PolygonType; + typedef typename PolygonType::VertexListConstIteratorType PolygonIteratorType; + typedef otb::ObjectList<PolygonType> PolygonListType; + typedef typename PolygonListType::Pointer PolygonListPointerType; + typedef typename PolygonListType::Iterator PolygonListIteratorType; + typedef ImageWidgetPolygonForm<LabelType> ImageWidgetPolygonFormType; + typedef typename ImageWidgetPolygonFormType::Pointer ImageWidgetPolygonFormPointerType; + typedef typename ImageWidgetPolygonFormType::ColorType ColorType; + typedef ImageWidgetCircleForm ImageWidgetCircleFormType; + typedef typename ImageWidgetCircleFormType::Pointer ImageWidgetCircleFormPointerType; + typedef std::map<LabelType,ColorType> ROIColorMapType; + + typedef otb::PolyLineParametricPathWithValue<double,2> PathType; + typedef typename PathType::VertexListConstIteratorType PathIteratorType; + typedef otb::ObjectList<PathType> PathListType; + typedef typename PathListType::Pointer PathListPointerType; + typedef typename PathListType::Iterator PathListIteratorType; + typedef ImageWidgetPolylineForm<double> ImageWidgetPolylineFormType; + typedef typename ImageWidgetPolylineFormType::Pointer ImageWidgetPolylineFormPointerType; + + /// Accessors + itkGetMacro(Built,bool); + itkGetMacro(ShrinkFactor,unsigned int); + itkSetMacro(RedChannelIndex,unsigned int); + itkGetMacro(RedChannelIndex,unsigned int); + itkSetMacro(GreenChannelIndex,unsigned int); + itkGetMacro(GreenChannelIndex,unsigned int); + itkSetMacro(BlueChannelIndex,unsigned int); + itkGetMacro(BlueChannelIndex,unsigned int); + itkSetMacro(Label,std::string); + itkGetMacro(Label,std::string); + itkSetMacro(QuicklookRatioCoef,double); + itkGetMacro(QuicklookRatioCoef,double); + itkSetMacro(NormalizationFactor,double); + itkGetMacro(NormalizationFactor,double); + itkGetMacro(Updating,bool); + itkGetMacro(UseScroll,bool); + itkGetObjectMacro(PolygonROIList, PolygonListType); + itkSetObjectMacro(PolygonROIList, PolygonListType); + itkGetObjectMacro(PathList, PathListType); + itkSetObjectMacro(PathList, PathListType); + itkGetObjectMacro(InterfaceBoxesList,FormListType); + itkSetObjectMacro(InterfaceBoxesList,FormListType); + itkSetMacro(InterfaceBoxesColor,ColorType); + itkGetMacro(InterfaceBoxesColor,ColorType); + itkSetMacro(DefaultROIColor,ColorType); + itkGetMacro(DefaultROIColor,ColorType); + itkSetMacro(NextROILabel,LabelType); + itkGetMacro(NextROILabel,LabelType); + itkGetMacro(FullWidget,FullWidgetPointerType); + itkGetMacro(ScrollWidget,ScrollWidgetPointerType); + itkGetMacro(ZoomWidget,ZoomWidgetPointerType); + itkGetMacro(RedHistogramWidget,HistogramWidgetPointerType); + itkGetMacro(GreenHistogramWidget,HistogramWidgetPointerType); + itkGetMacro(BlueHistogramWidget,HistogramWidgetPointerType); + itkGetMacro(ZoomMaxInitialSize,unsigned int); + itkSetMacro(ZoomMaxInitialSize,unsigned int); + itkGetMacro(ScrollMaxInitialSize,unsigned int); + itkSetMacro(ScrollMaxInitialSize,unsigned int); + itkGetMacro(FullMaxInitialSize,unsigned int); + itkSetMacro(FullMaxInitialSize,unsigned int); + itkSetMacro(ScrollLimitSize,unsigned int); + itkGetMacro(ScrollLimitSize,unsigned int); + itkGetMacro(PixLocOutput,FlOutputPointerType); + itkSetMacro(PixLocOutput,FlOutputPointerType); + itkSetMacro(RectangularROISelectionMode,bool); + itkGetMacro(RectangularROISelectionMode,bool); + itkSetMacro(PolygonalROISelectionMode,bool); + itkGetMacro(PolygonalROISelectionMode,bool); + itkGetObjectMacro(InputImage,ImageType); + itkGetMacro(ImageGeometry,double); + itkSetMacro(ShowZoomWidget,bool); + itkGetMacro(ShowZoomWidget,bool); + itkSetMacro(ShowFullWidget,bool); + itkGetMacro(ShowFullWidget,bool); + itkSetMacro(ShowScrollWidget,bool); + itkGetMacro(ShowScrollWidget,bool); + itkSetMacro(UseImageOverlay,bool); + itkGetMacro(UseImageOverlay,bool); + itkSetMacro(ShowHistograms,bool); + itkGetMacro(ShowHistograms,bool); + itkGetObjectMacro(TransferFunctionList,TransferFunctionListType); + itkSetMacro(LineWidth,double); + itkGetMacro(LineWidth,double); + + /** Set the input image (VectorImage version) */ + virtual void SetImage(ImageType * img); + + /** Set the input image (Image version) */ + virtual void SetImage(SingleImageType * img); + + /** Set the input image overlay (VectorImage of unsigned char image with at least 3 channels) */ + virtual void SetImageOverlay(OverlayImageType * img); + + /** Get the shrinked image if scroll is activated and else the input image */ + virtual ImageType * GetShrinkedImage(void); + + /** Show the viewer (Update) */ + virtual void Show(void); + /** Hide all Image View Windows */ + virtual void Hide(void); + + /** Compute the normalization factors */ + virtual void ComputeNormalizationFactors(void); + + /** Build the interfaces */ + virtual void Build(void); + + /** Update the widgets */ + virtual void Update(void); + + /** Update the full widget */ + virtual void UpdateFullWidget(void); + + /** Update the scroll widget */ + virtual void UpdateScrollWidget(void); + + /** Update the ZoomWidget */ + virtual void UpdateZoomWidget(void); + + /** Change the ZoomViewedRegion + * \param clickedIndex The new center of the region + **/ + virtual void ChangeZoomViewedRegion(IndexType clickedIndex); + /** + * Change the Full Viewed region + * \param clickedIndex The new center of the region + */ + virtual void ChangeFullViewedRegion(IndexType clickedIndex); + + /** Compute the constrained region */ + virtual RegionType ComputeConstrainedRegion(RegionType smallRegion, RegionType bigRegion); + + /** Display pixel information */ + virtual void ReportPixel(IndexType index); + + /** Clear pixel information */ + virtual void ClearPixLocVal(void); + + /** Generate overlay list */ + virtual void GenerateOverlayList(void); + + /** This is a helper class that performs a Show() and Fl::run() in order to ease + * the use of the class for example in wrappings. + * \return The return code from fltk. + */ + int FlRun(void); + /** + * Link this viewer with the given viewer. + * \param viewer The viewer to link with. + */ + virtual void Link(Self * viewer); + /** + * Link this viewer with the given viewer. + * \param viewer The viewer to link with. + * \param offset Offset between two viewers + */ + virtual void Link(Self * viewer, OffsetType offset); + + /** + * Unlink this viewer with the given viewer. + * \param viewer The viewer to link with + */ + virtual void Unlink(Self * viewer); + /** + * Return the internal index if the viewers are linked + * \param viewer the viewer to ask + * \return -1 if the viewer are not linked + */ + virtual int IsLinkedTo(Self * viewer); + /** + * Return the offset associated with the linked viewer at the internal index. + * \param index the internal index + * \return the Offset + */ + virtual OffsetType GetOffset(int index); + + /** + * Clear all the links of the current viewer. + */ + virtual void ClearLinks(void); + + /** + * \return true if view model is RGB + */ + virtual ViewModelType GetViewModel(void); + + /** + * Set the view model + * \param viewModel True to turn on RGB view model + */ + virtual void SetViewModel(ViewModelType viewModel); + + /** + * Initialize view model + */ + virtual void InitializeViewModel(void); + + /** + * Force opengl buffers reset + */ + virtual void Reset(void); + + /** + * Force redraw + */ + virtual void ChangeTransferFunctions(void); + + /** + * Add a new color-label combination in the ROI color map. Note + * that if the entry already exists, it will be overwritten. + * \param label The label + * \param color the color to associate the label with + */ + virtual void AddROIColorMapEntry(const LabelType &label, const ColorType &color); + + + /** + * Remove a new color-label combination in the ROI color map. If the label + * is not present, does nothing. + * \param label The label + */ + virtual void RemoveROIColorMapEntry(const LabelType &label); + + /** + * Fill the color parameter with the color entry associated with the label. Returns + * true if the entry exists, and false otherwise. + * \param label The label + * \param color The color + * \return true if the label was found. + */ + virtual bool GetROIColorMapEntry(const LabelType &label, ColorType &color); + + + /** + * Clear the ROI color map. + */ + virtual void ClearROIColorMap(void); + + + /** + * Set the image overlay opacity of all widgets + * \param opacity + */ + virtual void SetImageOverlayOpacity(unsigned char opacity); + + +protected: + + /** + * Link this viewer with the given viewer. + * \param viewer The viewer to link with + * \param offset Offset between two viewers + * \param backwardLinkFlag Link back to this viewer. + */ + virtual void Link(Self * viewer, OffsetType offset, bool backwardLinkFlag); + + /** + * Unlink this viewer with the given viewer. + * \param viewer The viewer to link with. + * \param backwardLinkFlag Link back to this viewer. */ - template <class TPixel, class TLabel = double> - class ITK_EXPORT ImageViewerBase - : public itk::ProcessObject - { - public: - /** Standard class typedefs */ - typedef ImageViewerBase Self; - typedef itk::ProcessObject Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods). */ - itkTypeMacro(ImageViewerBase,itk::ProcessObject); - - /// Template pixel type - typedef TPixel InputPixelType; - typedef TLabel LabelType; - typedef otb::ImageViewerScrollWidget<InputPixelType,LabelType> ScrollWidgetType; - typedef otb::ImageViewerZoomWidget<InputPixelType,LabelType> ZoomWidgetType; - typedef otb::ImageViewerFullWidget<InputPixelType,LabelType> FullWidgetType; - typedef Fl_Output * FlOutputPointerType; - - typedef typename ScrollWidgetType::ImageType ImageType; - typedef typename ScrollWidgetType::OverlayImageType OverlayImageType; - typedef typename ScrollWidgetType::TransferFunctionListType TransferFunctionListType; - typedef typename TransferFunctionListType::Pointer TransferFunctionListPointerType; - typedef typename ScrollWidgetType::AffineTransferFunctionType AffineTransferFunctionType; - typedef typename ImageType::Pointer ImagePointerType; - typedef typename OverlayImageType::Pointer OverlayImagePointerType; - typedef typename ImageType::IndexType IndexType; - typedef typename ImageType::PointType PointType; - typedef typename ImageType::SizeType SizeType; - typedef typename ImageType::PixelType PixelType; - typedef typename ImageType::RegionType RegionType; - typedef typename ImageType::OffsetType OffsetType; - typedef typename ScrollWidgetType::VectorPixelType VectorPixelType; - typedef typename ScrollWidgetType::ViewModelType ViewModelType; - typedef typename ScrollWidgetType::Pointer ScrollWidgetPointerType; - typedef typename ZoomWidgetType::Pointer ZoomWidgetPointerType; - typedef typename FullWidgetType::Pointer FullWidgetPointerType; - itkStaticConstMacro(ImageDimension,unsigned int,ImageType::ImageDimension); - - - typedef itk::ImageRegionConstIterator< ImageType > InputIteratorType; - typedef itk::Vector<typename itk::NumericTraits<InputPixelType>::RealType,1> MeasurementVectorType; - typedef itk::Statistics::ListSample<MeasurementVectorType> ListSampleType; - typedef float HistogramMeasurementType; - typedef itk::Statistics::ListSampleToHistogramGenerator<ListSampleType,HistogramMeasurementType, - itk::Statistics::DenseFrequencyContainer,1> HistogramGeneratorType; - typedef otb::ObjectList<ListSampleType> ListSampleListType; - typedef otb::ObjectList<HistogramGeneratorType> HistogramGeneratorListType; - typedef typename HistogramGeneratorListType::Pointer HistogramGeneratorListPointerType; - typedef typename HistogramGeneratorType::HistogramType HistogramType; - typedef otb::ImageViewerHistogramAndTransferFunctionWidget<HistogramType,InputPixelType,LabelType> HistogramWidgetType; - typedef typename HistogramWidgetType::Pointer HistogramWidgetPointerType; - - /// Support for conversion from otb::Image to otb::VectorImage - typedef typename PixelType::ValueType ValueType; - typedef otb::Image<ValueType,ImageDimension> SingleImageType; - typedef typename SingleImageType::Pointer SingleImagePointerType; - typedef otb::ImageToVectorImageCastFilter<SingleImageType,ImageType> VectorCastFilterType; - typedef typename VectorCastFilterType::Pointer VectorCastFilterPointerType; - - /// Definition of streaming shrink image filter - typedef otb::StreamingShrinkImageFilter<ImageType,ImageType> ShrinkFilterType; - typedef typename ShrinkFilterType::Pointer ShrinkFilterPointerType; - typedef otb::StreamingShrinkImageFilter<OverlayImageType,OverlayImageType> OverlayShrinkFilterType; - typedef typename OverlayShrinkFilterType::Pointer OverlayShrinkFilterPointerType; - - /// Definition of box form to represent displayed regions. - typedef otb::ImageWidgetBoxForm BoxType; - typedef typename BoxType::Pointer BoxPointerType; - - /// List of linked viewer typedef - typedef otb::ObjectList<Self> ViewerListType; - typedef typename ViewerListType::Pointer ViewerListPointerType; - - /// Linked viewer offset list - typedef std::vector<OffsetType> OffsetListType; - - /// Type for the overlay list - typedef typename FullWidgetType::FormListType FormListType; - typedef typename FormListType::Pointer FormListPointerType; - typedef typename FormListType::Iterator FormListIteratorType; - - /// type for the list of the polygon ROI - typedef otb::Polygon<LabelType> PolygonType; - typedef typename PolygonType::VertexListConstIteratorType PolygonIteratorType; - typedef otb::ObjectList<PolygonType> PolygonListType; - typedef typename PolygonListType::Pointer PolygonListPointerType; - typedef typename PolygonListType::Iterator PolygonListIteratorType; - typedef ImageWidgetPolygonForm<LabelType> ImageWidgetPolygonFormType; - typedef typename ImageWidgetPolygonFormType::Pointer ImageWidgetPolygonFormPointerType; - typedef typename ImageWidgetPolygonFormType::ColorType ColorType; - typedef ImageWidgetCircleForm ImageWidgetCircleFormType; - typedef typename ImageWidgetCircleFormType::Pointer ImageWidgetCircleFormPointerType; - typedef std::map<LabelType,ColorType> ROIColorMapType; - - typedef otb::PolyLineParametricPathWithValue<double,2> PathType; - typedef typename PathType::VertexListConstIteratorType PathIteratorType; - typedef otb::ObjectList<PathType> PathListType; - typedef typename PathListType::Pointer PathListPointerType; - typedef typename PathListType::Iterator PathListIteratorType; - typedef ImageWidgetPolylineForm<double> ImageWidgetPolylineFormType; - typedef typename ImageWidgetPolylineFormType::Pointer ImageWidgetPolylineFormPointerType; - - /// Accessors - itkGetMacro(Built,bool); - itkGetMacro(ShrinkFactor,unsigned int); - itkSetMacro(RedChannelIndex,unsigned int); - itkGetMacro(RedChannelIndex,unsigned int); - itkSetMacro(GreenChannelIndex,unsigned int); - itkGetMacro(GreenChannelIndex,unsigned int); - itkSetMacro(BlueChannelIndex,unsigned int); - itkGetMacro(BlueChannelIndex,unsigned int); - itkSetMacro(Label,std::string); - itkGetMacro(Label,std::string); - itkSetMacro(QuicklookRatioCoef,double); - itkGetMacro(QuicklookRatioCoef,double); - itkSetMacro(NormalizationFactor,double); - itkGetMacro(NormalizationFactor,double); - itkGetMacro(Updating,bool); - itkGetMacro(UseScroll,bool); - itkGetObjectMacro(PolygonROIList, PolygonListType); - itkSetObjectMacro(PolygonROIList, PolygonListType); - itkGetObjectMacro(PathList, PathListType); - itkSetObjectMacro(PathList, PathListType); - itkGetObjectMacro(InterfaceBoxesList,FormListType); - itkSetObjectMacro(InterfaceBoxesList,FormListType); - itkSetMacro(InterfaceBoxesColor,ColorType); - itkGetMacro(InterfaceBoxesColor,ColorType); - itkSetMacro(DefaultROIColor,ColorType); - itkGetMacro(DefaultROIColor,ColorType); - itkSetMacro(NextROILabel,LabelType); - itkGetMacro(NextROILabel,LabelType); - itkGetMacro(FullWidget,FullWidgetPointerType); - itkGetMacro(ScrollWidget,ScrollWidgetPointerType); - itkGetMacro(ZoomWidget,ZoomWidgetPointerType); - itkGetMacro(RedHistogramWidget,HistogramWidgetPointerType); - itkGetMacro(GreenHistogramWidget,HistogramWidgetPointerType); - itkGetMacro(BlueHistogramWidget,HistogramWidgetPointerType); - itkGetMacro(ZoomMaxInitialSize,unsigned int); - itkSetMacro(ZoomMaxInitialSize,unsigned int); - itkGetMacro(ScrollMaxInitialSize,unsigned int); - itkSetMacro(ScrollMaxInitialSize,unsigned int); - itkGetMacro(FullMaxInitialSize,unsigned int); - itkSetMacro(FullMaxInitialSize,unsigned int); - itkSetMacro(ScrollLimitSize,unsigned int); - itkGetMacro(ScrollLimitSize,unsigned int); - itkGetMacro(PixLocOutput,FlOutputPointerType); - itkSetMacro(PixLocOutput,FlOutputPointerType); - itkSetMacro(RectangularROISelectionMode,bool); - itkGetMacro(RectangularROISelectionMode,bool); - itkSetMacro(PolygonalROISelectionMode,bool); - itkGetMacro(PolygonalROISelectionMode,bool); - itkGetObjectMacro(InputImage,ImageType); - itkGetMacro(ImageGeometry,double); - itkSetMacro(ShowZoomWidget,bool); - itkGetMacro(ShowZoomWidget,bool); - itkSetMacro(ShowFullWidget,bool); - itkGetMacro(ShowFullWidget,bool); - itkSetMacro(ShowScrollWidget,bool); - itkGetMacro(ShowScrollWidget,bool); - itkSetMacro(UseImageOverlay,bool); - itkGetMacro(UseImageOverlay,bool); - itkSetMacro(ShowHistograms,bool); - itkGetMacro(ShowHistograms,bool); - itkGetObjectMacro(TransferFunctionList,TransferFunctionListType); - itkSetMacro(LineWidth,double); - itkGetMacro(LineWidth,double); - - /** Set the input image (VectorImage version) */ - virtual void SetImage(ImageType * img); - - /** Set the input image (Image version) */ - virtual void SetImage(SingleImageType * img); - - /** Set the input image overlay (VectorImage of unsigned char image with at least 3 channels) */ - virtual void SetImageOverlay(OverlayImageType * img); - - /** Get the shrinked image if scroll is activated and else the input image */ - virtual ImageType * GetShrinkedImage(void); - - /** Show the viewer (Update) */ - virtual void Show(void); - /** Hide all Image View Windows */ - virtual void Hide(void); - - /** Compute the normalization factors */ - virtual void ComputeNormalizationFactors(void); - - /** Build the interfaces */ - virtual void Build(void); - - /** Update the widgets */ - virtual void Update(void); - - /** Update the full widget */ - virtual void UpdateFullWidget(void); - - /** Update the scroll widget */ - virtual void UpdateScrollWidget(void); - - /** Update the ZoomWidget */ - virtual void UpdateZoomWidget(void); - - /** Change the ZoomViewedRegion - * \param clickedIndex The new center of the region - **/ - virtual void ChangeZoomViewedRegion(IndexType clickedIndex); - /** - * Change the Full Viewed region - * \param clickedIndex The new center of the region - */ - virtual void ChangeFullViewedRegion(IndexType clickedIndex); - - /** Compute the constrained region */ - virtual RegionType ComputeConstrainedRegion(RegionType smallRegion, RegionType bigRegion); - - /** Display pixel information */ - virtual void ReportPixel(IndexType index); - - /** Clear pixel information */ - virtual void ClearPixLocVal(void); - - /** Generate overlay list */ - virtual void GenerateOverlayList(void); - - /** This is a helper class that performs a Show() and Fl::run() in order to ease - * the use of the class for example in wrappings. - * \return The return code from fltk. - */ - int FlRun(void); - /** - * Link this viewer with the given viewer. - * \param viewer The viewer to link with. - */ - virtual void Link(Self * viewer); - /** - * Link this viewer with the given viewer. - * \param viewer The viewer to link with. - * \param offset Offset between two viewers - */ - virtual void Link(Self * viewer, OffsetType offset); - - /** - * Unlink this viewer with the given viewer. - * \param viewer The viewer to link with - */ - virtual void Unlink(Self * viewer); - /** - * Return the internal index if the viewers are linked - * \param viewer the viewer to ask - * \return -1 if the viewer are not linked - */ - virtual int IsLinkedTo(Self * viewer); - /** - * Return the offset associated with the linked viewer at the internal index. - * \param index the internal index - * \return the Offset - */ - virtual OffsetType GetOffset(int index); - - /** - * Clear all the links of the current viewer. - */ - virtual void ClearLinks(void); - - /** - * \return true if view model is RGB - */ - virtual ViewModelType GetViewModel(void); - - /** - * Set the view model - * \param viewModel True to turn on RGB view model - */ - virtual void SetViewModel(ViewModelType viewModel); - - /** - * Initialize view model - */ - virtual void InitializeViewModel(void); - - /** - * Force opengl buffers reset - */ - virtual void Reset(void); - - /** - * Force redraw - */ - virtual void ChangeTransferFunctions(void); - - /** - * Add a new color-label combination in the ROI color map. Note - * that if the entry already exists, it will be overwritten. - * \param label The label - * \param color the color to associate the label with - */ - virtual void AddROIColorMapEntry(const LabelType &label, const ColorType &color); - - - /** - * Remove a new color-label combination in the ROI color map. If the label - * is not present, does nothing. - * \param label The label - */ - virtual void RemoveROIColorMapEntry(const LabelType &label); - - /** - * Fill the color parameter with the color entry associated with the label. Returns - * true if the entry exists, and false otherwise. - * \param label The label - * \param color The color - * \return true if the label was found. - */ - virtual bool GetROIColorMapEntry(const LabelType &label, ColorType &color); - - - /** - * Clear the ROI color map. - */ - virtual void ClearROIColorMap(void); - - - /** - * Set the image overlay opacity of all widgets - * \param opacity - */ - virtual void SetImageOverlayOpacity(unsigned char opacity); - - - protected: - - /** - * Link this viewer with the given viewer. - * \param viewer The viewer to link with - * \param offset Offset between two viewers - * \param backwardLinkFlag Link back to this viewer. - */ - virtual void Link(Self * viewer, OffsetType offset, bool backwardLinkFlag); - - /** - * Unlink this viewer with the given viewer. - * \param viewer The viewer to link with. - * \param backwardLinkFlag Link back to this viewer. - */ - virtual void Unlink(Self * viewer,bool backwardLinkFlag); - - // Constructor and destructor - ImageViewerBase(); - ~ImageViewerBase(); - - /** Line width*/ - double m_LineWidth; - - private: - ImageViewerBase(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - /// Label - std::string m_Label; - /// zoom widget component - ZoomWidgetPointerType m_ZoomWidget; - /// Show zoom widget flag - bool m_ShowZoomWidget; - /// scroll widget component - ScrollWidgetPointerType m_ScrollWidget; - /// Show scroll widget flag - bool m_ShowScrollWidget; - /// full widget component - FullWidgetPointerType m_FullWidget; - /// Show full widget flag - bool m_ShowFullWidget; - /// The image to view - ImagePointerType m_InputImage; - /// The image overlay - OverlayImagePointerType m_InputImageOverlay; - /// true if scroll widget is used - bool m_UseScroll; - /// Show the histograms - bool m_ShowHistograms; - - /// Intial sizes - unsigned int m_ScrollMaxInitialSize; - unsigned int m_FullMaxInitialSize; - unsigned int m_ZoomMaxInitialSize; - /// Image geomerty ratio - double m_ImageGeometry; - /// Limit size for the scroll view - unsigned int m_ScrollLimitSize; - FlOutputPointerType m_PixLocOutput; - /// Pointer to the shrink filters - ShrinkFilterPointerType m_Shrink; - OverlayShrinkFilterPointerType m_ShrinkOverlay; - - /// The shrink factor - unsigned int m_ShrinkFactor; - /// true if the Gui has been built. - bool m_Built; - /// Channel indices - unsigned int m_RedChannelIndex; - unsigned int m_GreenChannelIndex; - unsigned int m_BlueChannelIndex; - /// Quicklook quality factor - double m_QuicklookRatioCoef; - /// Normalization quality factor - double m_NormalizationFactor; - /// Converter from otb::Image to otb::VectorImage - VectorCastFilterPointerType m_VectorCastFilter; - VectorCastFilterPointerType m_VectorCastFilterOverlay; - /// Wether the viewer is updating or not - bool m_Updating; - /// The list of viewer with which this viewer is linked - ViewerListPointerType m_LinkedViewerList; - /// Linked viewer offset list - OffsetListType m_LinkedViewerOffsetList; - /// PolygonList - PolygonListPointerType m_PolygonROIList; - /// PathList - PathListPointerType m_PathList; - /// Interface boxes - FormListPointerType m_InterfaceBoxesList; - /// Next ROI color - ColorType m_DefaultROIColor; - /// Interfaces box color - ColorType m_InterfaceBoxesColor; - /// Label of the next ROI - LabelType m_NextROILabel; - /// Toogle the rectangular ROI selection mode - bool m_RectangularROISelectionMode; - /// Toogle the polygonal ROI selection mode - bool m_PolygonalROISelectionMode; - /// Map used to associate a label with a color - ROIColorMapType m_ROIColorMap; - /// True if an image overlay is used - bool m_UseImageOverlay; - /// List of histogram generators (one per channel) - HistogramGeneratorListPointerType m_HistogramGeneratorList; - /// Transfer function list - TransferFunctionListPointerType m_TransferFunctionList; - - /// Histogram widgets - HistogramWidgetPointerType m_RedHistogramWidget; - HistogramWidgetPointerType m_BlueHistogramWidget; - HistogramWidgetPointerType m_GreenHistogramWidget; - - }; + virtual void Unlink(Self * viewer,bool backwardLinkFlag); + + // Constructor and destructor + ImageViewerBase(); + ~ImageViewerBase(); + + /** Line width*/ + double m_LineWidth; + +private: + ImageViewerBase(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /// Label + std::string m_Label; + /// zoom widget component + ZoomWidgetPointerType m_ZoomWidget; + /// Show zoom widget flag + bool m_ShowZoomWidget; + /// scroll widget component + ScrollWidgetPointerType m_ScrollWidget; + /// Show scroll widget flag + bool m_ShowScrollWidget; + /// full widget component + FullWidgetPointerType m_FullWidget; + /// Show full widget flag + bool m_ShowFullWidget; + /// The image to view + ImagePointerType m_InputImage; + /// The image overlay + OverlayImagePointerType m_InputImageOverlay; + /// true if scroll widget is used + bool m_UseScroll; + /// Show the histograms + bool m_ShowHistograms; + + /// Intial sizes + unsigned int m_ScrollMaxInitialSize; + unsigned int m_FullMaxInitialSize; + unsigned int m_ZoomMaxInitialSize; + /// Image geomerty ratio + double m_ImageGeometry; + /// Limit size for the scroll view + unsigned int m_ScrollLimitSize; + FlOutputPointerType m_PixLocOutput; + /// Pointer to the shrink filters + ShrinkFilterPointerType m_Shrink; + OverlayShrinkFilterPointerType m_ShrinkOverlay; + + /// The shrink factor + unsigned int m_ShrinkFactor; + /// true if the Gui has been built. + bool m_Built; + /// Channel indices + unsigned int m_RedChannelIndex; + unsigned int m_GreenChannelIndex; + unsigned int m_BlueChannelIndex; + /// Quicklook quality factor + double m_QuicklookRatioCoef; + /// Normalization quality factor + double m_NormalizationFactor; + /// Converter from otb::Image to otb::VectorImage + VectorCastFilterPointerType m_VectorCastFilter; + VectorCastFilterPointerType m_VectorCastFilterOverlay; + /// Wether the viewer is updating or not + bool m_Updating; + /// The list of viewer with which this viewer is linked + ViewerListPointerType m_LinkedViewerList; + /// Linked viewer offset list + OffsetListType m_LinkedViewerOffsetList; + /// PolygonList + PolygonListPointerType m_PolygonROIList; + /// PathList + PathListPointerType m_PathList; + /// Interface boxes + FormListPointerType m_InterfaceBoxesList; + /// Next ROI color + ColorType m_DefaultROIColor; + /// Interfaces box color + ColorType m_InterfaceBoxesColor; + /// Label of the next ROI + LabelType m_NextROILabel; + /// Toogle the rectangular ROI selection mode + bool m_RectangularROISelectionMode; + /// Toogle the polygonal ROI selection mode + bool m_PolygonalROISelectionMode; + /// Map used to associate a label with a color + ROIColorMapType m_ROIColorMap; + /// True if an image overlay is used + bool m_UseImageOverlay; + /// List of histogram generators (one per channel) + HistogramGeneratorListPointerType m_HistogramGeneratorList; + /// Transfer function list + TransferFunctionListPointerType m_TransferFunctionList; + + /// Histogram widgets + HistogramWidgetPointerType m_RedHistogramWidget; + HistogramWidgetPointerType m_BlueHistogramWidget; + HistogramWidgetPointerType m_GreenHistogramWidget; + +}; } // end namespace otb diff --git a/Code/Visu/otbImageViewerBase.txx b/Code/Visu/otbImageViewerBase.txx index 7a29f1ded5fdab902c2e42b1a460fed9932a26d8..2c32a2eaef8045d1762d07b5dd8f75d4aa6d8b63 100644 --- a/Code/Visu/otbImageViewerBase.txx +++ b/Code/Visu/otbImageViewerBase.txx @@ -27,68 +27,68 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /// Constructor - template <class TPixel, class TLabel> - ImageViewerBase<TPixel,TLabel> - ::ImageViewerBase() - { - m_UseScroll = false; - m_ScrollMaxInitialSize = 300; - m_FullMaxInitialSize = 600; - m_ZoomMaxInitialSize = 200; - m_ImageGeometry = 1.0; - m_ScrollLimitSize = 600; - m_InterfaceBoxesColor[0]=1.0; - m_InterfaceBoxesColor[1]=0; - m_InterfaceBoxesColor[2]=0; - m_DefaultROIColor[0]=0; - m_InterfaceBoxesColor[3]=1.0; - m_DefaultROIColor[1]=0; - m_DefaultROIColor[2]=1.0; - m_DefaultROIColor[3]=0.5; - m_NextROILabel = 0; - m_ShrinkFactor=1; - m_RedChannelIndex = 0; - m_GreenChannelIndex = 1; - m_BlueChannelIndex = 2; - m_Built=false; - m_Shrink = ShrinkFilterType::New(); - m_PixLocOutput=NULL; - m_NormalizationFactor = 0.02; - m_QuicklookRatioCoef = 2; - m_VectorCastFilter = NULL; - m_LinkedViewerList = ViewerListType::New(); - m_Updating = false; - m_PolygonROIList = PolygonListType::New(); - m_PathList = PathListType::New(); - m_InterfaceBoxesList = FormListType::New(); - m_ShowFullWidget = true; - m_ShowScrollWidget = true; - m_ShowZoomWidget = true; - m_Label = "Default"; - m_RectangularROISelectionMode = false; - m_PolygonalROISelectionMode = false; - m_UseImageOverlay = false; - m_HistogramGeneratorList=HistogramGeneratorListType::New(); - m_TransferFunctionList = TransferFunctionListType::New(); - m_RedHistogramWidget = HistogramWidgetType::New(); - m_GreenHistogramWidget = HistogramWidgetType::New(); - m_BlueHistogramWidget = HistogramWidgetType::New(); - m_ShowHistograms = true; - } +/// Constructor +template <class TPixel, class TLabel> +ImageViewerBase<TPixel,TLabel> +::ImageViewerBase() +{ + m_UseScroll = false; + m_ScrollMaxInitialSize = 300; + m_FullMaxInitialSize = 600; + m_ZoomMaxInitialSize = 200; + m_ImageGeometry = 1.0; + m_ScrollLimitSize = 600; + m_InterfaceBoxesColor[0]=1.0; + m_InterfaceBoxesColor[1]=0; + m_InterfaceBoxesColor[2]=0; + m_DefaultROIColor[0]=0; + m_InterfaceBoxesColor[3]=1.0; + m_DefaultROIColor[1]=0; + m_DefaultROIColor[2]=1.0; + m_DefaultROIColor[3]=0.5; + m_NextROILabel = 0; + m_ShrinkFactor=1; + m_RedChannelIndex = 0; + m_GreenChannelIndex = 1; + m_BlueChannelIndex = 2; + m_Built=false; + m_Shrink = ShrinkFilterType::New(); + m_PixLocOutput=NULL; + m_NormalizationFactor = 0.02; + m_QuicklookRatioCoef = 2; + m_VectorCastFilter = NULL; + m_LinkedViewerList = ViewerListType::New(); + m_Updating = false; + m_PolygonROIList = PolygonListType::New(); + m_PathList = PathListType::New(); + m_InterfaceBoxesList = FormListType::New(); + m_ShowFullWidget = true; + m_ShowScrollWidget = true; + m_ShowZoomWidget = true; + m_Label = "Default"; + m_RectangularROISelectionMode = false; + m_PolygonalROISelectionMode = false; + m_UseImageOverlay = false; + m_HistogramGeneratorList=HistogramGeneratorListType::New(); + m_TransferFunctionList = TransferFunctionListType::New(); + m_RedHistogramWidget = HistogramWidgetType::New(); + m_GreenHistogramWidget = HistogramWidgetType::New(); + m_BlueHistogramWidget = HistogramWidgetType::New(); + m_ShowHistograms = true; +} - /// Destructor - template <class TPixel, class TLabel> - ImageViewerBase<TPixel,TLabel> - ::~ImageViewerBase() - {} - - /// Compute the normalization factor - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::ComputeNormalizationFactors(void) - { +/// Destructor +template <class TPixel, class TLabel> +ImageViewerBase<TPixel,TLabel> +::~ImageViewerBase() +{} + +/// Compute the normalization factor +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::ComputeNormalizationFactors(void) +{ typename ListSampleListType::Pointer sl = ListSampleListType::New(); @@ -97,7 +97,7 @@ namespace otb InputIteratorType it; // if scroll is activated, compute the factors from the quicklook - if(m_UseScroll) + if (m_UseScroll) { it = InputIteratorType(m_Shrink->GetOutput(),m_Shrink->GetOutput()->GetLargestPossibleRegion()); it.GoToBegin(); @@ -112,30 +112,30 @@ namespace otb it.GoToBegin(); } - if(this->GetViewModel() == ScrollWidgetType::COMPLEX_MODULUS) + if (this->GetViewModel() == ScrollWidgetType::COMPLEX_MODULUS) { sl->PushBack(ListSampleType::New()); - while( !it.IsAtEnd() ) + while ( !it.IsAtEnd() ) { PixelType pixel = it.Get(); // for(unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) // { - double re = static_cast<double>(pixel[m_RedChannelIndex]); - double im = static_cast<double>(pixel[m_GreenChannelIndex]); - sl->GetNthElement(0)->PushBack(vcl_sqrt(static_cast<double>(re*re+im*im))); + double re = static_cast<double>(pixel[m_RedChannelIndex]); + double im = static_cast<double>(pixel[m_GreenChannelIndex]); + sl->GetNthElement(0)->PushBack(vcl_sqrt(static_cast<double>(re*re+im*im))); // } ++it; } } - else if(this->GetViewModel() == ScrollWidgetType::COMPLEX_PHASE) + else if (this->GetViewModel() == ScrollWidgetType::COMPLEX_PHASE) { sl->PushBack(ListSampleType::New()); - while( !it.IsAtEnd() ) + while ( !it.IsAtEnd() ) { PixelType pixel = it.Get(); // for(unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) // { - sl->GetNthElement(0)->PushBack(vcl_atan2(static_cast<double>(pixel[m_GreenChannelIndex]),static_cast<double>(pixel[m_RedChannelIndex]))); + sl->GetNthElement(0)->PushBack(vcl_atan2(static_cast<double>(pixel[m_GreenChannelIndex]),static_cast<double>(pixel[m_RedChannelIndex]))); // } ++it; } @@ -143,14 +143,14 @@ namespace otb } else { - for(unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) + for (unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) { sl->PushBack(ListSampleType::New()); } - while( !it.IsAtEnd() ) + while ( !it.IsAtEnd() ) { PixelType pixel = it.Get(); - for(unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) + for (unsigned int i = 0;i<m_InputImage->GetNumberOfComponentsPerPixel();++i) { sl->GetNthElement(i)->PushBack(pixel[i]); } @@ -162,162 +162,162 @@ namespace otb m_TransferFunctionList->Clear(); otbMsgDebugMacro(<<"Nb bands: "<<m_InputImage->GetNumberOfComponentsPerPixel()); - for(unsigned int i = 0;i<sl->Size();++i) - { - typename HistogramGeneratorType::Pointer generator = HistogramGeneratorType::New(); - generator->SetListSample(sl->GetNthElement(i)); - typename HistogramGeneratorType::HistogramType::SizeType size; - // size.Fill(static_cast<unsigned int>(vcl_ceil(1/m_NormalizationFactor)*10)); - size.Fill(256); - generator->SetNumberOfBins(size); - generator->Update(); - m_HistogramGeneratorList->PushBack(generator); - m_TransferFunctionList->PushBack(AffineTransferFunctionType::New()); - double min = generator->GetOutput()->Quantile(0,m_NormalizationFactor); - double max = generator->GetOutput()->Quantile(0,1-m_NormalizationFactor); - m_TransferFunctionList->Back()->SetLowerBound(static_cast<InputPixelType>(min)); - m_TransferFunctionList->Back()->SetUpperBound(static_cast<InputPixelType>(max)); - } + for (unsigned int i = 0;i<sl->Size();++i) + { + typename HistogramGeneratorType::Pointer generator = HistogramGeneratorType::New(); + generator->SetListSample(sl->GetNthElement(i)); + typename HistogramGeneratorType::HistogramType::SizeType size; + // size.Fill(static_cast<unsigned int>(vcl_ceil(1/m_NormalizationFactor)*10)); + size.Fill(256); + generator->SetNumberOfBins(size); + generator->Update(); + m_HistogramGeneratorList->PushBack(generator); + m_TransferFunctionList->PushBack(AffineTransferFunctionType::New()); + double min = generator->GetOutput()->Quantile(0,m_NormalizationFactor); + double max = generator->GetOutput()->Quantile(0,1-m_NormalizationFactor); + m_TransferFunctionList->Back()->SetLowerBound(static_cast<InputPixelType>(min)); + m_TransferFunctionList->Back()->SetUpperBound(static_cast<InputPixelType>(max)); + } - if(m_UseScroll) - { - m_ScrollWidget->SetTransferFunctionList(m_TransferFunctionList); - } + if (m_UseScroll) + { + m_ScrollWidget->SetTransferFunctionList(m_TransferFunctionList); + } m_ZoomWidget->SetTransferFunctionList(m_TransferFunctionList); m_FullWidget->SetTransferFunctionList(m_TransferFunctionList); - } +} - /// Build the HMI - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::Build(void) +/// Build the HMI +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::Build(void) +{ + otbMsgDebugMacro(<<"Entering build method"); + if (!m_InputImage) { - otbMsgDebugMacro(<<"Entering build method"); - if(!m_InputImage) - { - itkExceptionMacro(<<"No input image !"); - } + itkExceptionMacro(<<"No input image !"); + } - if(m_UseImageOverlay && !m_InputImageOverlay) - { - itkExceptionMacro(<<"UseImageOverlay option toggled, but no image overlay specified !"); - } + if (m_UseImageOverlay && !m_InputImageOverlay) + { + itkExceptionMacro(<<"UseImageOverlay option toggled, but no image overlay specified !"); + } - if(m_UseImageOverlay - &&m_InputImage->GetLargestPossibleRegion().GetSize() - != m_InputImageOverlay->GetLargestPossibleRegion().GetSize()) - { - itkExceptionMacro(<<"Input image and input image overlay do not have the same size !"); - } + if (m_UseImageOverlay + &&m_InputImage->GetLargestPossibleRegion().GetSize() + != m_InputImageOverlay->GetLargestPossibleRegion().GetSize()) + { + itkExceptionMacro(<<"Input image and input image overlay do not have the same size !"); + } - itk::OStringStream oss; - // Get the image dimension - typename ImageType::SizeType size = m_InputImage->GetLargestPossibleRegion().GetSize(); - m_ImageGeometry = static_cast<double>(size[0])/static_cast<double>(size[1]); + itk::OStringStream oss; + // Get the image dimension + typename ImageType::SizeType size = m_InputImage->GetLargestPossibleRegion().GetSize(); + m_ImageGeometry = static_cast<double>(size[0])/static_cast<double>(size[1]); - // initiate windows dimensions - int wscroll=200; - int hscroll=0; - int wfull = (size[0]<m_FullMaxInitialSize ? size[0] : m_FullMaxInitialSize); - int hfull = (size[1]<m_FullMaxInitialSize ? size[1] : m_FullMaxInitialSize); + // initiate windows dimensions + int wscroll=200; + int hscroll=0; + int wfull = (size[0]<m_FullMaxInitialSize ? size[0] : m_FullMaxInitialSize); + int hfull = (size[1]<m_FullMaxInitialSize ? size[1] : m_FullMaxInitialSize); - // decide wether to use scroll view or not - if(size[0]<m_ScrollLimitSize&&size[1]<m_ScrollLimitSize) - { - m_UseScroll=false; - } - else - { - m_UseScroll=true; - // Compute scroll size : - if(m_ImageGeometry<1) + // decide wether to use scroll view or not + if (size[0]<m_ScrollLimitSize&&size[1]<m_ScrollLimitSize) + { + m_UseScroll=false; + } + else + { + m_UseScroll=true; + // Compute scroll size : + if (m_ImageGeometry<1) { hscroll = m_ScrollMaxInitialSize; wscroll = static_cast<int>(static_cast<double>(m_ScrollMaxInitialSize)*m_ImageGeometry); } - else + else { wscroll = m_ScrollMaxInitialSize; hscroll = static_cast<int>(static_cast<double>(m_ScrollMaxInitialSize)/m_ImageGeometry); } - // Create the quicklook - m_Shrink->SetInput(m_InputImage); - if(size[0]/hscroll < size[1]/wscroll) + // Create the quicklook + m_Shrink->SetInput(m_InputImage); + if (size[0]/hscroll < size[1]/wscroll) { m_ShrinkFactor = static_cast<unsigned int>(vcl_ceil((static_cast<double>(size[0])/static_cast<double>(wscroll))/m_QuicklookRatioCoef)); } - else + else { m_ShrinkFactor = static_cast<unsigned int>(vcl_ceil((static_cast<double>(size[1])/static_cast<double>(hscroll))/m_QuicklookRatioCoef)); } - otbMsgDebugMacro(<<"Shrink factor: "<<m_ShrinkFactor); - m_Shrink->SetShrinkFactor(m_ShrinkFactor); - typedef otb::FltkFilterWatcher WatcherType; - WatcherType watcher(m_Shrink,wfull-200,hfull/2,200,20, "Generating Quicklook ..."); - m_Shrink->Update(); - } + otbMsgDebugMacro(<<"Shrink factor: "<<m_ShrinkFactor); + m_Shrink->SetShrinkFactor(m_ShrinkFactor); + typedef otb::FltkFilterWatcher WatcherType; + WatcherType watcher(m_Shrink,wfull-200,hfull/2,200,20, "Generating Quicklook ..."); + m_Shrink->Update(); + } - // Create full windows - m_FullWidget = FullWidgetType::New(); - m_FullWidget->SetParent(this); - m_FullWidget->SetInput(m_InputImage); - if(m_UseImageOverlay) - { - m_FullWidget->SetInputOverlay(m_InputImageOverlay); - m_FullWidget->SetImageOverlayVisible(true); - } - m_FullWidget->Init(0,0,wfull,hfull,""); - m_FullWidget->box( FL_EMBOSSED_BOX ); - m_FullWidget->SetFormOverlayVisible(true); - - // Create the zoom window - m_ZoomWidget = ZoomWidgetType::New(); - m_ZoomWidget->SetParent(this); - m_ZoomWidget->SetZoomFactor(4.0); - m_ZoomWidget->SetInput(m_InputImage); - if(m_UseImageOverlay) - { - m_ZoomWidget->SetInputOverlay(m_InputImageOverlay); - m_ZoomWidget->SetImageOverlayVisible(true); - } - m_ZoomWidget->Init(0,0,m_ZoomMaxInitialSize,m_ZoomMaxInitialSize,""); - m_ZoomWidget->box( FL_EMBOSSED_BOX ); - m_ZoomWidget->SetFormOverlayVisible(true); + // Create full windows + m_FullWidget = FullWidgetType::New(); + m_FullWidget->SetParent(this); + m_FullWidget->SetInput(m_InputImage); + if (m_UseImageOverlay) + { + m_FullWidget->SetInputOverlay(m_InputImageOverlay); + m_FullWidget->SetImageOverlayVisible(true); + } + m_FullWidget->Init(0,0,wfull,hfull,""); + m_FullWidget->box( FL_EMBOSSED_BOX ); + m_FullWidget->SetFormOverlayVisible(true); + + // Create the zoom window + m_ZoomWidget = ZoomWidgetType::New(); + m_ZoomWidget->SetParent(this); + m_ZoomWidget->SetZoomFactor(4.0); + m_ZoomWidget->SetInput(m_InputImage); + if (m_UseImageOverlay) + { + m_ZoomWidget->SetInputOverlay(m_InputImageOverlay); + m_ZoomWidget->SetImageOverlayVisible(true); + } + m_ZoomWidget->Init(0,0,m_ZoomMaxInitialSize,m_ZoomMaxInitialSize,""); + m_ZoomWidget->box( FL_EMBOSSED_BOX ); + m_ZoomWidget->SetFormOverlayVisible(true); - // Create the zoom selection mode - if(m_ShowZoomWidget) - { - BoxPointerType zoomBox = BoxType::New(); - SizeType zoomBoxSize; - IndexType zoomBoxIndex; - zoomBoxSize[0]=(m_ZoomWidget->GetViewedRegion().GetSize()[0]+2); - zoomBoxSize[1]=(m_ZoomWidget->GetViewedRegion().GetSize()[1]+2); - zoomBoxIndex[0]=(m_ZoomWidget->GetViewedRegion().GetIndex()[0]-1); - zoomBoxIndex[1]=(m_ZoomWidget->GetViewedRegion().GetIndex()[1]-1); - zoomBox->SetIndex(zoomBoxIndex); - zoomBox->SetSize(zoomBoxSize); - zoomBox->SetColor(m_InterfaceBoxesColor); - m_InterfaceBoxesList->PushBack(zoomBox); - } + // Create the zoom selection mode + if (m_ShowZoomWidget) + { + BoxPointerType zoomBox = BoxType::New(); + SizeType zoomBoxSize; + IndexType zoomBoxIndex; + zoomBoxSize[0]=(m_ZoomWidget->GetViewedRegion().GetSize()[0]+2); + zoomBoxSize[1]=(m_ZoomWidget->GetViewedRegion().GetSize()[1]+2); + zoomBoxIndex[0]=(m_ZoomWidget->GetViewedRegion().GetIndex()[0]-1); + zoomBoxIndex[1]=(m_ZoomWidget->GetViewedRegion().GetIndex()[1]-1); + zoomBox->SetIndex(zoomBoxIndex); + zoomBox->SetSize(zoomBoxSize); + zoomBox->SetColor(m_InterfaceBoxesColor); + m_InterfaceBoxesList->PushBack(zoomBox); + } - if(m_UseScroll) - { - // Create the scroll window - m_ScrollWidget = ScrollWidgetType::New(); - m_ScrollWidget->SetInput(m_Shrink->GetOutput()); - m_ScrollWidget->SetParent(this); - m_ScrollWidget->Init(0,0,wscroll,hscroll,oss.str().c_str()); - m_ScrollWidget->box( FL_EMBOSSED_BOX ); - m_ScrollWidget->SetFormOverlayVisible(true); - m_ScrollWidget->SetSubSamplingRate(m_ShrinkFactor); - - if(m_UseImageOverlay) + if (m_UseScroll) + { + // Create the scroll window + m_ScrollWidget = ScrollWidgetType::New(); + m_ScrollWidget->SetInput(m_Shrink->GetOutput()); + m_ScrollWidget->SetParent(this); + m_ScrollWidget->Init(0,0,wscroll,hscroll,oss.str().c_str()); + m_ScrollWidget->box( FL_EMBOSSED_BOX ); + m_ScrollWidget->SetFormOverlayVisible(true); + m_ScrollWidget->SetSubSamplingRate(m_ShrinkFactor); + + if (m_UseImageOverlay) { m_ShrinkOverlay = OverlayShrinkFilterType::New(); m_ShrinkOverlay->SetInput(m_InputImageOverlay); @@ -329,463 +329,463 @@ namespace otb m_ScrollWidget->SetImageOverlayVisible(true); } - // Create the scroll selection box - BoxPointerType box = BoxType::New(); - SizeType scrollBoxSize; - IndexType scrollBoxIndex; - scrollBoxSize[0]=(m_FullWidget->GetViewedRegion().GetSize()[0]+2); - scrollBoxSize[1]=(m_FullWidget->GetViewedRegion().GetSize()[1]+2); - scrollBoxIndex[0]=(m_FullWidget->GetViewedRegion().GetIndex()[0]-1); - scrollBoxIndex[1]=(m_FullWidget->GetViewedRegion().GetIndex()[1]-1); - otbMsgDebugMacro(<<"Scroll box: "<<scrollBoxIndex<<" "<<scrollBoxSize); - box->SetSize(scrollBoxSize); - box->SetIndex(scrollBoxIndex); - box->SetColor(m_InterfaceBoxesColor); - m_InterfaceBoxesList->PushBack(box); - } + // Create the scroll selection box + BoxPointerType box = BoxType::New(); + SizeType scrollBoxSize; + IndexType scrollBoxIndex; + scrollBoxSize[0]=(m_FullWidget->GetViewedRegion().GetSize()[0]+2); + scrollBoxSize[1]=(m_FullWidget->GetViewedRegion().GetSize()[1]+2); + scrollBoxIndex[0]=(m_FullWidget->GetViewedRegion().GetIndex()[0]-1); + scrollBoxIndex[1]=(m_FullWidget->GetViewedRegion().GetIndex()[1]-1); + otbMsgDebugMacro(<<"Scroll box: "<<scrollBoxIndex<<" "<<scrollBoxSize); + box->SetSize(scrollBoxSize); + box->SetIndex(scrollBoxIndex); + box->SetColor(m_InterfaceBoxesColor); + m_InterfaceBoxesList->PushBack(box); + } - // Compute the normalization factors - ComputeNormalizationFactors(); + // Compute the normalization factors + ComputeNormalizationFactors(); - InitializeViewModel(); + InitializeViewModel(); - m_RedHistogramWidget->SetParent(this); - m_BlueHistogramWidget->SetParent(this); - m_GreenHistogramWidget->SetParent(this); + m_RedHistogramWidget->SetParent(this); + m_BlueHistogramWidget->SetParent(this); + m_GreenHistogramWidget->SetParent(this); - m_RedHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); - m_BlueHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); - m_GreenHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); + m_RedHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); + m_BlueHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); + m_GreenHistogramWidget->resize(0,0,m_FullMaxInitialSize/2,m_ZoomMaxInitialSize); - GenerateOverlayList(); + GenerateOverlayList(); - m_Built=true; - } - /// Set the image (VectorImage version) - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::SetImage(ImageType * img) + m_Built=true; +} +/// Set the image (VectorImage version) +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::SetImage(ImageType * img) +{ + m_InputImage = dynamic_cast<ImageType *>( img ); +} +/// Set the image overlay (VectorImage version) +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::SetImageOverlay(OverlayImageType * img) +{ + m_InputImageOverlay = dynamic_cast<OverlayImageType *>( img ); +} + + +template <class TPixel, class TLabel> +typename ImageViewerBase<TPixel,TLabel> +::ImageType * +ImageViewerBase<TPixel,TLabel> +::GetShrinkedImage(void) +{ + if (m_UseScroll) { - m_InputImage = dynamic_cast<ImageType *>( img ); + return m_Shrink->GetOutput(); } -/// Set the image overlay (VectorImage version) - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::SetImageOverlay(OverlayImageType * img) + else { - m_InputImageOverlay = dynamic_cast<OverlayImageType *>( img ); + return m_InputImage; } +} +/// Set the image (Image version) +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::SetImage(SingleImageType * img) +{ + m_VectorCastFilter = VectorCastFilterType::New(); + m_VectorCastFilter->SetInput(img); + m_VectorCastFilter->UpdateOutputInformation(); + m_InputImage = m_VectorCastFilter->GetOutput(); +} - - template <class TPixel, class TLabel> - typename ImageViewerBase<TPixel,TLabel> - ::ImageType * - ImageViewerBase<TPixel,TLabel> - ::GetShrinkedImage(void) - { - if(m_UseScroll) - { - return m_Shrink->GetOutput(); - } - else - { - return m_InputImage; - } - } - /// Set the image (Image version) - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::SetImage(SingleImageType * img) +/// Show the app +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::Show(void) +{ + //comment: std::cout<<"Entering show method"<<std::endl; + if (!m_Built) { - m_VectorCastFilter = VectorCastFilterType::New(); - m_VectorCastFilter->SetInput(img); - m_VectorCastFilter->UpdateOutputInformation(); - m_InputImage = m_VectorCastFilter->GetOutput(); + this->Build(); } - - /// Show the app - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::Show(void) + Fl::check(); + if (m_UseScroll && m_ShowScrollWidget) { - //comment: std::cout<<"Entering show method"<<std::endl; - if(!m_Built) - { - this->Build(); - } - Fl::check(); - if(m_UseScroll && m_ShowScrollWidget) - { - m_ScrollWidget->Show(); - } + m_ScrollWidget->Show(); + } - if(m_ShowFullWidget) - { - m_FullWidget->Show(); - } + if (m_ShowFullWidget) + { + m_FullWidget->Show(); + } - if(m_ShowZoomWidget) - { - m_ZoomWidget->Show(); - } - if(m_ShowHistograms) - { - m_RedHistogramWidget->show(); + if (m_ShowZoomWidget) + { + m_ZoomWidget->Show(); + } + if (m_ShowHistograms) + { + m_RedHistogramWidget->show(); - if(this->GetViewModel()== ScrollWidgetType::RGB) + if (this->GetViewModel()== ScrollWidgetType::RGB) { m_GreenHistogramWidget->show(); m_BlueHistogramWidget->show(); } - } - - Fl::check(); - //comment: std::cout<<"Leaving show method"<<std::endl; } - /** This is a helper class that performs a Show() and Fl::run() in order to ease - the use of the class for example in wrappings.*/ - template <class TPixel, class TLabel> - int - ImageViewerBase<TPixel,TLabel> - ::FlRun(void) + + Fl::check(); + //comment: std::cout<<"Leaving show method"<<std::endl; +} +/** This is a helper class that performs a Show() and Fl::run() in order to ease + the use of the class for example in wrappings.*/ +template <class TPixel, class TLabel> +int +ImageViewerBase<TPixel,TLabel> +::FlRun(void) +{ + this->Show(); + return Fl::run(); +} + + +/// Hide the app +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::Hide(void) +{ + Fl::check(); + if (m_UseScroll) { - this->Show(); - return Fl::run(); + m_ScrollWidget->hide(); } + m_FullWidget->hide(); + m_ZoomWidget->hide(); + m_RedHistogramWidget->hide(); - /// Hide the app - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::Hide(void) + if (this->GetViewModel()==ScrollWidgetType::RGB) { - Fl::check(); - if(m_UseScroll) - { - m_ScrollWidget->hide(); - } - m_FullWidget->hide(); - m_ZoomWidget->hide(); - - m_RedHistogramWidget->hide(); + m_GreenHistogramWidget->hide(); + m_BlueHistogramWidget->hide(); + } - if(this->GetViewModel()==ScrollWidgetType::RGB) - { - m_GreenHistogramWidget->hide(); - m_BlueHistogramWidget->hide(); - } + Fl::check(); - Fl::check(); +} +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::GenerateOverlayList(void) +{ + FormListPointerType new_list = FormListType::New(); + if (m_ShowZoomWidget) + { + BoxPointerType zoomBox = BoxType::New(); + SizeType zoomBoxSize; + IndexType zoomBoxIndex; + zoomBoxSize[0]=(m_ZoomWidget->GetViewedRegion().GetSize()[0]+2); + zoomBoxSize[1]=(m_ZoomWidget->GetViewedRegion().GetSize()[1]+2); + zoomBoxIndex[0]=(m_ZoomWidget->GetViewedRegion().GetIndex()[0]-1); + zoomBoxIndex[1]=(m_ZoomWidget->GetViewedRegion().GetIndex()[1]-1); + zoomBox->SetIndex(zoomBoxIndex); + zoomBox->SetSize(zoomBoxSize); + zoomBox->SetColor(m_InterfaceBoxesColor); + m_InterfaceBoxesList->SetNthElement(0,zoomBox); } - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::GenerateOverlayList(void) + if (m_UseScroll) { - FormListPointerType new_list = FormListType::New(); - if(m_ShowZoomWidget) - { - BoxPointerType zoomBox = BoxType::New(); - SizeType zoomBoxSize; - IndexType zoomBoxIndex; - zoomBoxSize[0]=(m_ZoomWidget->GetViewedRegion().GetSize()[0]+2); - zoomBoxSize[1]=(m_ZoomWidget->GetViewedRegion().GetSize()[1]+2); - zoomBoxIndex[0]=(m_ZoomWidget->GetViewedRegion().GetIndex()[0]-1); - zoomBoxIndex[1]=(m_ZoomWidget->GetViewedRegion().GetIndex()[1]-1); - zoomBox->SetIndex(zoomBoxIndex); - zoomBox->SetSize(zoomBoxSize); - zoomBox->SetColor(m_InterfaceBoxesColor); - m_InterfaceBoxesList->SetNthElement(0,zoomBox); - } - - if(m_UseScroll) + BoxPointerType box = BoxType::New(); + SizeType scrollBoxSize; + IndexType scrollBoxIndex; + scrollBoxSize[0]=(m_FullWidget->GetViewedRegion().GetSize()[0]+2); + scrollBoxSize[1]=(m_FullWidget->GetViewedRegion().GetSize()[1]+2); + scrollBoxIndex[0]=(m_FullWidget->GetViewedRegion().GetIndex()[0]-1); + scrollBoxIndex[1]=(m_FullWidget->GetViewedRegion().GetIndex()[1]-1); + box->SetSize(scrollBoxSize); + box->SetIndex(scrollBoxIndex); + box->SetColor(m_InterfaceBoxesColor); + int idx; + if (m_ShowZoomWidget) { - BoxPointerType box = BoxType::New(); - SizeType scrollBoxSize; - IndexType scrollBoxIndex; - scrollBoxSize[0]=(m_FullWidget->GetViewedRegion().GetSize()[0]+2); - scrollBoxSize[1]=(m_FullWidget->GetViewedRegion().GetSize()[1]+2); - scrollBoxIndex[0]=(m_FullWidget->GetViewedRegion().GetIndex()[0]-1); - scrollBoxIndex[1]=(m_FullWidget->GetViewedRegion().GetIndex()[1]-1); - box->SetSize(scrollBoxSize); - box->SetIndex(scrollBoxIndex); - box->SetColor(m_InterfaceBoxesColor); - int idx; - if(m_ShowZoomWidget) - { - idx = 1; + idx = 1; + } + else + { + idx = 0; + } + m_InterfaceBoxesList->SetNthElement(idx,box); } - else + + for (FormListIteratorType it1 = m_InterfaceBoxesList->Begin(); + it1!=m_InterfaceBoxesList->End();++it1) { - idx = 0; + new_list->PushBack(it1.Get()); } - m_InterfaceBoxesList->SetNthElement(idx,box); - } - for(FormListIteratorType it1 = m_InterfaceBoxesList->Begin(); - it1!=m_InterfaceBoxesList->End();++it1) - { - new_list->PushBack(it1.Get()); - } - - for(PolygonListIteratorType it2 = m_PolygonROIList->Begin(); - it2!=m_PolygonROIList->End();++it2) - { - ImageWidgetPolygonFormPointerType new_poly = ImageWidgetPolygonFormType::New(); - new_poly->SetPolygon(it2.Get()); - - ColorType color; - - if(this->GetROIColorMapEntry(it2.Get()->GetValue(),color)) - { - new_poly->SetColor(color); - } - else - { - new_poly->SetColor(m_DefaultROIColor); - } - - for(PolygonIteratorType pIt = it2.Get()->GetVertexList()->Begin(); - pIt != it2.Get()->GetVertexList()->End();++pIt) - { - ImageWidgetCircleFormPointerType new_circle = ImageWidgetCircleFormType::New(); - - new_circle->SetCenter(pIt.Value()); - new_circle->SetRadius(2); - new_circle->SetSolid(false); - new_circle->SetColor(m_InterfaceBoxesColor); - new_list->PushBack(new_circle); - - } - new_list->PushBack(new_poly); - } - - for(PathListIteratorType it2 = m_PathList->Begin(); - it2!=m_PathList->End();++it2) - { - ImageWidgetPolylineFormPointerType new_line = ImageWidgetPolylineFormType::New(); - new_line->SetPolyline(it2.Get()); -// new_line->SetInternalValueToAlphaChannel(true); + for (PolygonListIteratorType it2 = m_PolygonROIList->Begin(); + it2!=m_PolygonROIList->End();++it2) + { + ImageWidgetPolygonFormPointerType new_poly = ImageWidgetPolygonFormType::New(); + new_poly->SetPolygon(it2.Get()); - new_line->SetColor(m_DefaultROIColor); - new_line->SetLineWidth(m_LineWidth); + ColorType color; - new_list->PushBack(new_line); - } + if (this->GetROIColorMapEntry(it2.Get()->GetValue(),color)) + { + new_poly->SetColor(color); + } + else + { + new_poly->SetColor(m_DefaultROIColor); + } + for (PolygonIteratorType pIt = it2.Get()->GetVertexList()->Begin(); + pIt != it2.Get()->GetVertexList()->End();++pIt) + { + ImageWidgetCircleFormPointerType new_circle = ImageWidgetCircleFormType::New(); - if(m_UseScroll) - { - m_ScrollWidget->SetFormListOverlay(new_list); - } + new_circle->SetCenter(pIt.Value()); + new_circle->SetRadius(2); + new_circle->SetSolid(false); + new_circle->SetColor(m_InterfaceBoxesColor); + new_list->PushBack(new_circle); - m_FullWidget->SetFormListOverlay(new_list); - m_ZoomWidget->SetFormListOverlay(new_list); + } + new_list->PushBack(new_poly); } + for (PathListIteratorType it2 = m_PathList->Begin(); + it2!=m_PathList->End();++it2) + { + ImageWidgetPolylineFormPointerType new_line = ImageWidgetPolylineFormType::New(); + new_line->SetPolyline(it2.Get()); +// new_line->SetInternalValueToAlphaChannel(true); + + new_line->SetColor(m_DefaultROIColor); + new_line->SetLineWidth(m_LineWidth); + + new_list->PushBack(new_line); + } - /// Update the display - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::Update(void) + if (m_UseScroll) { - m_Updating = true; - //comment: std::cout<<"Update: "<<m_Label<<" Updating flag on"<<std::endl; - GenerateOverlayList(); - Fl::check(); - UpdateScrollWidget(); - UpdateFullWidget(); - UpdateZoomWidget(); + m_ScrollWidget->SetFormListOverlay(new_list); + } - // Update histogram widgets + m_FullWidget->SetFormListOverlay(new_list); + m_ZoomWidget->SetFormListOverlay(new_list); +} - m_RedHistogramWidget->redraw(); - if(this->GetViewModel()==ScrollWidgetType::RGB) - { - m_GreenHistogramWidget->redraw(); - m_BlueHistogramWidget->redraw(); - } +/// Update the display +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::Update(void) +{ + m_Updating = true; + //comment: std::cout<<"Update: "<<m_Label<<" Updating flag on"<<std::endl; + GenerateOverlayList(); + Fl::check(); + UpdateScrollWidget(); + UpdateFullWidget(); + UpdateZoomWidget(); - // update the linked viewer - typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); - typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); + // Update histogram widgets - while(linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) - { - if(!linkedIt.Get()->GetUpdating() && linkedIt.Get()->GetBuilt()) + m_RedHistogramWidget->redraw(); + + if (this->GetViewModel()==ScrollWidgetType::RGB) { - linkedIt.Get()->Update(); - } - ++linkedIt; - ++offIt; + m_GreenHistogramWidget->redraw(); + m_BlueHistogramWidget->redraw(); + } + + + // update the linked viewer + typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); + typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); + + while (linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) + { + if (!linkedIt.Get()->GetUpdating() && linkedIt.Get()->GetBuilt()) + { + linkedIt.Get()->Update(); } + ++linkedIt; + ++offIt; + } Fl::check(); //comment: std::cout<<"Update: "<<m_Label<<" Updating flag off"<<std::endl; m_Updating = false; +} + +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::ReportPixel(IndexType index) +{ + //comment: std::cout<<"Entering report pixel: "<<m_Label<<std::endl; + if (m_PixLocOutput == NULL) + { + //comment: std::cout<<"PixLocOutput == NULL, returning ..."<<std::endl; + return; } + itk::OStringStream oss; + oss<<index<<" (image position)"<<std::endl; + PointType point; + m_InputImage->TransformIndexToPhysicalPoint(index,point); + oss << std::setprecision(15) << point<<" (physical coordinates)"<<std::endl; - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::ReportPixel(IndexType index) + if (m_InputImage->GetBufferedRegion().IsInside(index)) { - //comment: std::cout<<"Entering report pixel: "<<m_Label<<std::endl; - if(m_PixLocOutput == NULL) + //comment: std::cout<<"Index: "<<index<<std::endl; + + typename ImageType::PixelType newPixel = m_InputImage->GetPixel(index); + + if (this->GetViewModel() == ScrollWidgetType::RGB || this->GetViewModel() == ScrollWidgetType::GRAYSCALE) { - //comment: std::cout<<"PixLocOutput == NULL, returning ..."<<std::endl; - return; + oss<<newPixel<<" ("<<m_Label<<" pixel values)"<<std::endl; } - itk::OStringStream oss; - oss<<index<<" (image position)"<<std::endl; - PointType point; - m_InputImage->TransformIndexToPhysicalPoint(index,point); - oss << std::setprecision(15) << point<<" (physical coordinates)"<<std::endl; + else if (this->GetViewModel() == ScrollWidgetType::COMPLEX_MODULUS) + { + double re = static_cast<double>(newPixel[m_RedChannelIndex]); + double im = static_cast<double>(newPixel[m_GreenChannelIndex]); + double modulus = vcl_sqrt(re*re+im*im); + oss<<modulus<<std::setprecision(3)<<" ("<<m_Label<<" modulus value)" <<std::endl; - if(m_InputImage->GetBufferedRegion().IsInside(index)) + } + else if (this->GetViewModel() == ScrollWidgetType::COMPLEX_PHASE) { - //comment: std::cout<<"Index: "<<index<<std::endl; + double re = static_cast<double>(newPixel[m_RedChannelIndex]); + double im = static_cast<double>(newPixel[m_GreenChannelIndex]); + double phase = vcl_atan2(im,re); + oss<<phase<<std::setprecision(3)<<" ("<<m_Label<<" phase value)"<<std::endl; + } + } + else + { + IndexType shrinkIndex; + shrinkIndex[0]=index[0]/m_ShrinkFactor; + shrinkIndex[1]=index[1]/m_ShrinkFactor; - typename ImageType::PixelType newPixel = m_InputImage->GetPixel(index); + if (m_Shrink->GetOutput()->GetBufferedRegion().IsInside(shrinkIndex)) + { + typename ImageType::PixelType newPixel = m_Shrink->GetOutput()->GetPixel(shrinkIndex); + oss<<newPixel<<" ("<<m_Label<<" pixel values)"<<std::endl; + } + } - if(this->GetViewModel() == ScrollWidgetType::RGB || this->GetViewModel() == ScrollWidgetType::GRAYSCALE) - { - oss<<newPixel<<" ("<<m_Label<<" pixel values)"<<std::endl; - } - else if(this->GetViewModel() == ScrollWidgetType::COMPLEX_MODULUS) - { - double re = static_cast<double>(newPixel[m_RedChannelIndex]); - double im = static_cast<double>(newPixel[m_GreenChannelIndex]); - double modulus = vcl_sqrt(re*re+im*im); - oss<<modulus<<std::setprecision(3)<<" ("<<m_Label<<" modulus value)" <<std::endl; + typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); + typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); - } - else if(this->GetViewModel() == ScrollWidgetType::COMPLEX_PHASE) - { - double re = static_cast<double>(newPixel[m_RedChannelIndex]); - double im = static_cast<double>(newPixel[m_GreenChannelIndex]); - double phase = vcl_atan2(im,re); - oss<<phase<<std::setprecision(3)<<" ("<<m_Label<<" phase value)"<<std::endl; - } + while (linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) + { + IndexType currentIndex = index + (*offIt); + //comment: std::cout<<"CurrentIndex: "<<currentIndex<<std::endl; + if (linkedIt.Get()->GetInputImage()->GetBufferedRegion().IsInside(currentIndex)) + { + typename ImageType::PixelType newPixel = linkedIt.Get()->GetInputImage()->GetPixel(currentIndex); + oss<<newPixel<<" ("<<linkedIt.Get()->GetLabel()<<" pixel values)"<<std::endl; } else { IndexType shrinkIndex; - shrinkIndex[0]=index[0]/m_ShrinkFactor; - shrinkIndex[1]=index[1]/m_ShrinkFactor; + shrinkIndex[0]=currentIndex[0]/m_ShrinkFactor; + shrinkIndex[1]=currentIndex[1]/m_ShrinkFactor; - if(m_Shrink->GetOutput()->GetBufferedRegion().IsInside(shrinkIndex)) + if (linkedIt.Get()->GetShrinkedImage()->GetBufferedRegion().IsInside(shrinkIndex)) { - typename ImageType::PixelType newPixel = m_Shrink->GetOutput()->GetPixel(shrinkIndex); - oss<<newPixel<<" ("<<m_Label<<" pixel values)"<<std::endl; - } - } - - typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); - typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); - - while(linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) - { - IndexType currentIndex = index + (*offIt); - //comment: std::cout<<"CurrentIndex: "<<currentIndex<<std::endl; - if(linkedIt.Get()->GetInputImage()->GetBufferedRegion().IsInside(currentIndex)) - { - typename ImageType::PixelType newPixel = linkedIt.Get()->GetInputImage()->GetPixel(currentIndex); + typename ImageType::PixelType newPixel = linkedIt.Get()->GetShrinkedImage()->GetPixel(shrinkIndex); oss<<newPixel<<" ("<<linkedIt.Get()->GetLabel()<<" pixel values)"<<std::endl; } - else - { - IndexType shrinkIndex; - shrinkIndex[0]=currentIndex[0]/m_ShrinkFactor; - shrinkIndex[1]=currentIndex[1]/m_ShrinkFactor; - - if(linkedIt.Get()->GetShrinkedImage()->GetBufferedRegion().IsInside(shrinkIndex)) - { - typename ImageType::PixelType newPixel = linkedIt.Get()->GetShrinkedImage()->GetPixel(shrinkIndex); - oss<<newPixel<<" ("<<linkedIt.Get()->GetLabel()<<" pixel values)"<<std::endl; - } - } - ++linkedIt; - ++offIt; - } - if(oss.good()) - { - m_PixLocOutput->value(oss.str().c_str()); - m_PixLocOutput->redraw(); - Fl::check(); } - //comment: std::cout<<"Leaving report pixel: "<<m_Label<<std::endl; + ++linkedIt; + ++offIt; } - - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::ClearPixLocVal(void) + if (oss.good()) { - if(m_PixLocOutput == NULL) - { - //comment: std::cout<<"PixLocOutput == NULL, returning ..."<<std::endl; - return; - } - m_PixLocOutput->value(""); + m_PixLocOutput->value(oss.str().c_str()); m_PixLocOutput->redraw(); Fl::check(); } + //comment: std::cout<<"Leaving report pixel: "<<m_Label<<std::endl; +} + +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::ClearPixLocVal(void) +{ + if (m_PixLocOutput == NULL) + { + //comment: std::cout<<"PixLocOutput == NULL, returning ..."<<std::endl; + return; + } + m_PixLocOutput->value(""); + m_PixLocOutput->redraw(); + Fl::check(); +} - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::SetImageOverlayOpacity(unsigned char opacity) +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::SetImageOverlayOpacity(unsigned char opacity) +{ + if (m_UseImageOverlay) { - if(m_UseImageOverlay) - { - m_FullWidget->SetImageOverlayOpacity(opacity); - m_ZoomWidget->SetImageOverlayOpacity(opacity); + m_FullWidget->SetImageOverlayOpacity(opacity); + m_ZoomWidget->SetImageOverlayOpacity(opacity); - if(m_UseScroll) + if (m_UseScroll) { m_ScrollWidget->SetImageOverlayOpacity(opacity); } - } } +} - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::UpdateZoomWidget(void) - { - m_ZoomWidget->redraw(); - } +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::UpdateZoomWidget(void) +{ + m_ZoomWidget->redraw(); +} - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::UpdateFullWidget(void) - { - m_FullWidget->redraw(); - } +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::UpdateFullWidget(void) +{ + m_FullWidget->redraw(); +} - template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> - ::UpdateScrollWidget(void) +template <class TPixel, class TLabel> +void +ImageViewerBase<TPixel,TLabel> +::UpdateScrollWidget(void) +{ + if (m_UseScroll) { - if(m_UseScroll) - { - m_ScrollWidget->redraw(); - } + m_ScrollWidget->redraw(); } +} template <class TPixel, class TLabel> typename ImageViewerBase<TPixel,TLabel> @@ -794,37 +794,37 @@ ImageViewerBase<TPixel,TLabel> ::ComputeConstrainedRegion(RegionType smallRegion, RegionType bigRegion) { // This function assumes that smallRegion is inside huge region - if(smallRegion.GetSize()[0]>bigRegion.GetSize()[0] - ||smallRegion.GetSize()[1]>bigRegion.GetSize()[1]) - { - itkExceptionMacro("Small region not inside big region !"); - } - else - { - RegionType resp; - IndexType index = smallRegion.GetIndex(); - SizeType size = smallRegion.GetSize(); - - if(smallRegion.GetIndex()[0]<bigRegion.GetIndex()[0]) + if (smallRegion.GetSize()[0]>bigRegion.GetSize()[0] + ||smallRegion.GetSize()[1]>bigRegion.GetSize()[1]) { - index[0]=bigRegion.GetIndex()[0]; + itkExceptionMacro("Small region not inside big region !"); } - if(smallRegion.GetIndex()[1]<bigRegion.GetIndex()[1]) - { - index[1]=bigRegion.GetIndex()[1]; - } - if(index[0]+size[0]>=bigRegion.GetIndex()[0]+bigRegion.GetSize()[0]) - { - index[0]=bigRegion.GetIndex()[0]+bigRegion.GetSize()[0]-size[0]; - } - if(index[1]+size[1]>=bigRegion.GetIndex()[1]+bigRegion.GetSize()[1]) + else { - index[1]=bigRegion.GetIndex()[1]+bigRegion.GetSize()[1]-size[1]; - } - resp.SetSize(size); - resp.SetIndex(index); - return resp; + RegionType resp; + IndexType index = smallRegion.GetIndex(); + SizeType size = smallRegion.GetSize(); + + if (smallRegion.GetIndex()[0]<bigRegion.GetIndex()[0]) + { + index[0]=bigRegion.GetIndex()[0]; } + if (smallRegion.GetIndex()[1]<bigRegion.GetIndex()[1]) + { + index[1]=bigRegion.GetIndex()[1]; + } + if (index[0]+size[0]>=bigRegion.GetIndex()[0]+bigRegion.GetSize()[0]) + { + index[0]=bigRegion.GetIndex()[0]+bigRegion.GetSize()[0]-size[0]; + } + if (index[1]+size[1]>=bigRegion.GetIndex()[1]+bigRegion.GetSize()[1]) + { + index[1]=bigRegion.GetIndex()[1]+bigRegion.GetSize()[1]-size[1]; + } + resp.SetSize(size); + resp.SetIndex(index); + return resp; + } } template <class TPixel, class TLabel> @@ -847,57 +847,57 @@ ImageViewerBase<TPixel,TLabel> typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); - while(linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) - { - if(!linkedIt.Get()->GetUpdating()) + while (linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) { - IndexType linkedIndex; - linkedIndex[0] = clickedIndex[0]+(*offIt)[0]; - linkedIndex[1] = clickedIndex[1]+(*offIt)[1]; - linkedIt.Get()->ChangeFullViewedRegion(linkedIndex); - } - ++offIt; - ++linkedIt; + if (!linkedIt.Get()->GetUpdating()) + { + IndexType linkedIndex; + linkedIndex[0] = clickedIndex[0]+(*offIt)[0]; + linkedIndex[1] = clickedIndex[1]+(*offIt)[1]; + linkedIt.Get()->ChangeFullViewedRegion(linkedIndex); } + ++offIt; + ++linkedIt; + } //comment: std::cout<<"ChangeFullViewedRegion: "<<m_Label<<" Updating flag off"<<std::endl; m_Updating = false; } template <class TPixel, class TLabel> - void - ImageViewerBase<TPixel,TLabel> +void +ImageViewerBase<TPixel,TLabel> ::ChangeZoomViewedRegion(IndexType clickedIndex) { m_Updating = true; //comment: std::cout<<"ChangeZoomViewedRegion: "<<m_Label<<" Updating flag on"<<std::endl; - if(m_ShowZoomWidget) - { - RegionType region = m_ZoomWidget->GetViewedRegion(); - IndexType newIndex; - newIndex[0]=clickedIndex[0]-region.GetSize()[0]/2; - newIndex[1]=clickedIndex[1]-region.GetSize()[1]/2; + if (m_ShowZoomWidget) + { + RegionType region = m_ZoomWidget->GetViewedRegion(); + IndexType newIndex; + newIndex[0]=clickedIndex[0]-region.GetSize()[0]/2; + newIndex[1]=clickedIndex[1]-region.GetSize()[1]/2; - region.SetIndex(newIndex); - RegionType newRegion = ComputeConstrainedRegion(region,m_FullWidget->GetViewedRegion()); - m_ZoomWidget->SetZoomUpperLeftCorner(newRegion.GetIndex()); + region.SetIndex(newIndex); + RegionType newRegion = ComputeConstrainedRegion(region,m_FullWidget->GetViewedRegion()); + m_ZoomWidget->SetZoomUpperLeftCorner(newRegion.GetIndex()); - typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); - typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); + typename ViewerListType::Iterator linkedIt = m_LinkedViewerList->Begin(); + typename OffsetListType::iterator offIt = m_LinkedViewerOffsetList.begin(); - while(linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) - { - if(!linkedIt.Get()->GetUpdating()) + while (linkedIt!=m_LinkedViewerList->End()&&offIt!=m_LinkedViewerOffsetList.end()) + { + if (!linkedIt.Get()->GetUpdating()) { IndexType linkedIndex; linkedIndex[0] = clickedIndex[0]+(*offIt)[0]; linkedIndex[1] = clickedIndex[1]+(*offIt)[1]; linkedIt.Get()->ChangeZoomViewedRegion(linkedIndex); } - ++offIt; - ++linkedIt; - } + ++offIt; + ++linkedIt; } + } //comment: std::cout<<"ChangeZoomViewedRegion: "<<m_Label<<" Updating flag off"<<std::endl; m_Updating = false; } @@ -910,28 +910,28 @@ ImageViewerBase<TPixel,TLabel> //comment: std::cout<<"Entering link: "<<viewer->GetLabel()<<" flag: "<<backwardLinkFlag<<std::endl; // Search if this viewer is already linked typename ViewerListType::Iterator it = m_LinkedViewerList->Begin(); - while(it!=m_LinkedViewerList->End()) - { - if(it.Get()==viewer) + while (it!=m_LinkedViewerList->End()) { - otbMsgDebugMacro(<<"This viewer is already linked !"); - return; - } - ++it; + if (it.Get()==viewer) + { + otbMsgDebugMacro(<<"This viewer is already linked !"); + return; } + ++it; + } // If not, add it with its offset m_LinkedViewerList->PushBack(viewer); m_LinkedViewerOffsetList.push_back(offset); // If backward link flag is set, add the backward link - if(backwardLinkFlag) - { - OffsetType invertOffset; - invertOffset[0]=-offset[0]; - invertOffset[1]=-offset[1]; - viewer->Link(this,invertOffset,false); - } - //comment: std::cout<<"Leaving link: "<<viewer->GetLabel()<<" flag: "<<backwardLinkFlag<<std::endl; + if (backwardLinkFlag) + { + OffsetType invertOffset; + invertOffset[0]=-offset[0]; + invertOffset[1]=-offset[1]; + viewer->Link(this,invertOffset,false); + } + //comment: std::cout<<"Leaving link: "<<viewer->GetLabel()<<" flag: "<<backwardLinkFlag<<std::endl; } template <class TPixel, class TLabel> @@ -961,28 +961,28 @@ ImageViewerBase<TPixel,TLabel> bool found = false; // Search the given viewer in the linked list typename ViewerListType::Iterator it = m_LinkedViewerList->Begin(); - while(!found&&it!=m_LinkedViewerList->End()) - { - if(it.Get()==viewer) - { - found = true; - } - else + while (!found&&it!=m_LinkedViewerList->End()) { - ++counter; - } - ++it; + if (it.Get()==viewer) + { + found = true; } + else + { + ++counter; + } + ++it; + } // If found, erase m_LinkedViewerList->Erase(counter); m_LinkedViewerOffsetList.erase(m_LinkedViewerOffsetList.begin()+counter); // If backward link flag is set, remove the backward link - if(backwardLinkFlag) - { - viewer->Unlink(this,false); - } + if (backwardLinkFlag) + { + viewer->Unlink(this,false); + } } template <class TPixel, class TLabel> void @@ -1000,15 +1000,15 @@ ImageViewerBase<TPixel,TLabel> { int counter = 0; typename ViewerListType::Iterator it = m_LinkedViewerList->Begin(); - while(it!=m_LinkedViewerList->End()) - { - if(it.Get()==viewer) + while (it!=m_LinkedViewerList->End()) { - return counter; - } - ++counter; - ++it; + if (it.Get()==viewer) + { + return counter; } + ++counter; + ++it; + } return -1; } @@ -1018,11 +1018,11 @@ ImageViewerBase<TPixel,TLabel> ::ClearLinks(void) { typename ViewerListType::Iterator it = m_LinkedViewerList->Begin(); - while(it!=m_LinkedViewerList->End()) - { - it.Get()->Unlink(this,false); - ++it; - } + while (it!=m_LinkedViewerList->End()) + { + it.Get()->Unlink(this,false); + ++it; + } m_LinkedViewerList->Clear(); m_LinkedViewerOffsetList.clear(); } @@ -1051,20 +1051,20 @@ void ImageViewerBase<TPixel,TLabel> ::SetViewModel(ViewModelType viewModel) { - switch(viewModel) - { - case ScrollWidgetType::RGB: - { + switch (viewModel) + { + case ScrollWidgetType::RGB: + { // if(m_InputImage->GetNumberOfComponentsPerPixel()>2) // { //NOTE: No reason to prevent a 2 bands image to be displayed in RGB // and the image is not necessarily loaded at that time. - if(m_UseScroll) - { - m_ScrollWidget->SetViewModel(viewModel); - m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); - m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); - m_ScrollWidget->SetBlueChannelIndex(m_BlueChannelIndex); - } + if (m_UseScroll) + { + m_ScrollWidget->SetViewModel(viewModel); + m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); + m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); + m_ScrollWidget->SetBlueChannelIndex(m_BlueChannelIndex); + } m_FullWidget->SetViewModel(viewModel); m_ZoomWidget->SetViewModel(viewModel); m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); @@ -1111,89 +1111,89 @@ ImageViewerBase<TPixel,TLabel> m_GreenHistogramWidget->SetTextColor(green); break; // } - } - case ScrollWidgetType::GRAYSCALE: + } + case ScrollWidgetType::GRAYSCALE: + { + if (m_UseScroll) { - if(m_UseScroll) - { - m_ScrollWidget->SetViewModel(viewModel); - m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); - } - m_FullWidget->SetViewModel(viewModel); - m_ZoomWidget->SetViewModel(viewModel); - m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); - m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); - - ComputeNormalizationFactors(); - - typename HistogramWidgetType::ColorType gray; - gray.Fill(0.5); - - m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(m_RedChannelIndex)->GetOutput()); - m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(m_RedChannelIndex)); - m_RedHistogramWidget->SetLabel("Grayscale channel"); - m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); - m_RedHistogramWidget->SetHistogramColor(gray); - m_RedHistogramWidget->SetTextColor(gray); - break; + m_ScrollWidget->SetViewModel(viewModel); + m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); } - case ScrollWidgetType::COMPLEX_MODULUS: + m_FullWidget->SetViewModel(viewModel); + m_ZoomWidget->SetViewModel(viewModel); + m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); + m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); + + ComputeNormalizationFactors(); + + typename HistogramWidgetType::ColorType gray; + gray.Fill(0.5); + + m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(m_RedChannelIndex)->GetOutput()); + m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(m_RedChannelIndex)); + m_RedHistogramWidget->SetLabel("Grayscale channel"); + m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); + m_RedHistogramWidget->SetHistogramColor(gray); + m_RedHistogramWidget->SetTextColor(gray); + break; + } + case ScrollWidgetType::COMPLEX_MODULUS: + { + if (m_UseScroll) { - if(m_UseScroll) - { - m_ScrollWidget->SetViewModel(viewModel); - m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); - m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); - } - m_FullWidget->SetViewModel(viewModel); - m_ZoomWidget->SetViewModel(viewModel); - m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); - m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); - m_ZoomWidget->SetGreenChannelIndex(m_GreenChannelIndex); - m_FullWidget->SetGreenChannelIndex(m_GreenChannelIndex); - - ComputeNormalizationFactors(); - - typename HistogramWidgetType::ColorType gray; - gray.Fill(0.5); - - m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(0)->GetOutput()); - m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(0)); - m_RedHistogramWidget->SetLabel("Modulus"); - m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); - m_RedHistogramWidget->SetHistogramColor(gray); - m_RedHistogramWidget->SetTextColor(gray); - break; + m_ScrollWidget->SetViewModel(viewModel); + m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); + m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); } - case ScrollWidgetType::COMPLEX_PHASE: + m_FullWidget->SetViewModel(viewModel); + m_ZoomWidget->SetViewModel(viewModel); + m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); + m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); + m_ZoomWidget->SetGreenChannelIndex(m_GreenChannelIndex); + m_FullWidget->SetGreenChannelIndex(m_GreenChannelIndex); + + ComputeNormalizationFactors(); + + typename HistogramWidgetType::ColorType gray; + gray.Fill(0.5); + + m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(0)->GetOutput()); + m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(0)); + m_RedHistogramWidget->SetLabel("Modulus"); + m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); + m_RedHistogramWidget->SetHistogramColor(gray); + m_RedHistogramWidget->SetTextColor(gray); + break; + } + case ScrollWidgetType::COMPLEX_PHASE: + { + if (m_UseScroll) { - if(m_UseScroll) - { - m_ScrollWidget->SetViewModel(viewModel); - m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); - m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); - } - m_FullWidget->SetViewModel(viewModel); - m_ZoomWidget->SetViewModel(viewModel); - m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); - m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); - m_ZoomWidget->SetGreenChannelIndex(m_GreenChannelIndex); - m_FullWidget->SetGreenChannelIndex(m_GreenChannelIndex); - - ComputeNormalizationFactors(); - - typename HistogramWidgetType::ColorType gray; - gray.Fill(0.5); - - m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(0)->GetOutput()); - m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(0)); - m_RedHistogramWidget->SetLabel("Phase"); - m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); - m_RedHistogramWidget->SetHistogramColor(gray); - m_RedHistogramWidget->SetTextColor(gray); - break; - } + m_ScrollWidget->SetViewModel(viewModel); + m_ScrollWidget->SetRedChannelIndex(m_RedChannelIndex); + m_ScrollWidget->SetGreenChannelIndex(m_GreenChannelIndex); } + m_FullWidget->SetViewModel(viewModel); + m_ZoomWidget->SetViewModel(viewModel); + m_ZoomWidget->SetRedChannelIndex(m_RedChannelIndex); + m_FullWidget->SetRedChannelIndex(m_RedChannelIndex); + m_ZoomWidget->SetGreenChannelIndex(m_GreenChannelIndex); + m_FullWidget->SetGreenChannelIndex(m_GreenChannelIndex); + + ComputeNormalizationFactors(); + + typename HistogramWidgetType::ColorType gray; + gray.Fill(0.5); + + m_RedHistogramWidget->SetHistogram(m_HistogramGeneratorList->GetNthElement(0)->GetOutput()); + m_RedHistogramWidget->SetTransferFunction(m_TransferFunctionList->GetNthElement(0)); + m_RedHistogramWidget->SetLabel("Phase"); + m_RedHistogramWidget->SetTransferFunctionLabel("Affine"); + m_RedHistogramWidget->SetHistogramColor(gray); + m_RedHistogramWidget->SetTextColor(gray); + break; + } + } } template<class TPixel, class TLabel> @@ -1201,14 +1201,14 @@ void ImageViewerBase<TPixel,TLabel> ::InitializeViewModel(void) { - if(m_InputImage->GetNumberOfComponentsPerPixel()>2) - { - this->SetViewModel(ScrollWidgetType::RGB); - } - else - { - this->SetViewModel(ScrollWidgetType::GRAYSCALE); - } + if (m_InputImage->GetNumberOfComponentsPerPixel()>2) + { + this->SetViewModel(ScrollWidgetType::RGB); + } + else + { + this->SetViewModel(ScrollWidgetType::GRAYSCALE); + } } template<class TPixel, class TLabel> @@ -1218,10 +1218,10 @@ ImageViewerBase<TPixel,TLabel> { m_FullWidget->Reset(); m_ZoomWidget->Reset(); - if(m_UseScroll) - { - m_ScrollWidget->Reset(); - } + if (m_UseScroll) + { + m_ScrollWidget->Reset(); + } } @@ -1231,17 +1231,17 @@ ImageViewerBase<TPixel,TLabel> ::ChangeTransferFunctions(void) { m_TransferFunctionList->SetNthElement(m_RedChannelIndex, m_RedHistogramWidget->GetTransferFunction()); - if(m_FullWidget->GetViewModel()==ScrollWidgetType::RGB) - { - m_TransferFunctionList->SetNthElement(m_BlueChannelIndex, m_BlueHistogramWidget->GetTransferFunction()); - m_TransferFunctionList->SetNthElement(m_GreenChannelIndex, m_GreenHistogramWidget->GetTransferFunction()); - } + if (m_FullWidget->GetViewModel()==ScrollWidgetType::RGB) + { + m_TransferFunctionList->SetNthElement(m_BlueChannelIndex, m_BlueHistogramWidget->GetTransferFunction()); + m_TransferFunctionList->SetNthElement(m_GreenChannelIndex, m_GreenHistogramWidget->GetTransferFunction()); + } m_FullWidget->ClearBufferedRegion(); m_ZoomWidget->ClearBufferedRegion(); - if(m_UseScroll) - { - m_ScrollWidget->ClearBufferedRegion(); - } + if (m_UseScroll) + { + m_ScrollWidget->ClearBufferedRegion(); + } } template<class TPixel, class TLabel> @@ -1268,11 +1268,11 @@ ImageViewerBase<TPixel,TLabel> typename ROIColorMapType::iterator it = m_ROIColorMap.find(label); bool resp = false; - if(it!=m_ROIColorMap.end()) - { - color = it->second; - resp = true; - } + if (it!=m_ROIColorMap.end()) + { + color = it->second; + resp = true; + } return resp; } diff --git a/Code/Visu/otbImageViewerFullResolutionEventsInterface.h b/Code/Visu/otbImageViewerFullResolutionEventsInterface.h index 6c3671dbe3dc3c384ab1955cdb97d1fe23843494..f888940c32ed9494521008581544b850326e1826 100644 --- a/Code/Visu/otbImageViewerFullResolutionEventsInterface.h +++ b/Code/Visu/otbImageViewerFullResolutionEventsInterface.h @@ -25,9 +25,9 @@ PURPOSE. See the above copyright notices for more information. namespace otb { class ImageViewerFullResolutionEventsInterface -: public itk::Object + : public itk::Object { - public: +public: /** Standard class typedefs */ typedef ImageViewerFullResolutionEventsInterface Self; typedef itk::Object Superclass; @@ -44,20 +44,20 @@ class ImageViewerFullResolutionEventsInterface itkGetMacro(ForwardEvents,bool); /** Users actions */ - virtual void RegionSelected(const RegionType & region){}; - virtual void ViewedRegionChanged(){}; - virtual void PixelClicked(const IndexType& index){}; + virtual void RegionSelected(const RegionType & region) {}; + virtual void ViewedRegionChanged() {}; + virtual void PixelClicked(const IndexType& index) {}; - protected: +protected: /** Constructor */ ImageViewerFullResolutionEventsInterface() - { - m_ForwardEvents = false; - } + { + m_ForwardEvents = false; + } /** Destructor */ - ~ImageViewerFullResolutionEventsInterface(){} + ~ImageViewerFullResolutionEventsInterface() {} - private: +private: ImageViewerFullResolutionEventsInterface(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Code/Visu/otbImageViewerFullWidget.h b/Code/Visu/otbImageViewerFullWidget.h index 3d2cb180499af6081685e980b05053e1367b403b..93315e869f43df1807bec791a915cd4e7d264061 100644 --- a/Code/Visu/otbImageViewerFullWidget.h +++ b/Code/Visu/otbImageViewerFullWidget.h @@ -38,11 +38,11 @@ template <class TPixel, class TLabel> class ImageViewerBase; * \sa ImageViewer, FullResolutionImageWidget * */ - template <class TPixel, class TLabel = double> +template <class TPixel, class TLabel = double> class ITK_EXPORT ImageViewerFullWidget - : public FullResolutionImageWidget<TPixel> + : public FullResolutionImageWidget<TPixel> { - public: +public: /** Standard class typedefs */ typedef ImageViewerFullWidget Self; typedef FullResolutionImageWidget<TPixel> Superclass; @@ -55,18 +55,18 @@ class ITK_EXPORT ImageViewerFullWidget /** Run-time type information (and related methods). */ itkTypeMacro(ImageViewerFullWidget, FullResolutionImageWidget); - /** This interface is provided in case some other application wants to intercept polygon an rectangle selection events */ - typedef ImageViewerFullResolutionEventsInterface EventsInterfaceType; - typedef EventsInterfaceType::Pointer EventsInterfacePointerType; + /** This interface is provided in case some other application wants to intercept polygon an rectangle selection events */ + typedef ImageViewerFullResolutionEventsInterface EventsInterfaceType; + typedef EventsInterfaceType::Pointer EventsInterfacePointerType; typedef TPixel PixelType; typedef TLabel LabelType; typedef typename Superclass::IndexType IndexType; typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::ImageType ImageType; - typedef typename Superclass::RegionType RegionType; - typedef typename Superclass::OverlayImageType OverlayImageType; + typedef typename Superclass::ImageType ImageType; + typedef typename Superclass::RegionType RegionType; + typedef typename Superclass::OverlayImageType OverlayImageType; typedef ImageViewerBase<PixelType, LabelType> ParentType; typedef ParentType* ParentPointerType; @@ -85,300 +85,300 @@ class ITK_EXPORT ImageViewerFullWidget itkGetObjectMacro(EventsInterface,EventsInterfaceType); itkSetObjectMacro(EventsInterface,EventsInterfaceType); - virtual void SetUpperLeftCorner(IndexType index) - { - Superclass::SetUpperLeftCorner(index); - if(m_EventsInterface.IsNotNull()) - { - m_EventsInterface->ViewedRegionChanged(); - } - } + virtual void SetUpperLeftCorner(IndexType index) + { + Superclass::SetUpperLeftCorner(index); + if (m_EventsInterface.IsNotNull()) + { + m_EventsInterface->ViewedRegionChanged(); + } + } - /** Handle method */ + /** Handle method */ /** Default mode handling, without ROI selection */ virtual int DefaultHandle(int event) { - switch(event) - { - case FL_PUSH: - { - // in case of mouse click, change the point of view - int x = Fl::event_x(); - int y = Fl::event_y(); - IndexType clickedIndex; - clickedIndex[0]=x; - clickedIndex[1]=y; - clickedIndex=this->WindowToImageCoordinates(clickedIndex); - - if(m_EventsInterface.IsNotNull()) + switch (event) { - m_EventsInterface->PixelClicked(clickedIndex); - } - if(m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) + case FL_PUSH: { - m_Parent->ChangeZoomViewedRegion(clickedIndex); - m_Parent->Update(); + // in case of mouse click, change the point of view + int x = Fl::event_x(); + int y = Fl::event_y(); + IndexType clickedIndex; + clickedIndex[0]=x; + clickedIndex[1]=y; + clickedIndex=this->WindowToImageCoordinates(clickedIndex); + + if (m_EventsInterface.IsNotNull()) + { + m_EventsInterface->PixelClicked(clickedIndex); + } + if (m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) + { + m_Parent->ChangeZoomViewedRegion(clickedIndex); + m_Parent->Update(); + } + return 1; } - return 1; - } - case FL_KEYDOWN: + case FL_KEYDOWN: { IndexType newIndex = m_Parent->GetZoomWidget()->GetViewedRegion().GetIndex(); SizeType newSize = m_Parent->GetZoomWidget()->GetViewedRegion().GetSize(); - bool moved = false; - switch(Fl::event_key()) - { - case FL_Down: + bool moved = false; + switch (Fl::event_key()) + { + case FL_Down: { - newIndex[1] += static_cast<long int>(newSize[1]/2)+newSize[1]/2; + newIndex[1] += static_cast<long int>(newSize[1]/2)+newSize[1]/2; newIndex[0] += newSize[0]/2; - moved = true; - break; - } - case FL_Up: + moved = true; + break; + } + case FL_Up: { - newIndex[1] += -static_cast<long int>(newSize[1]/2) - +newSize[1]/2; + newIndex[1] += -static_cast<long int>(newSize[1]/2) + +newSize[1]/2; newIndex[0] += newSize[0]/2; - moved = true; - break; - } - case FL_Left: - { - newIndex[0] += -static_cast<long int>(newSize[0]/2) - + newSize[0]/2; + moved = true; + break; + } + case FL_Left: + { + newIndex[0] += -static_cast<long int>(newSize[0]/2) + + newSize[0]/2; newIndex[1] += newSize[1]/2; - moved = true; - break; - } - case FL_Right: - { - newIndex[0] += static_cast<long int>(newSize[0]/2) - + newSize[0]/2; + moved = true; + break; + } + case FL_Right: + { + newIndex[0] += static_cast<long int>(newSize[0]/2) + + newSize[0]/2; newIndex[1] += newSize[1]/2; - moved = true; - break; - } - // if the view center was moved: - if(moved) - { - m_Parent->ChangeFullViewedRegion(newIndex); - m_Parent->ChangeZoomViewedRegion(newIndex); - m_Parent->Update(); - } - } - return 1; - } - } + moved = true; + break; + } + // if the view center was moved: + if (moved) + { + m_Parent->ChangeFullViewedRegion(newIndex); + m_Parent->ChangeZoomViewedRegion(newIndex); + m_Parent->Update(); + } + } + return 1; + } + } return 0; } virtual int RectangleROISelectionHandle(int event) { - switch(event) + switch (event) { - case FL_PUSH: + case FL_PUSH: + { + int x = Fl::event_x(); + int y = Fl::event_y(); + IndexType clickedIndex; + clickedIndex[0]=x; + clickedIndex[1]=y; + if (!m_Drag) { - int x = Fl::event_x(); - int y = Fl::event_y(); - IndexType clickedIndex; - clickedIndex[0]=x; - clickedIndex[1]=y; - if (!m_Drag) - { - m_LastIndex=this->WindowToImageCoordinates(clickedIndex); + m_LastIndex=this->WindowToImageCoordinates(clickedIndex); + } + return 1; + } + case FL_DRAG: + { + int x = Fl::event_x(); + int y = Fl::event_y(); + IndexType index; + index[0]=x; + index[1]=y; + IndexType clickedIndex=this->WindowToImageCoordinates(index); + typename BoxType::Pointer box = BoxType::New(); + box->SetColor(m_Parent->GetInterfaceBoxesColor()); + IndexType boxIndex; + SizeType boxSize; + // compute the size of the selection box + if (clickedIndex[0]>m_LastIndex[0]) + { + boxIndex[0]=m_LastIndex[0]; + boxSize[0]=clickedIndex[0]-m_LastIndex[0]; + } + else + { + boxIndex[0]=clickedIndex[0]; + boxSize[0]=m_LastIndex[0]-clickedIndex[0]; + } + if (clickedIndex[1]>m_LastIndex[1]) + { + boxIndex[1]=m_LastIndex[1]; + boxSize[1]=clickedIndex[1]-m_LastIndex[1]; + } + else + { + boxIndex[1]=clickedIndex[1]; + boxSize[1]=m_LastIndex[1]-clickedIndex[1]; + } + box->SetIndex(boxIndex); + box->SetSize(boxSize); + if (m_Drag) + { + m_Parent->GetInterfaceBoxesList()->PopBack(); + + } + m_Parent->GetInterfaceBoxesList()->PushBack(box); + m_Drag=true; + m_Parent->Update(); + return 1; + } + + case FL_RELEASE: + { + int x = Fl::event_x(); + int y = Fl::event_y(); + IndexType clickedIndex; + clickedIndex[0]=x; + clickedIndex[1]=y; + clickedIndex=this->WindowToImageCoordinates(clickedIndex); + if (m_Drag) + { + m_Parent->GetInterfaceBoxesList()->PopBack(); + } + if (m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) + { + if (m_Parent->GetPolygonROIList()->Size()==0) + { + m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); + m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); } - return 1; } - case FL_DRAG: + IndexType boxIndex; + SizeType boxSize; + if (clickedIndex[0]>m_LastIndex[0]) + { + boxIndex[0]=m_LastIndex[0]; + boxSize[0]=clickedIndex[0]-m_LastIndex[0]; + } + else + { + boxIndex[0]=clickedIndex[0]; + boxSize[0]=m_LastIndex[0]-clickedIndex[0]; + } + if (clickedIndex[1]>m_LastIndex[1]) + { + boxIndex[1]=m_LastIndex[1]; + boxSize[1]=clickedIndex[1]-m_LastIndex[1]; + } + else { - int x = Fl::event_x(); - int y = Fl::event_y(); - IndexType index; - index[0]=x; - index[1]=y; - IndexType clickedIndex=this->WindowToImageCoordinates(index); - typename BoxType::Pointer box = BoxType::New(); - box->SetColor(m_Parent->GetInterfaceBoxesColor()); - IndexType boxIndex; - SizeType boxSize; - // compute the size of the selection box - if(clickedIndex[0]>m_LastIndex[0]) - { - boxIndex[0]=m_LastIndex[0]; - boxSize[0]=clickedIndex[0]-m_LastIndex[0]; - } - else - { - boxIndex[0]=clickedIndex[0]; - boxSize[0]=m_LastIndex[0]-clickedIndex[0]; - } - if(clickedIndex[1]>m_LastIndex[1]) - { - boxIndex[1]=m_LastIndex[1]; - boxSize[1]=clickedIndex[1]-m_LastIndex[1]; - } - else - { - boxIndex[1]=clickedIndex[1]; - boxSize[1]=m_LastIndex[1]-clickedIndex[1]; - } - box->SetIndex(boxIndex); - box->SetSize(boxSize); - if(m_Drag) - { - m_Parent->GetInterfaceBoxesList()->PopBack(); - - } - m_Parent->GetInterfaceBoxesList()->PushBack(box); - m_Drag=true; - m_Parent->Update(); - return 1; + boxIndex[1]=clickedIndex[1]; + boxSize[1]=m_LastIndex[1]-clickedIndex[1]; } - case FL_RELEASE: + if (m_EventsInterface.IsNotNull()) { - int x = Fl::event_x(); - int y = Fl::event_y(); - IndexType clickedIndex; - clickedIndex[0]=x; - clickedIndex[1]=y; - clickedIndex=this->WindowToImageCoordinates(clickedIndex); - if(m_Drag) - { - m_Parent->GetInterfaceBoxesList()->PopBack(); - } - if(m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) - { - if(m_Parent->GetPolygonROIList()->Size()==0) - { - m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); - m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); - } - } - IndexType boxIndex; - SizeType boxSize; - if(clickedIndex[0]>m_LastIndex[0]) - { - boxIndex[0]=m_LastIndex[0]; - boxSize[0]=clickedIndex[0]-m_LastIndex[0]; - } - else - { - boxIndex[0]=clickedIndex[0]; - boxSize[0]=m_LastIndex[0]-clickedIndex[0]; - } - if(clickedIndex[1]>m_LastIndex[1]) - { - boxIndex[1]=m_LastIndex[1]; - boxSize[1]=clickedIndex[1]-m_LastIndex[1]; - } - else - { - boxIndex[1]=clickedIndex[1]; - boxSize[1]=m_LastIndex[1]-clickedIndex[1]; - } + RegionType selectedRegion; + selectedRegion.SetIndex(boxIndex); + selectedRegion.SetSize(boxSize); + m_EventsInterface->RegionSelected(selectedRegion); + } + if (m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) + { + ContinuousIndexType newVertex; + // Up Left corner + newVertex[0] = boxIndex[0]; + newVertex[1] = boxIndex[1]; + m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); + // Up Right corner + newVertex[0] += boxSize[0]; + m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); + // Down Right corner + newVertex[1] += boxSize[1]; + m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); + // Down Left corner + newVertex[0]= boxIndex[0]; + m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); + m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); + m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); - if(m_EventsInterface.IsNotNull()) - { - RegionType selectedRegion; - selectedRegion.SetIndex(boxIndex); - selectedRegion.SetSize(boxSize); - m_EventsInterface->RegionSelected(selectedRegion); - } - if(m_EventsInterface.IsNull() || m_EventsInterface->GetForwardEvents()) - { - ContinuousIndexType newVertex; - // Up Left corner - newVertex[0] = boxIndex[0]; - newVertex[1] = boxIndex[1]; - m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); - // Up Right corner - newVertex[0] += boxSize[0]; - m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); - // Down Right corner - newVertex[1] += boxSize[1]; - m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); - // Down Left corner - newVertex[0]= boxIndex[0]; - m_Parent->GetPolygonROIList()->Back()->AddVertex(newVertex); - m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); - m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); - - m_Parent->Update(); - } - m_Drag=false; - return 1; + m_Parent->Update(); } + m_Drag=false; + return 1; + } } return 0; } virtual int PolygonROISelectionHandle(int event) { - switch(event) + switch (event) + { + case FL_PUSH: + { + int x = Fl::event_x(); + int y = Fl::event_y(); + IndexType clickedIndex; + clickedIndex[0]=x; + clickedIndex[1]=y; + clickedIndex=this->WindowToImageCoordinates(clickedIndex); + // If left mouse click + if (Fl::event_button()==FL_LEFT_MOUSE) { - case FL_PUSH: + // If not already editing a polygon, start a new one. + if (m_Parent->GetPolygonROIList()->Size()==0) { - int x = Fl::event_x(); - int y = Fl::event_y(); - IndexType clickedIndex; - clickedIndex[0]=x; - clickedIndex[1]=y; - clickedIndex=this->WindowToImageCoordinates(clickedIndex); - // If left mouse click - if(Fl::event_button()==FL_LEFT_MOUSE) - { - // If not already editing a polygon, start a new one. - if(m_Parent->GetPolygonROIList()->Size()==0) - { - m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); - m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); + m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); + m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); } - m_Parent->GetPolygonROIList()->Back()->AddVertex(clickedIndex); - m_Parent->Update(); - } - else if(Fl::event_button()==FL_RIGHT_MOUSE) - { - m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); - m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); + m_Parent->GetPolygonROIList()->Back()->AddVertex(clickedIndex); + m_Parent->Update(); + } + else if (Fl::event_button()==FL_RIGHT_MOUSE) + { + m_Parent->GetPolygonROIList()->PushBack(PolygonType::New()); + m_Parent->GetPolygonROIList()->Back()->SetValue(m_Parent->GetNextROILabel()); - } - return 1; - } - case FL_KEYDOWN: - { - // erase the last vertex of the current polygon - if(Fl::event_key()==FL_Page_Down) - { - if(m_Parent->GetPolygonROIList()->Size()>0) + } + return 1; + } + case FL_KEYDOWN: + { + // erase the last vertex of the current polygon + if (Fl::event_key()==FL_Page_Down) { - unsigned int sizeOfThePolygon = m_Parent->GetPolygonROIList()->Back()->GetVertexList()->Size(); - if(sizeOfThePolygon>0) + if (m_Parent->GetPolygonROIList()->Size()>0) { - // itk::PolylineParametricPath does not provide a RemoveVertex() method, and the access to the vertex list is const, so we have no other choice to remove a vertex. - VertexListPointerType list = const_cast<VertexListType *>(m_Parent->GetPolygonROIList()->Back()->GetVertexList()); - list->pop_back(); - m_Parent->Update(); - } - } + unsigned int sizeOfThePolygon = m_Parent->GetPolygonROIList()->Back()->GetVertexList()->Size(); + if (sizeOfThePolygon>0) + { + // itk::PolylineParametricPath does not provide a RemoveVertex() method, and the access to the vertex list is const, so we have no other choice to remove a vertex. + VertexListPointerType list = const_cast<VertexListType *>(m_Parent->GetPolygonROIList()->Back()->GetVertexList()); + list->pop_back(); + m_Parent->Update(); } - return 1; } } + return 1; + } + } return 0; -} + } virtual int handle(int event) { - // Handle the mode selection to call the specific handle methods */ - if(event == FL_KEYDOWN) + // Handle the mode selection to call the specific handle methods */ + if (event == FL_KEYDOWN) { // Erase the last ROI - if(Fl::event_key()==FL_Delete && m_Parent->GetPolygonROIList()->Size() > 0) + if (Fl::event_key()==FL_Delete && m_Parent->GetPolygonROIList()->Size() > 0) { m_Parent->GetPolygonROIList()->Erase(m_Parent->GetPolygonROIList()->Size()-1); m_Parent->Update(); @@ -414,55 +414,55 @@ class ITK_EXPORT ImageViewerFullWidget // } } // handle the pixel value reporting - switch(event) + switch (event) { - case FL_ENTER: + case FL_ENTER: { m_MouseIn = true; return 1; } - case FL_LEAVE: + case FL_LEAVE: { m_MouseIn = false; m_Parent->ClearPixLocVal(); return 1; - } - case FL_MOVE: + } + case FL_MOVE: { - // If we move inside the point of view, then report the pixel location and value. + // If we move inside the point of view, then report the pixel location and value. m_MouseIn=true; - if(m_MouseMoveCount%m_ValueUpdateFrequency==0) - { - m_MousePos[0]=Fl::event_x(); - m_MousePos[1]=Fl::event_y(); - IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); - m_Parent->ReportPixel(newIndex); - m_MouseMoveCount=0; - } + if (m_MouseMoveCount%m_ValueUpdateFrequency==0) + { + m_MousePos[0]=Fl::event_x(); + m_MousePos[1]=Fl::event_y(); + IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); + m_Parent->ReportPixel(newIndex); + m_MouseMoveCount=0; + } m_MouseMoveCount++; - return 1; - } - case FL_FOCUS: - { - return 1; - } - case FL_UNFOCUS: + return 1; + } + case FL_FOCUS: + { + return 1; + } + case FL_UNFOCUS: { return 1; } - case FL_HIDE: + case FL_HIDE: { m_Parent->Hide(); return 0; } } // If the current mode is rectangle selection, call the right handle method - if(m_Parent->GetRectangularROISelectionMode()) + if (m_Parent->GetRectangularROISelectionMode()) { return RectangleROISelectionHandle(event); } // If the current mode is polygon selection, call the right handle method - else if(m_Parent->GetPolygonalROISelectionMode()) + else if (m_Parent->GetPolygonalROISelectionMode()) { return PolygonROISelectionHandle(event); } @@ -474,28 +474,28 @@ class ITK_EXPORT ImageViewerFullWidget } virtual void resize(int x,int y, int w, int h) - { - Superclass::resize(x,y,w,h); - if(m_Parent->GetBuilt()) - m_Parent->Update(); - } + { + Superclass::resize(x,y,w,h); + if (m_Parent->GetBuilt()) + m_Parent->Update(); + } - protected: +protected: /** * Constructor. */ ImageViewerFullWidget() - { - m_MouseIn = false; - m_MousePos.Fill(0); - m_MouseMoveCount = 0; - m_LastIndex.Fill(0); - m_ShortCutRectangle = false; - m_ShortCutPolygon = false; - m_Drag = false; - m_ValueUpdateFrequency = 5; - - }; + { + m_MouseIn = false; + m_MousePos.Fill(0); + m_MouseMoveCount = 0; + m_LastIndex.Fill(0); + m_ShortCutRectangle = false; + m_ShortCutPolygon = false; + m_Drag = false; + m_ValueUpdateFrequency = 5; + + }; /** * Destructor. */ @@ -504,7 +504,7 @@ class ITK_EXPORT ImageViewerFullWidget m_Parent = NULL; } - private: +private: ParentPointerType m_Parent; IndexType m_MousePos; bool m_MouseIn; @@ -514,7 +514,7 @@ class ITK_EXPORT ImageViewerFullWidget bool m_ShortCutRectangle; bool m_ShortCutPolygon; bool m_Drag; - EventsInterfacePointerType m_EventsInterface; + EventsInterfacePointerType m_EventsInterface; }; } // end namespace otb diff --git a/Code/Visu/otbImageViewerHistogramAndTransferFunctionWidget.h b/Code/Visu/otbImageViewerHistogramAndTransferFunctionWidget.h index 59d5847e2a92ac02d495baf11cba3172a346bb0b..3215da24258e172b710fb74b9f4f15c8859e500a 100644 --- a/Code/Visu/otbImageViewerHistogramAndTransferFunctionWidget.h +++ b/Code/Visu/otbImageViewerHistogramAndTransferFunctionWidget.h @@ -36,9 +36,9 @@ template <class TPixel, class TLabel> class ImageViewerBase; */ template <class THistogram, class TPixel, class TLabel> class ITK_EXPORT ImageViewerHistogramAndTransferFunctionWidget - : public HistogramAndTransferFunctionWidget<THistogram,TPixel> - { - public: + : public HistogramAndTransferFunctionWidget<THistogram,TPixel> +{ +public: /** Standard typedefs */ typedef ImageViewerHistogramAndTransferFunctionWidget Self; typedef HistogramAndTransferFunctionWidget<THistogram,TPixel> Superclass; @@ -71,33 +71,33 @@ class ITK_EXPORT ImageViewerHistogramAndTransferFunctionWidget itkSetMacro(Parent,ParentPointerType); itkGetMacro(Parent,ParentPointerType); - protected: +protected: // event handling virtual int handle(int event) - { - double factor = (this->GetHistogram()->Quantile(0,1.)-this->GetHistogram()->Quantile(0,0.)) - /(static_cast<double>(this->w())-2*this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w())); - double xupper = this->GetMarginX() + static_cast<double>(this->GetTransferFunction()->GetUpperBound()-this->GetHistogram()->Quantile(0,0.))/factor; - double xlower = this->GetMarginX() + static_cast<double>(this->GetTransferFunction()->GetLowerBound()-this->GetHistogram()->Quantile(0,0.))/factor; - switch(event) { - case FL_PUSH: + double factor = (this->GetHistogram()->Quantile(0,1.)-this->GetHistogram()->Quantile(0,0.)) + /(static_cast<double>(this->w())-2*this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w())); + double xupper = this->GetMarginX() + static_cast<double>(this->GetTransferFunction()->GetUpperBound()-this->GetHistogram()->Quantile(0,0.))/factor; + double xlower = this->GetMarginX() + static_cast<double>(this->GetTransferFunction()->GetLowerBound()-this->GetHistogram()->Quantile(0,0.))/factor; + switch (event) + { + case FL_PUSH: { double x = Fl::event_x(); - if((vcl_abs(x-xlower)<50) || (vcl_abs(x-xupper)<50)) - { - if(vcl_abs(x-xlower)<vcl_abs(x-xupper)) - { - m_ModifyLower = true; - } - else + if ((vcl_abs(x-xlower)<50) || (vcl_abs(x-xupper)<50)) { - m_ModifyUpper = true; - } + if (vcl_abs(x-xlower)<vcl_abs(x-xupper)) + { + m_ModifyLower = true; } + else + { + m_ModifyUpper = true; + } + } return 1; } - case FL_RELEASE: + case FL_RELEASE: { m_ModifyLower = false; m_ModifyUpper = false; @@ -105,56 +105,56 @@ class ITK_EXPORT ImageViewerHistogramAndTransferFunctionWidget m_Parent->Update(); return 1; } - case FL_DRAG: + case FL_DRAG: { double x = Fl::event_x(); - if(m_ModifyLower && (x>this->GetMarginX()) && (x<static_cast<double>(this->w())-this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w()))) - { - x = (x>xupper ? xupper : x); - this->GetTransferFunction()->SetLowerBound(static_cast<PixelType>(this->GetHistogram()->Quantile(0,0.)+(x-this->GetMarginX())*factor)); - this->redraw(); - } - else if(m_ModifyUpper && (x<static_cast<double>(this->w())-this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w()))) - { - x = (x<xlower ? xlower : x); - this->GetTransferFunction()->SetUpperBound(static_cast<PixelType>(this->GetHistogram()->Quantile(0,0.)+(x-this->GetMarginX())*factor)); - this->redraw(); - } + if (m_ModifyLower && (x>this->GetMarginX()) && (x<static_cast<double>(this->w())-this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w()))) + { + x = (x>xupper ? xupper : x); + this->GetTransferFunction()->SetLowerBound(static_cast<PixelType>(this->GetHistogram()->Quantile(0,0.)+(x-this->GetMarginX())*factor)); + this->redraw(); + } + else if (m_ModifyUpper && (x<static_cast<double>(this->w())-this->GetMarginX()-this->GetOutputHistogramMargin()*static_cast<double>(this->w()))) + { + x = (x<xlower ? xlower : x); + this->GetTransferFunction()->SetUpperBound(static_cast<PixelType>(this->GetHistogram()->Quantile(0,0.)+(x-this->GetMarginX())*factor)); + this->redraw(); + } return 1; } - case FL_MOUSEWHEEL: + case FL_MOUSEWHEEL: { int dy = Fl::event_dy(); - if(dy>0) - { - m_TransferFunctionCode++; - } + if (dy>0) + { + m_TransferFunctionCode++; + } else - { - m_TransferFunctionCode--; - } + { + m_TransferFunctionCode--; + } m_TransferFunctionCode = vcl_abs(m_TransferFunctionCode%4); TransferFunctionPointerType newFunction; - switch(m_TransferFunctionCode) - { - case 0: - newFunction = AffineTransferFunctionType::New(); - this->SetTransferFunctionLabel("Affine"); - break; - case 1: - newFunction = SquareRootTransferFunctionType::New(); - this->SetTransferFunctionLabel("Square Root"); - break; - case 2: - newFunction = LogTransferFunctionType::New(); - this->SetTransferFunctionLabel("Logarithmic"); - break; - case 3: - newFunction = SquareonentialTransferFunctionType::New(); - this->SetTransferFunctionLabel("Square"); - break; - } + switch (m_TransferFunctionCode) + { + case 0: + newFunction = AffineTransferFunctionType::New(); + this->SetTransferFunctionLabel("Affine"); + break; + case 1: + newFunction = SquareRootTransferFunctionType::New(); + this->SetTransferFunctionLabel("Square Root"); + break; + case 2: + newFunction = LogTransferFunctionType::New(); + this->SetTransferFunctionLabel("Logarithmic"); + break; + case 3: + newFunction = SquareonentialTransferFunctionType::New(); + this->SetTransferFunctionLabel("Square"); + break; + } newFunction->SetLowerBound(this->GetTransferFunction()->GetLowerBound()); newFunction->SetUpperBound(this->GetTransferFunction()->GetUpperBound()); this->SetTransferFunction(newFunction); @@ -163,27 +163,27 @@ class ITK_EXPORT ImageViewerHistogramAndTransferFunctionWidget return 1; } - } - return 0; } + return 0; + } /** Constructor */ ImageViewerHistogramAndTransferFunctionWidget() - { - m_ModifyLower = false; - m_ModifyUpper = false; - m_TransferFunctionCode = 0; - } + { + m_ModifyLower = false; + m_ModifyUpper = false; + m_TransferFunctionCode = 0; + } /** Destructor */ virtual ~ImageViewerHistogramAndTransferFunctionWidget() - { - m_Parent = NULL; - } - /**PrintSelf method */ + { + m_Parent = NULL; + } + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - } - private: + { + Superclass::PrintSelf(os,indent); + } +private: ImageViewerHistogramAndTransferFunctionWidget(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented /** Modify lower/upper threshold flag */ @@ -191,7 +191,7 @@ class ITK_EXPORT ImageViewerHistogramAndTransferFunctionWidget bool m_ModifyUpper; int m_TransferFunctionCode; ParentPointerType m_Parent; - }; +}; } // end namespace otb diff --git a/Code/Visu/otbImageViewerScrollWidget.h b/Code/Visu/otbImageViewerScrollWidget.h index e0a0ef12db1963bb1b25f820b5126cff760fe488..050636f596c6359428b298f5bfa64108247aaebd 100644 --- a/Code/Visu/otbImageViewerScrollWidget.h +++ b/Code/Visu/otbImageViewerScrollWidget.h @@ -38,9 +38,9 @@ template <class TPixel, class TLabel> class ImageViewerBase; */ template <class TPixel, class TLabel> class ITK_EXPORT ImageViewerScrollWidget - : public FixedSizeFullImageWidget<TPixel> + : public FixedSizeFullImageWidget<TPixel> { - public: +public: /** Standard class typedefs */ typedef ImageViewerScrollWidget Self; typedef FixedSizeFullImageWidget<TPixel> Superclass; @@ -69,10 +69,10 @@ class ITK_EXPORT ImageViewerScrollWidget /** Handle method */ virtual int handle(int event) - { - switch(event) { - case FL_PUSH: + switch (event) + { + case FL_PUSH: { int x = Fl::event_x(); int y = Fl::event_y(); @@ -85,58 +85,58 @@ class ITK_EXPORT ImageViewerScrollWidget //std::cout<<"Scroll widget: "<<m_Parent->GetLabel()<<" before parent update"<<std::endl; m_Parent->ChangeFullViewedRegion(clickedIndex); m_Parent->ChangeZoomViewedRegion(clickedIndex); - m_Parent->Update(); + m_Parent->Update(); //std::cout<<"Scroll widget: "<<m_Parent->GetLabel()<<" after parent update"<<std::endl; return 1; } - case FL_ENTER: + case FL_ENTER: { m_MouseIn = true; return 1; } - case FL_LEAVE: + case FL_LEAVE: { - m_MouseIn = false; - m_Parent->ClearPixLocVal(); - return 1; + m_MouseIn = false; + m_Parent->ClearPixLocVal(); + return 1; } - case FL_MOVE: + case FL_MOVE: { m_MouseIn=true; - if(m_MouseMoveCount%m_ValueUpdateFrequency==0) - { - m_MousePos[0]=Fl::event_x(); - m_MousePos[1]=Fl::event_y(); - IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); - IndexType realIndex; - realIndex[0]=newIndex[0]*m_Parent->GetShrinkFactor(); - realIndex[1]=newIndex[1]*m_Parent->GetShrinkFactor(); - m_Parent->ReportPixel(realIndex); - m_MouseMoveCount=0; - } - m_MouseMoveCount++; - return 1; + if (m_MouseMoveCount%m_ValueUpdateFrequency==0) + { + m_MousePos[0]=Fl::event_x(); + m_MousePos[1]=Fl::event_y(); + IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); + IndexType realIndex; + realIndex[0]=newIndex[0]*m_Parent->GetShrinkFactor(); + realIndex[1]=newIndex[1]*m_Parent->GetShrinkFactor(); + m_Parent->ReportPixel(realIndex); + m_MouseMoveCount=0; + } + m_MouseMoveCount++; + return 1; } - case FL_HIDE: + case FL_HIDE: { m_Parent->Hide(); return 0; } - } - return 0; } + return 0; + } - protected: +protected: /** * Constructor. */ ImageViewerScrollWidget() - { - m_MouseIn = false; - m_MousePos.Fill(0); - m_MouseMoveCount = 0; - m_ValueUpdateFrequency = 5; - }; + { + m_MouseIn = false; + m_MousePos.Fill(0); + m_MouseMoveCount = 0; + m_ValueUpdateFrequency = 5; + }; /** * Destructor. */ @@ -145,7 +145,7 @@ class ITK_EXPORT ImageViewerScrollWidget m_Parent = NULL; } - private: +private: ParentPointerType m_Parent; IndexType m_MousePos; bool m_MouseIn; diff --git a/Code/Visu/otbImageViewerZoomWidget.h b/Code/Visu/otbImageViewerZoomWidget.h index 32523bfd385db4d89d7d0f0edde7e5ce86808df7..d0ab6ef3b34d1010b919e9c8ae02ccd5a60ede9a 100644 --- a/Code/Visu/otbImageViewerZoomWidget.h +++ b/Code/Visu/otbImageViewerZoomWidget.h @@ -39,9 +39,9 @@ template <class TPixel, class TLabel> class ImageViewerBase; */ template <class TPixel, class TLabel> class ITK_EXPORT ImageViewerZoomWidget - : public ZoomableImageWidget<TPixel> + : public ZoomableImageWidget<TPixel> { - public: +public: /** Standard class typedefs */ typedef ImageViewerZoomWidget Self; typedef ZoomableImageWidget<TPixel> Superclass; @@ -66,131 +66,131 @@ class ITK_EXPORT ImageViewerZoomWidget itkGetMacro(Parent,ParentPointerType); /** Handle method */ virtual int handle(int event) - { - switch(event) { - case FL_ENTER: + switch (event) + { + case FL_ENTER: { m_MouseIn = true; return 1; } - case FL_LEAVE: + case FL_LEAVE: { m_MouseIn = false; m_Parent->UpdateZoomWidget(); m_Parent->ClearPixLocVal(); return 1; } - case FL_MOVE: + case FL_MOVE: { m_MouseIn=true; - if(m_MouseMoveCount%m_ValueUpdateFrequency==0) - { - m_MousePos[0]=Fl::event_x(); - m_MousePos[1]=Fl::event_y(); - IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); - m_Parent->ReportPixel(newIndex); - m_MouseMoveCount=0; - } + if (m_MouseMoveCount%m_ValueUpdateFrequency==0) + { + m_MousePos[0]=Fl::event_x(); + m_MousePos[1]=Fl::event_y(); + IndexType newIndex = this->WindowToImageCoordinates(m_MousePos); + m_Parent->ReportPixel(newIndex); + m_MouseMoveCount=0; + } m_MouseMoveCount++; return 1; } - case FL_MOUSEWHEEL: + case FL_MOUSEWHEEL: { int dy = Fl::event_dy(); - if(dy<0) + if (dy<0) { this->SetZoomFactor(this->GetOpenGlIsotropicZoom()+m_ZoomStep); } else - { - if(this->GetOpenGlIsotropicZoom()-m_ZoomStep>=1) { - this->SetZoomFactor(this->GetOpenGlIsotropicZoom()-m_ZoomStep); - } - else - { - this->SetZoomFactor(1.0); - } + if (this->GetOpenGlIsotropicZoom()-m_ZoomStep>=1) + { + this->SetZoomFactor(this->GetOpenGlIsotropicZoom()-m_ZoomStep); } + else + { + this->SetZoomFactor(1.0); + } + } m_Parent->Update(); return 1; } -case FL_FOCUS: + case FL_FOCUS: { - return 1; + return 1; } - case FL_UNFOCUS: + case FL_UNFOCUS: { return 1; } - case FL_KEYDOWN: + case FL_KEYDOWN: { IndexType newIndex = this->GetViewedRegion().GetIndex(); SizeType newSize = this->GetViewedRegion().GetSize(); newIndex[0]=newIndex[0]+newSize[0]/2; newIndex[1] = newIndex[1] + newSize[1]/2; - switch(Fl::event_key()) - { - case FL_Down: - { - newIndex[1] = newIndex[1]+newSize[1]/8; - break; - } - case FL_Up: - { - newIndex[1] = newIndex[1]-newSize[1]/8; - break; - } - case FL_Left: - { - newIndex[0] = newIndex[0]-newSize[0]/8; - break; - } - case FL_Right: - { - newIndex[0] = newIndex[0]+newSize[0]/8; - break; - } - } + switch (Fl::event_key()) + { + case FL_Down: + { + newIndex[1] = newIndex[1]+newSize[1]/8; + break; + } + case FL_Up: + { + newIndex[1] = newIndex[1]-newSize[1]/8; + break; + } + case FL_Left: + { + newIndex[0] = newIndex[0]-newSize[0]/8; + break; + } + case FL_Right: + { + newIndex[0] = newIndex[0]+newSize[0]/8; + break; + } + } m_Parent->ChangeZoomViewedRegion(newIndex); return 1; } - } - return 0; } + return 0; + } virtual void resize(int x,int y, int w, int h) - { - Superclass::resize(x,y,w,h); - if(m_Parent->GetBuilt()) - m_Parent->Update(); - } + { + Superclass::resize(x,y,w,h); + if (m_Parent->GetBuilt()) + m_Parent->Update(); + } - protected: +protected: /** * Constructor. */ ImageViewerZoomWidget() - { - m_ZoomStep = 0.2; - m_MouseIn = false; - m_MousePos.Fill(0); - m_MouseMoveCount = 0; - m_ValueUpdateFrequency = 5; - }; + { + m_ZoomStep = 0.2; + m_MouseIn = false; + m_MousePos.Fill(0); + m_MouseMoveCount = 0; + m_ValueUpdateFrequency = 5; + }; /** * Destructor. */ ~ImageViewerZoomWidget() { - m_Parent = NULL; + m_Parent = NULL; } - private: +private: ParentPointerType m_Parent; double m_ZoomStep; IndexType m_MousePos; diff --git a/Code/Visu/otbImageWidgetBase.h b/Code/Visu/otbImageWidgetBase.h index 37559bc857d901447187df78c7459f5e8008e0ba..a9efa3919008d820f90c8ca9afb4d1d74f6b9e98 100644 --- a/Code/Visu/otbImageWidgetBase.h +++ b/Code/Visu/otbImageWidgetBase.h @@ -28,240 +28,243 @@ namespace otb { - /** \class ImageWidgetBase - * \brief Base class for ImageWidget - * - */ +/** \class ImageWidgetBase + * \brief Base class for ImageWidget + * + */ template <class TPixel> class ImageWidgetBase - : public Fl_Gl_Window, public itk::Object + : public Fl_Gl_Window, public itk::Object +{ +public: + /** Standard class typedefs */ + typedef ImageWidgetBase Self; + typedef itk::Object Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory */ + itkNewMacro(Self); + + /** Runtime information */ + itkTypeMacro(ImageWidgetBase,Object); + + /** Template related typedef */ + typedef TPixel PixelType; + typedef otb::VectorImage<PixelType,2> ImageType; + typedef typename ImageType::PixelType VectorPixelType; + typedef typename ImageType::Pointer ImagePointerType; + typedef typename ImageType::SizeType SizeType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::RegionType RegionType; + + /// TODO: the type of this image should be templated + typedef otb::VectorImage<unsigned char,2> OverlayImageType; + typedef typename OverlayImageType::Pointer OverlayImagePointerType; + + /** View model */ + enum ViewModelType {GRAYSCALE,COMPLEX_MODULUS,COMPLEX_PHASE,RGB}; + + /** Form overlay typedef */ + typedef ImageWidgetFormBase FormType; + typedef FormType::Pointer FormPointerType; + typedef List<FormType> FormListType; + typedef typename FormListType::Pointer FormListPointerType; + typedef typename FormListType::ReverseIterator ReverseIteratorType; + typedef typename FormListType::Iterator IteratorType; + + typedef otb::ImageWidgetTransferFunction<PixelType> TransferFunctionType; + typedef otb::ImageWidgetAffineTransferFunction<PixelType> AffineTransferFunctionType; + typedef List<TransferFunctionType> TransferFunctionListType; + typedef typename TransferFunctionListType::Pointer TransferFunctionListPointerType; + + itkSetMacro(BufferedRegion,RegionType); + itkGetMacro(BufferedRegion,RegionType); + + itkSetMacro(ViewedRegion,RegionType); + itkGetMacro(ViewedRegion,RegionType); + + itkSetMacro(RedChannelIndex,unsigned int); + itkGetMacro(RedChannelIndex,unsigned int); + + itkSetMacro(GreenChannelIndex,unsigned int); + itkGetMacro(GreenChannelIndex,unsigned int); + + itkSetMacro(BlueChannelIndex,unsigned int); + itkGetMacro(BlueChannelIndex,unsigned int); + + itkSetMacro(FormOverlayVisible,bool); + itkGetMacro(FormOverlayVisible,bool); + + itkSetMacro(ImageOverlayVisible,bool); + itkGetMacro(ImageOverlayVisible,bool); + + itkSetMacro(BlackTransparency,bool); + itkGetMacro(BlackTransparency,bool); + + itkGetMacro(SubSamplingRate, unsigned int); + itkSetMacro(SubSamplingRate, unsigned int); + + itkSetMacro(ViewModel,ViewModelType); + itkGetMacro(ViewModel,ViewModelType); + + itkGetMacro(ImageOverlayOpacity,unsigned char); + itkSetMacro(ImageOverlayOpacity,unsigned char); + + itkGetObjectMacro(FormList,FormListType); + itkGetObjectMacro(TransferFunctionList,TransferFunctionListType); + + itkGetMacro(OpenGlIsotropicZoom,double); + + /** Set the input image. + * \param image The image to view. + */ + void SetInput(ImageType* image); + /** Get the input image. + * \return The image to view. + */ + ImageType * GetInput(void); + + /** Set the input overlay image. + * \param image The image to view. + */ + void SetInputOverlay(OverlayImageType* image); + /** Get the input overlay image. + * \return The image to view. + */ + OverlayImageType * GetInputOverlay(void); + + /** Set the input overlay form list. + * \param formList The form list to view. + */ + void SetFormListOverlay(FormListType* formList); + + /** Set the transfer function list + * \param list The transfer function list. + */ + void SetTransferFunctionList(TransferFunctionListType * list); + + /** Show The widget */ + void Show(void); + /** Reset the widget (Clear buffered region and re init the transfer functions) */ + void Reset(void); + /** Clear the buffered region */ + void ClearBufferedRegion(void); + + /** + * Convert window to image coordinate. + * \param index The window coordinate. + * \return The image coordinate. + */ + virtual IndexType WindowToImageCoordinates(IndexType index); + + /** Initialize the widget */ + virtual void Init(int x, int y, int w, int h, const char * l); + + /** Get the buffer index from the iterator position and the buffered region */ + inline unsigned int GetBufferIndex(const IndexType& iteratorIndex) + { + return (iteratorIndex[1]-m_BufferedRegion.GetIndex()[1])*4*m_BufferedRegion.GetSize()[0] + + 4*(iteratorIndex[0]-m_BufferedRegion.GetIndex()[0]); + } + + inline unsigned int GetRevertedBufferIndex(const IndexType& iteratorIndex) + { + return (m_BufferedRegion.GetSize()[1]-1+m_BufferedRegion.GetIndex()[1]-iteratorIndex[1])*4*m_BufferedRegion.GetSize()[0] + + 4*(iteratorIndex[0]-m_BufferedRegion.GetIndex()[0]); + } +protected: + /** Constructor */ + ImageWidgetBase(); + /** Destructor */ + ~ImageWidgetBase(); + + /** Draw the widget */ + virtual void draw(void); + /** Rebuild opengl buffer */ + virtual void RebuildOpenGlBuffer(void); + /** Rebuild opengl image overlay buffer */ + virtual void RebuildOpenGlImageOverlayBuffer(void); + + /** Normalization function */ + unsigned char Normalize(PixelType value, unsigned int channelIndex); + + /** Return the width and heigh of the displayed image (overloaded for scroll)*/ + inline virtual int wDisplayed() { - public: - /** Standard class typedefs */ - typedef ImageWidgetBase Self; - typedef itk::Object Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - - /** Method for creation through the object factory */ - itkNewMacro(Self); - - /** Runtime information */ - itkTypeMacro(ImageWidgetBase,Object); - - /** Template related typedef */ - typedef TPixel PixelType; - typedef otb::VectorImage<PixelType,2> ImageType; - typedef typename ImageType::PixelType VectorPixelType; - typedef typename ImageType::Pointer ImagePointerType; - typedef typename ImageType::SizeType SizeType; - typedef typename ImageType::IndexType IndexType; - typedef typename ImageType::RegionType RegionType; - - /// TODO: the type of this image should be templated - typedef otb::VectorImage<unsigned char,2> OverlayImageType; - typedef typename OverlayImageType::Pointer OverlayImagePointerType; - - /** View model */ - enum ViewModelType{GRAYSCALE,COMPLEX_MODULUS,COMPLEX_PHASE,RGB}; - - /** Form overlay typedef */ - typedef ImageWidgetFormBase FormType; - typedef FormType::Pointer FormPointerType; - typedef List<FormType> FormListType; - typedef typename FormListType::Pointer FormListPointerType; - typedef typename FormListType::ReverseIterator ReverseIteratorType; - typedef typename FormListType::Iterator IteratorType; - - typedef otb::ImageWidgetTransferFunction<PixelType> TransferFunctionType; - typedef otb::ImageWidgetAffineTransferFunction<PixelType> AffineTransferFunctionType; - typedef List<TransferFunctionType> TransferFunctionListType; - typedef typename TransferFunctionListType::Pointer TransferFunctionListPointerType; - - itkSetMacro(BufferedRegion,RegionType); - itkGetMacro(BufferedRegion,RegionType); - - itkSetMacro(ViewedRegion,RegionType); - itkGetMacro(ViewedRegion,RegionType); - - itkSetMacro(RedChannelIndex,unsigned int); - itkGetMacro(RedChannelIndex,unsigned int); - - itkSetMacro(GreenChannelIndex,unsigned int); - itkGetMacro(GreenChannelIndex,unsigned int); - - itkSetMacro(BlueChannelIndex,unsigned int); - itkGetMacro(BlueChannelIndex,unsigned int); - - itkSetMacro(FormOverlayVisible,bool); - itkGetMacro(FormOverlayVisible,bool); - - itkSetMacro(ImageOverlayVisible,bool); - itkGetMacro(ImageOverlayVisible,bool); - - itkSetMacro(BlackTransparency,bool); - itkGetMacro(BlackTransparency,bool); - - itkGetMacro(SubSamplingRate, unsigned int); - itkSetMacro(SubSamplingRate, unsigned int); - - itkSetMacro(ViewModel,ViewModelType); - itkGetMacro(ViewModel,ViewModelType); - - itkGetMacro(ImageOverlayOpacity,unsigned char); - itkSetMacro(ImageOverlayOpacity,unsigned char); - - itkGetObjectMacro(FormList,FormListType); - itkGetObjectMacro(TransferFunctionList,TransferFunctionListType); - - itkGetMacro(OpenGlIsotropicZoom,double); - - /** Set the input image. - * \param image The image to view. - */ - void SetInput(ImageType* image); - /** Get the input image. - * \return The image to view. - */ - ImageType * GetInput(void); - - /** Set the input overlay image. - * \param image The image to view. - */ - void SetInputOverlay(OverlayImageType* image); - /** Get the input overlay image. - * \return The image to view. - */ - OverlayImageType * GetInputOverlay(void); - - /** Set the input overlay form list. - * \param formList The form list to view. - */ - void SetFormListOverlay(FormListType* formList); - - /** Set the transfer function list - * \param list The transfer function list. - */ - void SetTransferFunctionList(TransferFunctionListType * list); - - /** Show The widget */ - void Show(void); - /** Reset the widget (Clear buffered region and re init the transfer functions) */ - void Reset(void); - /** Clear the buffered region */ - void ClearBufferedRegion(void); - - /** - * Convert window to image coordinate. - * \param index The window coordinate. - * \return The image coordinate. - */ - virtual IndexType WindowToImageCoordinates(IndexType index); - - /** Initialize the widget */ - virtual void Init(int x, int y, int w, int h, const char * l); - - /** Get the buffer index from the iterator position and the buffered region */ - inline unsigned int GetBufferIndex(const IndexType& iteratorIndex) - { - return (iteratorIndex[1]-m_BufferedRegion.GetIndex()[1])*4*m_BufferedRegion.GetSize()[0] - + 4*(iteratorIndex[0]-m_BufferedRegion.GetIndex()[0]); - } - - inline unsigned int GetRevertedBufferIndex(const IndexType& iteratorIndex) - { - return (m_BufferedRegion.GetSize()[1]-1+m_BufferedRegion.GetIndex()[1]-iteratorIndex[1])*4*m_BufferedRegion.GetSize()[0] - + 4*(iteratorIndex[0]-m_BufferedRegion.GetIndex()[0]); - } - protected: - /** Constructor */ - ImageWidgetBase(); - /** Destructor */ - ~ImageWidgetBase(); - - /** Draw the widget */ - virtual void draw(void); - /** Rebuild opengl buffer */ - virtual void RebuildOpenGlBuffer(void); - /** Rebuild opengl image overlay buffer */ - virtual void RebuildOpenGlImageOverlayBuffer(void); - - /** Normalization function */ - unsigned char Normalize(PixelType value, unsigned int channelIndex); - - /** Return the width and heigh of the displayed image (overloaded for scroll)*/ - inline virtual int wDisplayed() - { return this->w(); - } + } - inline virtual int hDisplayed() - { + inline virtual int hDisplayed() + { return this->h(); - } - - // PURE VIRTUAL METHODS - - // User is not supposed to be allowed to move the zoom in the generic implementation - itkSetMacro(OpenGlIsotropicZoom,double); - - - /** Unlarge OpenGlBuffer */ - virtual void UpdateOpenGlBufferedRegion(void){}; - /** Test if the buffer has to be enlarged */ - virtual bool UpdateOpenGlBufferedRegionRequested(void){return 1;}; - - /** Resize the widget */ - virtual void resize(int x, int y, int w, int h){}; - - // END PURE VIRTUAL METHODS - private: - ImageWidgetBase(const Self&); // purposely not implemented - void operator=(const Self&); // purposely not implemented - - /** Pointer to the viewed image */ - ImagePointerType m_Image; - /** OpenGl Buffer */ - unsigned char * m_OpenGlBuffer; - /** OpenGl Zoom factor */ - double m_OpenGlIsotropicZoom; - /** Buffered image region */ - RegionType m_BufferedRegion; - /** Viewed image region */ - RegionType m_ViewedRegion; - /** The view model */ - ViewModelType m_ViewModel; - /** Red channel index */ - unsigned int m_RedChannelIndex; - /** Green channel index */ - unsigned int m_GreenChannelIndex; - /** Blue channel index */ - unsigned int m_BlueChannelIndex; - /** Display the form overlay */ - bool m_FormOverlayVisible; - /** The form list form the overlay */ - FormListPointerType m_FormList; - /** Display the image overlay */ - bool m_ImageOverlayVisible; - /** Set black to transparent*/ - bool m_BlackTransparency; - /** The image Overlay opacity */ - unsigned char m_ImageOverlayOpacity; - /** Pointer to the overlay image */ - OverlayImagePointerType m_ImageOverlay; - /** OpenGl image overlay buffer */ - unsigned char * m_OpenGlImageOverlayBuffer; - /** Max value for normalization */ - VectorPixelType m_MaxComponentValues; - /** Min value for normalization */ - VectorPixelType m_MinComponentValues; - /** Subsampling rate in case of subsampled input image. - * Default is 1. - */ - unsigned int m_SubSamplingRate; - /** List of the transfer function by channel */ - TransferFunctionListPointerType m_TransferFunctionList; + } + + // PURE VIRTUAL METHODS + + // User is not supposed to be allowed to move the zoom in the generic implementation + itkSetMacro(OpenGlIsotropicZoom,double); + + + /** Unlarge OpenGlBuffer */ + virtual void UpdateOpenGlBufferedRegion(void) {}; + /** Test if the buffer has to be enlarged */ + virtual bool UpdateOpenGlBufferedRegionRequested(void) + { + return 1; }; + + /** Resize the widget */ + virtual void resize(int x, int y, int w, int h) {}; + + // END PURE VIRTUAL METHODS +private: + ImageWidgetBase(const Self&); // purposely not implemented + void operator=(const Self&); // purposely not implemented + + /** Pointer to the viewed image */ + ImagePointerType m_Image; + /** OpenGl Buffer */ + unsigned char * m_OpenGlBuffer; + /** OpenGl Zoom factor */ + double m_OpenGlIsotropicZoom; + /** Buffered image region */ + RegionType m_BufferedRegion; + /** Viewed image region */ + RegionType m_ViewedRegion; + /** The view model */ + ViewModelType m_ViewModel; + /** Red channel index */ + unsigned int m_RedChannelIndex; + /** Green channel index */ + unsigned int m_GreenChannelIndex; + /** Blue channel index */ + unsigned int m_BlueChannelIndex; + /** Display the form overlay */ + bool m_FormOverlayVisible; + /** The form list form the overlay */ + FormListPointerType m_FormList; + /** Display the image overlay */ + bool m_ImageOverlayVisible; + /** Set black to transparent*/ + bool m_BlackTransparency; + /** The image Overlay opacity */ + unsigned char m_ImageOverlayOpacity; + /** Pointer to the overlay image */ + OverlayImagePointerType m_ImageOverlay; + /** OpenGl image overlay buffer */ + unsigned char * m_OpenGlImageOverlayBuffer; + /** Max value for normalization */ + VectorPixelType m_MaxComponentValues; + /** Min value for normalization */ + VectorPixelType m_MinComponentValues; + /** Subsampling rate in case of subsampled input image. + * Default is 1. + */ + unsigned int m_SubSamplingRate; + /** List of the transfer function by channel */ + TransferFunctionListPointerType m_TransferFunctionList; +}; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/Visu/otbImageWidgetBase.txx b/Code/Visu/otbImageWidgetBase.txx index 2f40d9147b6111fba95552933edafdd584fda6d3..271b856db7af6eaeeaba2c9dfcad9f754eecdcf4 100644 --- a/Code/Visu/otbImageWidgetBase.txx +++ b/Code/Visu/otbImageWidgetBase.txx @@ -25,509 +25,517 @@ PURPOSE. See the above copyright notices for more information. namespace otb { - /** - * Constructor. - */ - template <class TPixel> - ImageWidgetBase<TPixel> - ::ImageWidgetBase() +/** + * Constructor. + */ +template <class TPixel> +ImageWidgetBase<TPixel> +::ImageWidgetBase() : Fl_Gl_Window(0,0,0,0,0) +{ + m_Image = NULL; + m_OpenGlIsotropicZoom = 1.0; + SizeType size; + size.Fill(0); + IndexType index; + index.Fill(0); + RegionType region; + region.SetSize(size); + region.SetIndex(index); + m_BufferedRegion = region; + m_ViewedRegion = region; + m_ViewModel=RGB; + m_RedChannelIndex = 0; + m_GreenChannelIndex = 1; + m_BlueChannelIndex = 2; + m_OpenGlBuffer = NULL; + m_FormOverlayVisible = false; + m_ImageOverlayVisible = false; + m_BlackTransparency = false; + m_FormList = FormListType::New(); + m_ImageOverlay = NULL; + m_OpenGlImageOverlayBuffer = NULL; + m_ImageOverlayOpacity = 128; + m_TransferFunctionList = TransferFunctionListType::New(); + m_TransferFunctionList->PushBack(AffineTransferFunctionType::New()); + m_SubSamplingRate = 1; +} +/** + * Destructor. + */ +template <class TPixel> +ImageWidgetBase<TPixel> +::~ImageWidgetBase() +{ + if (m_OpenGlBuffer != NULL) { - m_Image = NULL; - m_OpenGlIsotropicZoom = 1.0; - SizeType size; - size.Fill(0); - IndexType index; - index.Fill(0); - RegionType region; - region.SetSize(size); - region.SetIndex(index); - m_BufferedRegion = region; - m_ViewedRegion = region; - m_ViewModel=RGB; - m_RedChannelIndex = 0; - m_GreenChannelIndex = 1; - m_BlueChannelIndex = 2; - m_OpenGlBuffer = NULL; - m_FormOverlayVisible = false; - m_ImageOverlayVisible = false; - m_BlackTransparency = false; - m_FormList = FormListType::New(); - m_ImageOverlay = NULL; - m_OpenGlImageOverlayBuffer = NULL; - m_ImageOverlayOpacity = 128; - m_TransferFunctionList = TransferFunctionListType::New(); - m_TransferFunctionList->PushBack(AffineTransferFunctionType::New()); - m_SubSamplingRate = 1; - } - /** - * Destructor. - */ - template <class TPixel> - ImageWidgetBase<TPixel> - ::~ImageWidgetBase() - { - if(m_OpenGlBuffer != NULL) - { - delete [] m_OpenGlBuffer; - } - if(m_OpenGlImageOverlayBuffer != NULL) - { - delete [] m_OpenGlImageOverlayBuffer; - } - } - /** - * Reset the widget. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::Reset(void) - { - int x = this->x(); - int y = this->y(); - int w = this->w(); - int h = this->h(); - const char * label = this->label(); - ClearBufferedRegion(); - Init(x,y,w,h,label); + delete [] m_OpenGlBuffer; } - - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::ClearBufferedRegion(void) + if (m_OpenGlImageOverlayBuffer != NULL) { - SizeType size; - size.Fill(0); - m_BufferedRegion.SetSize(size); + delete [] m_OpenGlImageOverlayBuffer; } +} +/** + * Reset the widget. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::Reset(void) +{ + int x = this->x(); + int y = this->y(); + int w = this->w(); + int h = this->h(); + const char * label = this->label(); + ClearBufferedRegion(); + Init(x,y,w,h,label); +} + +template <class TPixel> +void +ImageWidgetBase<TPixel> +::ClearBufferedRegion(void) +{ + SizeType size; + size.Fill(0); + m_BufferedRegion.SetSize(size); +} - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::Init(int x, int y, int w, int h, const char * l) - { +template <class TPixel> +void +ImageWidgetBase<TPixel> +::Init(int x, int y, int w, int h, const char * l) +{ #ifdef OTB_GL_USE_ACCEL - otbMsgDevMacro(<<"Using OTB_GL_USE_ACCEL: ON"); + otbMsgDevMacro(<<"Using OTB_GL_USE_ACCEL: ON"); #else - otbMsgDevMacro(<<"Using OTB_GL_USE_ACCEL: OFF"); + otbMsgDevMacro(<<"Using OTB_GL_USE_ACCEL: OFF"); #endif - for(unsigned int i = 0; i<m_Image->GetNumberOfComponentsPerPixel();++i) - { - if(i>=m_TransferFunctionList->Size()) + for (unsigned int i = 0; i<m_Image->GetNumberOfComponentsPerPixel();++i) + { + if (i>=m_TransferFunctionList->Size()) { m_TransferFunctionList->PushBack(AffineTransferFunctionType::New()); } - } - } - /** - * Convert window to image coordinate. - * \param index The window coordinate. - * \return The image coordinate. - */ - template <class TPixel> - typename ImageWidgetBase<TPixel> - ::IndexType - ImageWidgetBase<TPixel> - ::WindowToImageCoordinates(IndexType index) - { - double x,y; - IndexType resp; - IndexType origin = this->GetViewedRegion().GetIndex(); - x = static_cast<double>(index[0])/m_OpenGlIsotropicZoom +} + +/** + * Convert window to image coordinate. + * \param index The window coordinate. + * \return The image coordinate. + */ +template <class TPixel> +typename ImageWidgetBase<TPixel> +::IndexType +ImageWidgetBase<TPixel> +::WindowToImageCoordinates(IndexType index) +{ + double x,y; + IndexType resp; + IndexType origin = this->GetViewedRegion().GetIndex(); + x = static_cast<double>(index[0])/m_OpenGlIsotropicZoom +static_cast<double>(origin[0]); - y = static_cast<double>(origin[1]) + y = static_cast<double>(origin[1]) +static_cast<double>(index[1])/m_OpenGlIsotropicZoom; - SizeType maxSize = this->GetInput()->GetLargestPossibleRegion().GetSize(); - IndexType maxIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex(); - - if(x<maxIndex[0]) - { - resp[0]=maxIndex[0]; - } - else if(x>maxIndex[0]+maxSize[0]) - { - resp[0] = maxIndex[0]+maxSize[0]; - } - else - { - resp[0]=static_cast<int>(x); - } - - if(y<maxIndex[1]) - { - resp[1]=maxIndex[1]; - - } - else if(y>maxIndex[1]+maxSize[1]) - { - resp[1] = maxIndex[1]+maxSize[1]; - } - else - { - resp[1]=static_cast<int>(y); - } - return resp; - } + SizeType maxSize = this->GetInput()->GetLargestPossibleRegion().GetSize(); + IndexType maxIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex(); - /** Set the input image. - * \param image The image to view. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::SetInput(ImageType * image) + if (x<maxIndex[0]) { - m_Image=image; - m_Image->UpdateOutputInformation(); - SizeType size; - size.Fill(0); - m_BufferedRegion.SetSize(size); - SizeType displaySize; - displaySize[0]=this->w(); - displaySize[1]=this->h(); - m_ViewedRegion.SetSize(displaySize); - m_ViewedRegion.Crop(m_Image->GetLargestPossibleRegion()); + resp[0]=maxIndex[0]; } - /** Get the input image. - * \return The image to view. - */ - template <class TPixel> - typename ImageWidgetBase<TPixel> - ::ImageType * - ImageWidgetBase<TPixel> - ::GetInput(void) + else if (x>maxIndex[0]+maxSize[0]) { - return m_Image; + resp[0] = maxIndex[0]+maxSize[0]; } - - /** Set the input overlay image. - * \param image The image to view. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::SetInputOverlay(OverlayImageType * image) + else { - m_ImageOverlay=image; + resp[0]=static_cast<int>(x); } - /** Set the input overlay form list. - * \param image The form list to view. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::SetFormListOverlay(FormListType* formList) + if (y<maxIndex[1]) { - m_FormList = formList; - } + resp[1]=maxIndex[1]; - /** Set the transfer function list - * \param list The transfer function list. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::SetTransferFunctionList(TransferFunctionListType * list) + } + else if (y>maxIndex[1]+maxSize[1]) { - m_TransferFunctionList = list; + resp[1] = maxIndex[1]+maxSize[1]; } - - /** Get the input overlay image. - * \return The image to view. - */ - template <class TPixel> - typename ImageWidgetBase<TPixel> - ::OverlayImageType * - ImageWidgetBase<TPixel> - ::GetInputOverlay(void) + else { - return m_ImageOverlay; + resp[1]=static_cast<int>(y); } - - /** - * Show The widget. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::Show(void) + return resp; +} + +/** Set the input image. + * \param image The image to view. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::SetInput(ImageType * image) +{ + m_Image=image; + m_Image->UpdateOutputInformation(); + SizeType size; + size.Fill(0); + m_BufferedRegion.SetSize(size); + SizeType displaySize; + displaySize[0]=this->w(); + displaySize[1]=this->h(); + m_ViewedRegion.SetSize(displaySize); + m_ViewedRegion.Crop(m_Image->GetLargestPossibleRegion()); +} +/** Get the input image. + * \return The image to view. + */ +template <class TPixel> +typename ImageWidgetBase<TPixel> +::ImageType * +ImageWidgetBase<TPixel> +::GetInput(void) +{ + return m_Image; +} + +/** Set the input overlay image. + * \param image The image to view. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::SetInputOverlay(OverlayImageType * image) +{ + m_ImageOverlay=image; +} + +/** Set the input overlay form list. + * \param image The form list to view. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::SetFormListOverlay(FormListType* formList) +{ + m_FormList = formList; +} + +/** Set the transfer function list + * \param list The transfer function list. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::SetTransferFunctionList(TransferFunctionListType * list) +{ + m_TransferFunctionList = list; +} + +/** Get the input overlay image. + * \return The image to view. + */ +template <class TPixel> +typename ImageWidgetBase<TPixel> +::OverlayImageType * +ImageWidgetBase<TPixel> +::GetInputOverlay(void) +{ + return m_ImageOverlay; +} + +/** + * Show The widget. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::Show(void) +{ + if (!m_Image) { - if(!m_Image) - { - itkExceptionMacro(<<"No input image !"); - } - else - { - //otbMsgDebugMacro(<<"Zoomable widget Show"); - this->show(); - //otbMsgDebugMacro(<<"Before redraw."); - this->redraw(); - //otbMsgDebugMacro(<<"After redraw."); - } + itkExceptionMacro(<<"No input image !"); } - - template <class TPixel> - unsigned char - ImageWidgetBase<TPixel> - ::Normalize(PixelType value, unsigned int channelIndex) + else { - return m_TransferFunctionList->GetNthElement(channelIndex)->Map(value); + //otbMsgDebugMacro(<<"Zoomable widget Show"); + this->show(); + //otbMsgDebugMacro(<<"Before redraw."); + this->redraw(); + //otbMsgDebugMacro(<<"After redraw."); } +} - /** - * Draw the widget - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::draw(void) - { +template <class TPixel> +unsigned char +ImageWidgetBase<TPixel> +::Normalize(PixelType value, unsigned int channelIndex) +{ + return m_TransferFunctionList->GetNthElement(channelIndex)->Map(value); +} + +/** + * Draw the widget + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::draw(void) +{ - // otbMsgDebugMacro(<<"Draw"); + // otbMsgDebugMacro(<<"Draw"); - if(this->UpdateOpenGlBufferedRegionRequested()) - { - UpdateOpenGlBufferedRegion(); - m_Image->SetRequestedRegion(m_BufferedRegion); - m_Image->PropagateRequestedRegion(); - m_Image->UpdateOutputData(); - RebuildOpenGlBuffer(); - if(m_ImageOverlayVisible) + if (this->UpdateOpenGlBufferedRegionRequested()) + { + UpdateOpenGlBufferedRegion(); + m_Image->SetRequestedRegion(m_BufferedRegion); + m_Image->PropagateRequestedRegion(); + m_Image->UpdateOutputData(); + RebuildOpenGlBuffer(); + if (m_ImageOverlayVisible) { m_ImageOverlay->SetRequestedRegion(m_BufferedRegion); m_ImageOverlay->PropagateRequestedRegion(); m_ImageOverlay->UpdateOutputData(); } - } - - if(m_ImageOverlayVisible) - { - RebuildOpenGlImageOverlayBuffer(); - } + } - if (!this->valid()) - { - valid(1); - glLoadIdentity(); - glViewport(0,0,w(),h()); - glClearColor((float)0.0, (float)0.0, (float)0.0, (float)0.0); - glShadeModel(GL_FLAT); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - } + if (m_ImageOverlayVisible) + { + RebuildOpenGlImageOverlayBuffer(); + } - glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black - glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params + if (!this->valid()) + { + valid(1); glLoadIdentity(); - glMatrixMode(GL_PROJECTION); - this->ortho(); - glDisable(GL_BLEND); - - -#ifndef OTB_GL_USE_ACCEL + glViewport(0,0,w(),h()); + glClearColor((float)0.0, (float)0.0, (float)0.0, (float)0.0); + glShadeModel(GL_FLAT); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + } - // To be consistent with old method - int displayHeight = static_cast<int>(vcl_ceil(m_BufferedRegion.GetSize()[1]*m_OpenGlIsotropicZoom)); - int viewPortOffset = 0; - viewPortOffset = h()-displayHeight; - glRasterPos2i(0,viewPortOffset); + glClear(GL_COLOR_BUFFER_BIT); //this clears and paints to black + glMatrixMode(GL_MODELVIEW); //clear previous 3D draw params + glLoadIdentity(); + glMatrixMode(GL_PROJECTION); + this->ortho(); + glDisable(GL_BLEND); - glPixelZoom(m_OpenGlIsotropicZoom,m_OpenGlIsotropicZoom); - // display the image - glDrawPixels(m_BufferedRegion.GetSize()[0], - m_BufferedRegion.GetSize()[1], - GL_RGBA, - GL_UNSIGNED_BYTE, - m_OpenGlBuffer); -#else - glEnable(GL_TEXTURE_2D); - glColor4f(1.0,1.0,1.0,0.0); - GLuint texture; - glGenTextures(1, &texture); - glBindTexture(GL_TEXTURE_2D, texture); - glTexImage2D(GL_TEXTURE_2D, 0, 3, m_BufferedRegion.GetSize()[0], m_BufferedRegion.GetSize()[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, m_OpenGlBuffer); - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // Nearest Filtering - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // Nearest Filtering - // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering - // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering +#ifndef OTB_GL_USE_ACCEL - glBindTexture (GL_TEXTURE_2D, texture); - glBegin (GL_QUADS); - int hOffset = this->h() - this->hDisplayed(); - glTexCoord2f (0.0, 1.0); glVertex3f (0.0, 0.0+hOffset, 0.0); - glTexCoord2f (1.0, 1.0); glVertex3f (this->wDisplayed(), 0.0+hOffset, 0.0); - glTexCoord2f (1.0, 0.0); glVertex3f (this->wDisplayed(), this->hDisplayed()+hOffset, 0.0); - glTexCoord2f (0.0, 0.0); glVertex3f (0.0, this->hDisplayed()+hOffset, 0.0); - glEnd (); + // To be consistent with old method + int displayHeight = static_cast<int>(vcl_ceil(m_BufferedRegion.GetSize()[1]*m_OpenGlIsotropicZoom)); + int viewPortOffset = 0; + viewPortOffset = h()-displayHeight; + glRasterPos2i(0,viewPortOffset); - glDisable(GL_TEXTURE_2D); -#endif + glPixelZoom(m_OpenGlIsotropicZoom,m_OpenGlIsotropicZoom); - // if image overlay is activated, display image overlay - if(m_ImageOverlayVisible) - { -#ifndef OTB_GL_USE_ACCEL - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); + // display the image glDrawPixels(m_BufferedRegion.GetSize()[0], - m_BufferedRegion.GetSize()[1], - GL_RGBA, - GL_UNSIGNED_BYTE, - m_OpenGlImageOverlayBuffer); - - glDisable(GL_BLEND); - glEnd(); + m_BufferedRegion.GetSize()[1], + GL_RGBA, + GL_UNSIGNED_BYTE, + m_OpenGlBuffer); #else - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); - glColor4f(1.0,1.0,1.0,1.0); - GLuint textureOverlay; - glGenTextures(1, &textureOverlay); - glBindTexture(GL_TEXTURE_2D, textureOverlay); - glTexImage2D(GL_TEXTURE_2D, 0, 4, m_BufferedRegion.GetSize()[0], m_BufferedRegion.GetSize()[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, m_OpenGlImageOverlayBuffer); + glColor4f(1.0,1.0,1.0,0.0); + GLuint texture; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + glTexImage2D(GL_TEXTURE_2D, 0, 3, m_BufferedRegion.GetSize()[0], m_BufferedRegion.GetSize()[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, m_OpenGlBuffer); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // Nearest Filtering glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // Nearest Filtering + // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering + // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering - glBindTexture (GL_TEXTURE_2D, textureOverlay); + glBindTexture (GL_TEXTURE_2D, texture); glBegin (GL_QUADS); int hOffset = this->h() - this->hDisplayed(); - glTexCoord2f (0.0, 1.0); glVertex3f (0.0, 0.0+hOffset, 1.0); - glTexCoord2f (1.0, 1.0); glVertex3f (this->wDisplayed(), 0.0+hOffset, 1.0); - glTexCoord2f (1.0, 0.0); glVertex3f (this->wDisplayed(), this->hDisplayed()+hOffset, 1.0); - glTexCoord2f (0.0, 0.0); glVertex3f (0.0, this->hDisplayed()+hOffset, 1.0); + glTexCoord2f (0.0, 1.0); + glVertex3f (0.0, 0.0+hOffset, 0.0); + glTexCoord2f (1.0, 1.0); + glVertex3f (this->wDisplayed(), 0.0+hOffset, 0.0); + glTexCoord2f (1.0, 0.0); + glVertex3f (this->wDisplayed(), this->hDisplayed()+hOffset, 0.0); + glTexCoord2f (0.0, 0.0); + glVertex3f (0.0, this->hDisplayed()+hOffset, 0.0); glEnd (); + glDisable(GL_TEXTURE_2D); - glDisable(GL_BLEND); #endif - } + // if image overlay is activated, display image overlay + if (m_ImageOverlayVisible) + { +#ifndef OTB_GL_USE_ACCEL + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); + glDrawPixels(m_BufferedRegion.GetSize()[0], + m_BufferedRegion.GetSize()[1], + GL_RGBA, + GL_UNSIGNED_BYTE, + m_OpenGlImageOverlayBuffer); - if(m_FormOverlayVisible) - { - ReverseIteratorType it = m_FormList->ReverseBegin(); - //otbMsgDebugMacro(<<"Formlist size: "<<m_FormList->Size()); - for(;it!=m_FormList->ReverseEnd();++it) + glDisable(GL_BLEND); + glEnd(); +#else + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_TEXTURE_2D); + glColor4f(1.0,1.0,1.0,1.0); + GLuint textureOverlay; + glGenTextures(1, &textureOverlay); + glBindTexture(GL_TEXTURE_2D, textureOverlay); + glTexImage2D(GL_TEXTURE_2D, 0, 4, m_BufferedRegion.GetSize()[0], m_BufferedRegion.GetSize()[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, m_OpenGlImageOverlayBuffer); + glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // Nearest Filtering + glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // Nearest Filtering + + glBindTexture (GL_TEXTURE_2D, textureOverlay); + glBegin (GL_QUADS); + int hOffset = this->h() - this->hDisplayed(); + glTexCoord2f (0.0, 1.0); + glVertex3f (0.0, 0.0+hOffset, 1.0); + glTexCoord2f (1.0, 1.0); + glVertex3f (this->wDisplayed(), 0.0+hOffset, 1.0); + glTexCoord2f (1.0, 0.0); + glVertex3f (this->wDisplayed(), this->hDisplayed()+hOffset, 1.0); + glTexCoord2f (0.0, 0.0); + glVertex3f (0.0, this->hDisplayed()+hOffset, 1.0); + glEnd (); + glDisable(GL_TEXTURE_2D); + glDisable(GL_BLEND); +#endif + + } + + if (m_FormOverlayVisible) + { + ReverseIteratorType it = m_FormList->ReverseBegin(); + //otbMsgDebugMacro(<<"Formlist size: "<<m_FormList->Size()); + for (;it!=m_FormList->ReverseEnd();++it) { it.Get()->Draw(m_OpenGlIsotropicZoom, - m_ViewedRegion.GetIndex()[0], - m_ViewedRegion.GetIndex()[1], - this->h(), m_SubSamplingRate); + m_ViewedRegion.GetIndex()[0], + m_ViewedRegion.GetIndex()[1], + this->h(), m_SubSamplingRate); } - } - } - /** - * Rebuild opengl buffer. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::RebuildOpenGlBuffer(void) +} + +/** + * Rebuild opengl buffer. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::RebuildOpenGlBuffer(void) +{ + //otbMsgDebugMacro(<<"RebuildOpenGlBuffer"); + if (m_OpenGlBuffer != NULL) + { + //otbMsgDebugMacro(<<"Deleting previous buffer ..."); + delete [] m_OpenGlBuffer; + } + //otbMsgDebugMacro(<<"Buffered region: "<<m_BufferedRegion); + unsigned int bufferLenght = 4*m_BufferedRegion.GetNumberOfPixels(); + //otbMsgDebugMacro(<<"New buffer lenght: "<<bufferLenght); + m_OpenGlBuffer = new unsigned char[bufferLenght]; + + typedef itk::ImageRegionConstIteratorWithIndex<ImageType> IteratorType; + IteratorType it(m_Image,m_BufferedRegion); + unsigned int index = 0; + for (it.GoToBegin();!it.IsAtEnd();++it) { - //otbMsgDebugMacro(<<"RebuildOpenGlBuffer"); - if(m_OpenGlBuffer != NULL) - { - //otbMsgDebugMacro(<<"Deleting previous buffer ..."); - delete [] m_OpenGlBuffer; - } - //otbMsgDebugMacro(<<"Buffered region: "<<m_BufferedRegion); - unsigned int bufferLenght = 4*m_BufferedRegion.GetNumberOfPixels(); - //otbMsgDebugMacro(<<"New buffer lenght: "<<bufferLenght); - m_OpenGlBuffer = new unsigned char[bufferLenght]; - - typedef itk::ImageRegionConstIteratorWithIndex<ImageType> IteratorType; - IteratorType it(m_Image,m_BufferedRegion); - unsigned int index = 0; - for(it.GoToBegin();!it.IsAtEnd();++it) - { #ifdef OTB_GL_USE_ACCEL - index = GetBufferIndex(it.GetIndex()); + index = GetBufferIndex(it.GetIndex()); #else - index = GetRevertedBufferIndex(it.GetIndex()); + index = GetRevertedBufferIndex(it.GetIndex()); #endif - switch(m_ViewModel) + switch (m_ViewModel) { case RGB: - { - m_OpenGlBuffer[index] = Normalize(it.Get()[m_RedChannelIndex],m_RedChannelIndex); - m_OpenGlBuffer[index+1] = Normalize(it.Get()[m_GreenChannelIndex],m_GreenChannelIndex); - m_OpenGlBuffer[index+2] = Normalize(it.Get()[m_BlueChannelIndex],m_BlueChannelIndex); - m_OpenGlBuffer[index+3] = 255; - break; - } + { + m_OpenGlBuffer[index] = Normalize(it.Get()[m_RedChannelIndex],m_RedChannelIndex); + m_OpenGlBuffer[index+1] = Normalize(it.Get()[m_GreenChannelIndex],m_GreenChannelIndex); + m_OpenGlBuffer[index+2] = Normalize(it.Get()[m_BlueChannelIndex],m_BlueChannelIndex); + m_OpenGlBuffer[index+3] = 255; + break; + } case GRAYSCALE: - { - unsigned char gray = Normalize(it.Get()[m_RedChannelIndex],m_RedChannelIndex); - m_OpenGlBuffer[index] = gray; - m_OpenGlBuffer[index+1] = gray; - m_OpenGlBuffer[index+2] = gray; - m_OpenGlBuffer[index+3] = 255; - break; - } + { + unsigned char gray = Normalize(it.Get()[m_RedChannelIndex],m_RedChannelIndex); + m_OpenGlBuffer[index] = gray; + m_OpenGlBuffer[index+1] = gray; + m_OpenGlBuffer[index+2] = gray; + m_OpenGlBuffer[index+3] = 255; + break; + } case COMPLEX_MODULUS: - { - double re = static_cast<double>(it.Get()[m_RedChannelIndex]); - double im = static_cast<double>(it.Get()[m_GreenChannelIndex]); - // std::cout << " *** " << m_RedChannelIndex << " " << m_GreenChannelIndex << std::endl; - unsigned char modulus = Normalize(static_cast<PixelType>(vcl_sqrt(static_cast<double>(im*im+re*re))),0); - // std::cout << " ** " << im << " " << re << " -> " << static_cast<int>(modulus) << std::endl; - m_OpenGlBuffer[index] = modulus; - m_OpenGlBuffer[index+1] = modulus; - m_OpenGlBuffer[index+2] = modulus; - m_OpenGlBuffer[index+3] = 255; - break; - } + { + double re = static_cast<double>(it.Get()[m_RedChannelIndex]); + double im = static_cast<double>(it.Get()[m_GreenChannelIndex]); + // std::cout << " *** " << m_RedChannelIndex << " " << m_GreenChannelIndex << std::endl; + unsigned char modulus = Normalize(static_cast<PixelType>(vcl_sqrt(static_cast<double>(im*im+re*re))),0); + // std::cout << " ** " << im << " " << re << " -> " << static_cast<int>(modulus) << std::endl; + m_OpenGlBuffer[index] = modulus; + m_OpenGlBuffer[index+1] = modulus; + m_OpenGlBuffer[index+2] = modulus; + m_OpenGlBuffer[index+3] = 255; + break; + } case COMPLEX_PHASE: - { - unsigned char phase = Normalize(static_cast<PixelType>(vcl_atan2(static_cast<double>(it.Get()[m_GreenChannelIndex]),static_cast<double>(it.Get()[m_RedChannelIndex]))),0); - m_OpenGlBuffer[index] = phase; - m_OpenGlBuffer[index+1] = phase; - m_OpenGlBuffer[index+2] = phase; - m_OpenGlBuffer[index+3] = 255; - break; - } + { + unsigned char phase = Normalize(static_cast<PixelType>(vcl_atan2(static_cast<double>(it.Get()[m_GreenChannelIndex]),static_cast<double>(it.Get()[m_RedChannelIndex]))),0); + m_OpenGlBuffer[index] = phase; + m_OpenGlBuffer[index+1] = phase; + m_OpenGlBuffer[index+2] = phase; + m_OpenGlBuffer[index+3] = 255; + break; + } } - } } - /** - * Rebuild opengl image overlay buffer. - */ - template <class TPixel> - void - ImageWidgetBase<TPixel> - ::RebuildOpenGlImageOverlayBuffer(void) +} +/** + * Rebuild opengl image overlay buffer. + */ +template <class TPixel> +void +ImageWidgetBase<TPixel> +::RebuildOpenGlImageOverlayBuffer(void) +{ + if (m_ImageOverlay->GetNumberOfComponentsPerPixel()<3) { - if(m_ImageOverlay->GetNumberOfComponentsPerPixel()<3) - { - itkExceptionMacro(<<"Image overlay should have at least 3 channels."); - } + itkExceptionMacro(<<"Image overlay should have at least 3 channels."); + } - //otbMsgDebugMacro(<<"RebuildOpenGlImageOverlayBuffer"); - if(m_OpenGlImageOverlayBuffer != NULL) - { - //otbMsgDebugMacro(<<"Deleting previous buffer ..."); - delete [] m_OpenGlImageOverlayBuffer; - } - //otbMsgDebugMacro(<<"Buffered region: "<<m_BufferedRegion); - unsigned int bufferLenght = 4*m_BufferedRegion.GetNumberOfPixels(); - //otbMsgDebugMacro(<<"New buffer lenght: "<<bufferLenght); - m_OpenGlImageOverlayBuffer = new unsigned char[bufferLenght]; - - typedef itk::ImageRegionConstIteratorWithIndex<OverlayImageType> IteratorType; - IteratorType it(m_ImageOverlay,m_BufferedRegion); - unsigned int index = 0; - if(m_BlackTransparency) - { - for(it.GoToBegin();!it.IsAtEnd();++it) + //otbMsgDebugMacro(<<"RebuildOpenGlImageOverlayBuffer"); + if (m_OpenGlImageOverlayBuffer != NULL) + { + //otbMsgDebugMacro(<<"Deleting previous buffer ..."); + delete [] m_OpenGlImageOverlayBuffer; + } + //otbMsgDebugMacro(<<"Buffered region: "<<m_BufferedRegion); + unsigned int bufferLenght = 4*m_BufferedRegion.GetNumberOfPixels(); + //otbMsgDebugMacro(<<"New buffer lenght: "<<bufferLenght); + m_OpenGlImageOverlayBuffer = new unsigned char[bufferLenght]; + + typedef itk::ImageRegionConstIteratorWithIndex<OverlayImageType> IteratorType; + IteratorType it(m_ImageOverlay,m_BufferedRegion); + unsigned int index = 0; + if (m_BlackTransparency) + { + for (it.GoToBegin();!it.IsAtEnd();++it) { #ifdef OTB_GL_USE_ACCEL index = GetBufferIndex(it.GetIndex()); @@ -535,24 +543,24 @@ namespace otb index = GetRevertedBufferIndex(it.GetIndex()); #endif if ((it.Get()[0]==0)&&(it.Get()[1]==0)&&(it.Get()[2]==0)) - { - m_OpenGlImageOverlayBuffer[index] = 0; - m_OpenGlImageOverlayBuffer[index+1] = 0; - m_OpenGlImageOverlayBuffer[index+2] =0; - m_OpenGlImageOverlayBuffer[index+3] = 0; - } - else - { - m_OpenGlImageOverlayBuffer[index] = static_cast<unsigned char>(it.Get()[0]); - m_OpenGlImageOverlayBuffer[index+1] = static_cast<unsigned char>( it.Get()[1]); - m_OpenGlImageOverlayBuffer[index+2] = static_cast<unsigned char>(it.Get()[2]); - m_OpenGlImageOverlayBuffer[index+3] = m_ImageOverlayOpacity; - } - } + { + m_OpenGlImageOverlayBuffer[index] = 0; + m_OpenGlImageOverlayBuffer[index+1] = 0; + m_OpenGlImageOverlayBuffer[index+2] =0; + m_OpenGlImageOverlayBuffer[index+3] = 0; } - else + else { - for(it.GoToBegin();!it.IsAtEnd();++it) + m_OpenGlImageOverlayBuffer[index] = static_cast<unsigned char>(it.Get()[0]); + m_OpenGlImageOverlayBuffer[index+1] = static_cast<unsigned char>( it.Get()[1]); + m_OpenGlImageOverlayBuffer[index+2] = static_cast<unsigned char>(it.Get()[2]); + m_OpenGlImageOverlayBuffer[index+3] = m_ImageOverlayOpacity; + } + } + } + else + { + for (it.GoToBegin();!it.IsAtEnd();++it) { #ifdef OTB_GL_USE_ACCEL index = GetBufferIndex(it.GetIndex()); @@ -564,7 +572,7 @@ namespace otb m_OpenGlImageOverlayBuffer[index+2] =static_cast<unsigned char>(it.Get()[2]); m_OpenGlImageOverlayBuffer[index+3] =m_ImageOverlayOpacity; } - } } +} }// end namespace otb #endif diff --git a/Code/Visu/otbImageWidgetBoxForm.h b/Code/Visu/otbImageWidgetBoxForm.h index 0864e661127e5551d4b41b76f565802789179cf6..0e71a11ebf8a02617f199bae4c4841100dff4a73 100644 --- a/Code/Visu/otbImageWidgetBoxForm.h +++ b/Code/Visu/otbImageWidgetBoxForm.h @@ -29,9 +29,9 @@ namespace otb * */ class ImageWidgetBoxForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: +public: /** Standard class typedefs */ typedef ImageWidgetBoxForm Self; typedef ImageWidgetFormBase Superclass; @@ -54,45 +54,45 @@ class ImageWidgetBoxForm itkGetMacro(Index,IndexType); void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate) - { - if(this->GetVisible()) { - double xul = static_cast<double>((static_cast<double>(m_Index[0])-static_cast<double>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); - double xlr = static_cast<double>((static_cast<double>(m_Index[0]+m_Size[0])-static_cast<double>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); - - double yul = static_cast<double>(static_cast<double>(windowh)+(static_cast<double>(originy)-static_cast<double>(m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); - - double ylr = static_cast<double>(static_cast<double>(windowh)+(static_cast<double>(originy)-static_cast<double>(m_Size[1]+m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); - - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - glBegin(GL_LINE_LOOP); - glVertex2d(xul,yul); - glVertex2d(xul,ylr); - glVertex2d(xlr,ylr); - glVertex2d(xlr,yul); - glEnd(); - glDisable(GL_BLEND); - } - }; - protected: + if (this->GetVisible()) + { + double xul = static_cast<double>((static_cast<double>(m_Index[0])-static_cast<double>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); + double xlr = static_cast<double>((static_cast<double>(m_Index[0]+m_Size[0])-static_cast<double>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); + + double yul = static_cast<double>(static_cast<double>(windowh)+(static_cast<double>(originy)-static_cast<double>(m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); + + double ylr = static_cast<double>(static_cast<double>(windowh)+(static_cast<double>(originy)-static_cast<double>(m_Size[1]+m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); + + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + glBegin(GL_LINE_LOOP); + glVertex2d(xul,yul); + glVertex2d(xul,ylr); + glVertex2d(xlr,ylr); + glVertex2d(xlr,yul); + glEnd(); + glDisable(GL_BLEND); + } + }; +protected: /** Constructor. */ ImageWidgetBoxForm() - { - m_Index.Fill(0); - m_Size.Fill(0); - }; - /** Destructor. */ - ~ImageWidgetBoxForm(){}; - - private: - ImageWidgetBoxForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented - - IndexType m_Index; - SizeType m_Size; + { + m_Index.Fill(0); + m_Size.Fill(0); + }; + /** Destructor. */ + ~ImageWidgetBoxForm() {}; + +private: + ImageWidgetBoxForm(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented + + IndexType m_Index; + SizeType m_Size; }; } // end namespace otb diff --git a/Code/Visu/otbImageWidgetCircleForm.cxx b/Code/Visu/otbImageWidgetCircleForm.cxx index 28a0d51c539bd9b2ea27e5ccfe4eeb1547a58704..9b744f7e3e81d0d3b63bc151466d3a5bf702e5a7 100644 --- a/Code/Visu/otbImageWidgetCircleForm.cxx +++ b/Code/Visu/otbImageWidgetCircleForm.cxx @@ -41,31 +41,31 @@ void ImageWidgetCircleForm ::Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh,unsigned ss_rate) { - if(this->GetVisible()) - { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - } - if(m_Solid) - { - glBegin(GL_POLYGON); - } - else - { - glBegin(GL_LINE_LOOP); - } - for(double angle = 0;angle <= 2*M_PI;angle+=0.01/static_cast<double>(m_Radius)) - { - double xi = m_Center[0]+static_cast<double>(m_Radius)*vcl_sin(angle); - double yi = m_Center[1]+static_cast<double>(m_Radius)*vcl_cos(angle); + if (this->GetVisible()) + { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + } + if (m_Solid) + { + glBegin(GL_POLYGON); + } + else + { + glBegin(GL_LINE_LOOP); + } + for (double angle = 0;angle <= 2*M_PI;angle+=0.01/static_cast<double>(m_Radius)) + { + double xi = m_Center[0]+static_cast<double>(m_Radius)*vcl_sin(angle); + double yi = m_Center[1]+static_cast<double>(m_Radius)*vcl_cos(angle); - double xd = (xi-originx)*openGlZoom*(1/static_cast<double>(ss_rate)); - double yd = windowh+(originy-yi)*openGlZoom*(1/static_cast<double>(ss_rate)); - glVertex2d(xd,yd); - } - glEnd(); - glDisable(GL_BLEND); + double xd = (xi-originx)*openGlZoom*(1/static_cast<double>(ss_rate)); + double yd = windowh+(originy-yi)*openGlZoom*(1/static_cast<double>(ss_rate)); + glVertex2d(xd,yd); + } + glEnd(); + glDisable(GL_BLEND); } } // end namespace otb diff --git a/Code/Visu/otbImageWidgetCircleForm.h b/Code/Visu/otbImageWidgetCircleForm.h index b65910800564a3b095ffe769ffcafece02869496..a94619d414b26eabb906849b377d366eb8938f4c 100644 --- a/Code/Visu/otbImageWidgetCircleForm.h +++ b/Code/Visu/otbImageWidgetCircleForm.h @@ -29,9 +29,9 @@ namespace otb * */ class ITK_EXPORT ImageWidgetCircleForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: +public: /** Standard class typedefs */ typedef ImageWidgetCircleForm Self; typedef ImageWidgetFormBase Superclass; @@ -60,15 +60,15 @@ class ITK_EXPORT ImageWidgetCircleForm void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate); - protected: +protected: /** Constructor. */ ImageWidgetCircleForm(); /** Destructor. */ ~ImageWidgetCircleForm(); - private: +private: ImageWidgetCircleForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented /// true if needed to draw a solid polygon bool m_Solid; diff --git a/Code/Visu/otbImageWidgetFormBase.h b/Code/Visu/otbImageWidgetFormBase.h index 547dba340b64abae0eb6466fbf0b24b9b6c0739e..9990ab3f3c02dba2464fcf6a1a99566cb8d81457 100644 --- a/Code/Visu/otbImageWidgetFormBase.h +++ b/Code/Visu/otbImageWidgetFormBase.h @@ -32,16 +32,16 @@ namespace otb * */ class ITK_EXPORT ImageWidgetFormBase - : public itk::DataObject + : public itk::DataObject { - public: +public: /** Standard class typedefs */ typedef ImageWidgetFormBase Self; typedef itk::DataObject Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; - /** Runtime information */ + /** Runtime information */ itkTypeMacro(ImageWidgetFormBase,DataObject); /** Method for creation through the object factory */ @@ -65,12 +65,12 @@ class ITK_EXPORT ImageWidgetFormBase * \param a The alpha component. */ virtual void SetColor(float r, float g, float b, float a) - { - m_Color[0]=r; - m_Color[1]=g; - m_Color[2]=b; - m_Color[3]=a; - } + { + m_Color[0]=r; + m_Color[1]=g; + m_Color[2]=b; + m_Color[3]=a; + } /** * Draw the form in opengl context. * \param openGlZoom the openGl zoom factor, @@ -79,33 +79,36 @@ class ITK_EXPORT ImageWidgetFormBase * \param windowh The window height, * \param ss_rate The subsampling rate. */ - virtual void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate){}; + virtual void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate) {}; - virtual RegionType GetRegion(void){itkExceptionMacro("Method must be implemented in subclasses!");}; + virtual RegionType GetRegion(void) + { + itkExceptionMacro("Method must be implemented in subclasses!"); + }; - protected: +protected: /** Constructor. */ - ImageWidgetFormBase() - { - m_Visible=true; - m_Color[0]=1; - m_Color[1]=0; - m_Color[2]=0; - m_Color[3]=1; - }; + ImageWidgetFormBase() + { + m_Visible=true; + m_Color[0]=1; + m_Color[1]=0; + m_Color[2]=0; + m_Color[3]=1; + }; - /** Destructor. */ - ~ImageWidgetFormBase() - {}; + /** Destructor. */ + ~ImageWidgetFormBase() + {}; - ColorType m_Color; + ColorType m_Color; - private: - ImageWidgetFormBase(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented +private: + ImageWidgetFormBase(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented - bool m_Visible; + bool m_Visible; }; } // end namespace otb diff --git a/Code/Visu/otbImageWidgetPointForm.h b/Code/Visu/otbImageWidgetPointForm.h index 1e4d69f5a6d43fca98e9e671b71cb2ab38cd1549..9bf083883c66ab93681df1c2853e09188a18edb3 100644 --- a/Code/Visu/otbImageWidgetPointForm.h +++ b/Code/Visu/otbImageWidgetPointForm.h @@ -28,9 +28,9 @@ namespace otb * */ class ImageWidgetPointForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: +public: /** Standard class typedefs */ typedef ImageWidgetPointForm Self; typedef ImageWidgetFormBase Superclass; @@ -52,47 +52,47 @@ class ImageWidgetPointForm itkGetMacro(Index,IndexType); void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate) - { - if(this->GetVisible()) { - unsigned int x,y; - x = static_cast<unsigned int>((m_Index[0]-originx)*openGlZoom*ss_rate); - y = static_cast<unsigned int>(windowh-(m_Index[1]-originy)*openGlZoom*ss_rate); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - glBegin(GL_POINTS); - glVertex2f(x,y); - glEnd(); - } + if (this->GetVisible()) + { + unsigned int x,y; + x = static_cast<unsigned int>((m_Index[0]-originx)*openGlZoom*ss_rate); + y = static_cast<unsigned int>(windowh-(m_Index[1]-originy)*openGlZoom*ss_rate); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + glBegin(GL_POINTS); + glVertex2f(x,y); + glEnd(); } + } RegionType GetRegion(void) - { - RegionType resp; - SizeType size; - size.Fill(1); - resp.SetSize(size); - resp.SetIndex(m_Index); - return resp; - } + { + RegionType resp; + SizeType size; + size.Fill(1); + resp.SetSize(size); + resp.SetIndex(m_Index); + return resp; + } - protected: +protected: /** Constructor. */ - ImageWidgetPointForm() - { - m_Index.Fill(0); - } + ImageWidgetPointForm() + { + m_Index.Fill(0); + } - /** Destructor. */ - ~ImageWidgetPointForm(){}; + /** Destructor. */ + ~ImageWidgetPointForm() {}; - private: - ImageWidgetPointForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented +private: + ImageWidgetPointForm(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented - IndexType m_Index; + IndexType m_Index; }; } // end namespace otb diff --git a/Code/Visu/otbImageWidgetPolygonForm.h b/Code/Visu/otbImageWidgetPolygonForm.h index e196d56beefaaa04c34f76ad4f80c605ef313ed6..c6b8cba0743b597a1bc35db99e7d180da802b710 100644 --- a/Code/Visu/otbImageWidgetPolygonForm.h +++ b/Code/Visu/otbImageWidgetPolygonForm.h @@ -36,9 +36,9 @@ namespace otb */ template<class TValue = double> class ITK_EXPORT ImageWidgetPolygonForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: +public: /** Standard class typedefs */ typedef ImageWidgetPolygonForm Self; typedef ImageWidgetFormBase Superclass; @@ -74,15 +74,15 @@ class ITK_EXPORT ImageWidgetPolygonForm void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate); - protected: +protected: /** Constructor. */ ImageWidgetPolygonForm(); /** Destructor. */ ~ImageWidgetPolygonForm(); - private: +private: ImageWidgetPolygonForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented /** Internal pointer to the otb::Polygon data structure */ PolygonPointerType m_Polygon; diff --git a/Code/Visu/otbImageWidgetPolygonForm.txx b/Code/Visu/otbImageWidgetPolygonForm.txx index 7fd440d7235b303f4cfa8d1b057a7bfbea9d169f..2af158d5466791e522188896a9867a64b7b9b2fa 100644 --- a/Code/Visu/otbImageWidgetPolygonForm.txx +++ b/Code/Visu/otbImageWidgetPolygonForm.txx @@ -42,37 +42,37 @@ void ImageWidgetPolygonForm<TValue> ::Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh,unsigned ss_rate) { - if(this->GetVisible()) - { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GluPolygonDrawingHelper::Pointer polygonDrawer = GluPolygonDrawingHelper::New(); + if (this->GetVisible()) + { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + GluPolygonDrawingHelper::Pointer polygonDrawer = GluPolygonDrawingHelper::New(); - if(m_InternalValueToAlphaChannel) - { - polygonDrawer->Color4d(m_Color[0],m_Color[1],m_Color[2],m_Polygon->GetValue()); - } - else - { - polygonDrawer->Color4d(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - } - polygonDrawer->SetBoundaryOnly(!m_Solid); - VertexListConstIteratorType it = this->GetPolygon()->GetVertexList()->Begin(); + if (m_InternalValueToAlphaChannel) + { + polygonDrawer->Color4d(m_Color[0],m_Color[1],m_Color[2],m_Polygon->GetValue()); + } + else + { + polygonDrawer->Color4d(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + } + polygonDrawer->SetBoundaryOnly(!m_Solid); + VertexListConstIteratorType it = this->GetPolygon()->GetVertexList()->Begin(); - while(it != this->GetPolygon()->GetVertexList()->End()) - { - double x1 = it.Value()[0]; - double y1 = it.Value()[1]; + while (it != this->GetPolygon()->GetVertexList()->End()) + { + double x1 = it.Value()[0]; + double y1 = it.Value()[1]; - x1 = static_cast<int>((x1-originx)*openGlZoom*(1/static_cast<double>(ss_rate))); - y1 = static_cast<int>(windowh+(originy-y1)*openGlZoom*(1/static_cast<double>(ss_rate))); - polygonDrawer->Vertex2d(x1,y1); - ++it; - } - polygonDrawer->RenderPolygon(); - glDisable(GL_BLEND); + x1 = static_cast<int>((x1-originx)*openGlZoom*(1/static_cast<double>(ss_rate))); + y1 = static_cast<int>(windowh+(originy-y1)*openGlZoom*(1/static_cast<double>(ss_rate))); + polygonDrawer->Vertex2d(x1,y1); + ++it; } + polygonDrawer->RenderPolygon(); + glDisable(GL_BLEND); + } } } // end namespace otb diff --git a/Code/Visu/otbImageWidgetPolylineForm.h b/Code/Visu/otbImageWidgetPolylineForm.h index d2a5ce36afb8288fc764edb73ac4d17f8f295d6e..f5a7c679bb8ba933233d155e803b0ba9015ca62c 100644 --- a/Code/Visu/otbImageWidgetPolylineForm.h +++ b/Code/Visu/otbImageWidgetPolylineForm.h @@ -31,62 +31,62 @@ namespace otb */ template<class TValue = double> class ITK_EXPORT ImageWidgetPolylineForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: - /** Standard class typedefs */ - typedef ImageWidgetPolylineForm Self; - typedef ImageWidgetFormBase Superclass; - typedef itk::SmartPointer<Self> Pointer; - typedef itk::SmartPointer<const Self> ConstPointer; - typedef TValue ValueType; - - /** Method for creation through the object factory */ - itkNewMacro(Self); - - /** Runtime information */ - itkTypeMacro(ImageWidgetPolylineForm, ImageWidgetFormBase); - - /** Usefull typedef. */ - typedef itk::Size<2> SizeType; - typedef itk::Index<2> IndexType; - typedef PolyLineParametricPathWithValue<ValueType,2> PolylineType; - typedef typename PolylineType::Pointer PolylinePointerType; - typedef typename PolylineType::VertexType VertexType; - typedef typename PolylineType::VertexListType VertexListType; - typedef typename VertexListType::ConstIterator VertexListConstIteratorType; - typedef typename PolylineType::ContinuousIndexType ContinuousIndexType; - - /** Accessors */ - itkSetMacro(Polyline, PolylinePointerType); - itkGetMacro(Polyline, PolylinePointerType); - itkSetMacro(InternalValueToAlphaChannel,bool); - itkGetMacro(InternalValueToAlphaChannel,bool); - itkSetMacro(LineWidth,double); - itkGetMacro(LineWidth,double); - /** Actually draw the polyline */ - void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate); - - - protected: - /** Constructor. */ - ImageWidgetPolylineForm(); - /** Destructor. */ - ~ImageWidgetPolylineForm(); - - /** Line width*/ - double m_LineWidth; - - private: - ImageWidgetPolylineForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented - - /** Internal pointer to the otb::Polyline data structure */ - PolylinePointerType m_Polyline; - /** True if polygon internal value affects the alpha color value - * (can be used to denote membership values ) - */ - bool m_InternalValueToAlphaChannel; +public: + /** Standard class typedefs */ + typedef ImageWidgetPolylineForm Self; + typedef ImageWidgetFormBase Superclass; + typedef itk::SmartPointer<Self> Pointer; + typedef itk::SmartPointer<const Self> ConstPointer; + typedef TValue ValueType; + + /** Method for creation through the object factory */ + itkNewMacro(Self); + + /** Runtime information */ + itkTypeMacro(ImageWidgetPolylineForm, ImageWidgetFormBase); + + /** Usefull typedef. */ + typedef itk::Size<2> SizeType; + typedef itk::Index<2> IndexType; + typedef PolyLineParametricPathWithValue<ValueType,2> PolylineType; + typedef typename PolylineType::Pointer PolylinePointerType; + typedef typename PolylineType::VertexType VertexType; + typedef typename PolylineType::VertexListType VertexListType; + typedef typename VertexListType::ConstIterator VertexListConstIteratorType; + typedef typename PolylineType::ContinuousIndexType ContinuousIndexType; + + /** Accessors */ + itkSetMacro(Polyline, PolylinePointerType); + itkGetMacro(Polyline, PolylinePointerType); + itkSetMacro(InternalValueToAlphaChannel,bool); + itkGetMacro(InternalValueToAlphaChannel,bool); + itkSetMacro(LineWidth,double); + itkGetMacro(LineWidth,double); + /** Actually draw the polyline */ + void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh, unsigned int ss_rate); + + +protected: + /** Constructor. */ + ImageWidgetPolylineForm(); + /** Destructor. */ + ~ImageWidgetPolylineForm(); + + /** Line width*/ + double m_LineWidth; + +private: + ImageWidgetPolylineForm(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented + + /** Internal pointer to the otb::Polyline data structure */ + PolylinePointerType m_Polyline; + /** True if polygon internal value affects the alpha color value + * (can be used to denote membership values ) + */ + bool m_InternalValueToAlphaChannel; }; } // end namespace otb diff --git a/Code/Visu/otbImageWidgetPolylineForm.txx b/Code/Visu/otbImageWidgetPolylineForm.txx index f89e956227729f609fcd78abcc1342273e256c8d..94c28f574a099076a237cfcaaa96a563b2d3feec 100644 --- a/Code/Visu/otbImageWidgetPolylineForm.txx +++ b/Code/Visu/otbImageWidgetPolylineForm.txx @@ -42,39 +42,39 @@ void ImageWidgetPolylineForm<TValue> ::Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh,unsigned ss_rate) { - if(this->GetVisible()) + if (this->GetVisible()) { - // Set the point size - glLineWidth(m_LineWidth); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - if(m_InternalValueToAlphaChannel) - { - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Polyline->GetValue()); - } - else - { - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - } - glBegin(GL_LINE_STRIP); - - VertexListConstIteratorType it = this->GetPolyline()->GetVertexList()->Begin(); - while(it != this->GetPolyline()->GetVertexList()->End()) - { - double x1 = it.Value()[0]; - double y1 = it.Value()[1]; + // Set the point size + glLineWidth(m_LineWidth); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (m_InternalValueToAlphaChannel) + { + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Polyline->GetValue()); + } + else + { + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + } + glBegin(GL_LINE_STRIP); - x1 = static_cast<int>((x1-originx)*openGlZoom*(1/static_cast<double>(ss_rate))); - y1 = static_cast<int>(windowh+(originy-y1)*openGlZoom*(1/static_cast<double>(ss_rate))); + VertexListConstIteratorType it = this->GetPolyline()->GetVertexList()->Begin(); + while (it != this->GetPolyline()->GetVertexList()->End()) + { + double x1 = it.Value()[0]; + double y1 = it.Value()[1]; - glVertex2f(x1,y1); + x1 = static_cast<int>((x1-originx)*openGlZoom*(1/static_cast<double>(ss_rate))); + y1 = static_cast<int>(windowh+(originy-y1)*openGlZoom*(1/static_cast<double>(ss_rate))); - ++it; - } - glEnd(); - glDisable(GL_BLEND); - glLineWidth(1.0); + glVertex2f(x1,y1); + + ++it; } + glEnd(); + glDisable(GL_BLEND); + glLineWidth(1.0); + } } } // end namespace otb diff --git a/Code/Visu/otbImageWidgetRectangleForm.h b/Code/Visu/otbImageWidgetRectangleForm.h index ee762fc4a10b25848932df5749a2f6bb4963892c..b0279a7177f304f44195737176b5e05b99b2083a 100644 --- a/Code/Visu/otbImageWidgetRectangleForm.h +++ b/Code/Visu/otbImageWidgetRectangleForm.h @@ -28,9 +28,9 @@ namespace otb * */ class ImageWidgetRectangleForm - : public ImageWidgetFormBase + : public ImageWidgetFormBase { - public: +public: /** Standard class typedefs */ typedef ImageWidgetRectangleForm Self; typedef ImageWidgetFormBase Superclass; @@ -54,53 +54,53 @@ class ImageWidgetRectangleForm itkGetMacro(Index,IndexType); void Draw(double openGlZoom, unsigned int originx, unsigned int originy, unsigned int windowh,unsigned int ss_rate) - { - if(this->GetVisible()) { - //otbMsgDebugMacro(<<"Drawing a rectangle."); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); - glBegin(GL_QUADS); + if (this->GetVisible()) + { + //otbMsgDebugMacro(<<"Drawing a rectangle."); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(m_Color[0],m_Color[1],m_Color[2],m_Color[3]); + glBegin(GL_QUADS); - int xul = static_cast<int>((static_cast<int>(m_Index[0])-static_cast<int>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); - int xlr = static_cast<int>((static_cast<int>(m_Index[0]+m_Size[0])-static_cast<int>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); + int xul = static_cast<int>((static_cast<int>(m_Index[0])-static_cast<int>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); + int xlr = static_cast<int>((static_cast<int>(m_Index[0]+m_Size[0])-static_cast<int>(originx))*openGlZoom*(1/static_cast<double>(ss_rate))); - int yul = static_cast<int>(static_cast<int>(windowh)+(static_cast<int>(originy)-static_cast<int>(m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); + int yul = static_cast<int>(static_cast<int>(windowh)+(static_cast<int>(originy)-static_cast<int>(m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); - int ylr = static_cast<int>(static_cast<int>(windowh)+(static_cast<int>(originy)-static_cast<int>(m_Size[1]+m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); + int ylr = static_cast<int>(static_cast<int>(windowh)+(static_cast<int>(originy)-static_cast<int>(m_Size[1]+m_Index[1]))*openGlZoom*(1/static_cast<double>(ss_rate))); - gl_rect(xul,yul,xlr,ylr); - glEnd(); - glDisable(GL_BLEND); - } + gl_rect(xul,yul,xlr,ylr); + glEnd(); + glDisable(GL_BLEND); } + } RegionType GetRegion(void) - { - RegionType resp; - resp.SetSize(m_Size); - resp.SetIndex(m_Index); - return resp; - } + { + RegionType resp; + resp.SetSize(m_Size); + resp.SetIndex(m_Index); + return resp; + } - protected: +protected: /** Constructor. */ - ImageWidgetRectangleForm() - { - m_Index.Fill(0); - m_Size.Fill(0); - } + ImageWidgetRectangleForm() + { + m_Index.Fill(0); + m_Size.Fill(0); + } - /** Destructor. */ - ~ImageWidgetRectangleForm(){} + /** Destructor. */ + ~ImageWidgetRectangleForm() {} - private: - ImageWidgetRectangleForm(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented +private: + ImageWidgetRectangleForm(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented - IndexType m_Index; - SizeType m_Size; + IndexType m_Index; + SizeType m_Size; }; } // end namespace otb diff --git a/Code/Visu/otbImageWidgetTransferFunction.h b/Code/Visu/otbImageWidgetTransferFunction.h index e0f9f111e29a25ca8f31405dd32ae889be621b05..ed663e55dd7281170560d07fefaea089e6151a76 100644 --- a/Code/Visu/otbImageWidgetTransferFunction.h +++ b/Code/Visu/otbImageWidgetTransferFunction.h @@ -29,9 +29,9 @@ namespace otb */ template <class TPixel> class ITK_EXPORT ImageWidgetTransferFunction - : public itk::Object + : public itk::Object { - public: +public: /** Standard typedefs */ typedef ImageWidgetTransferFunction Self; typedef itk::Object Superclass; @@ -56,24 +56,27 @@ class ITK_EXPORT ImageWidgetTransferFunction * \param value the value to map * \return the screen printable value */ - virtual unsigned char Map(PixelType value){return 0;}; + virtual unsigned char Map(PixelType value) + { + return 0; + }; protected: /** Constructor */ ImageWidgetTransferFunction() - { - m_LowerBound = 0; - m_UpperBound = 255; - } + { + m_LowerBound = 0; + m_UpperBound = 255; + } /** Destructor */ virtual ~ImageWidgetTransferFunction() {} - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - os<<indent<<"Lower bound: "<<m_LowerBound<<std::endl; - os<<indent<<"Upper bound: "<<m_UpperBound<<std::endl; - } + { + Superclass::PrintSelf(os,indent); + os<<indent<<"Lower bound: "<<m_LowerBound<<std::endl; + os<<indent<<"Upper bound: "<<m_UpperBound<<std::endl; + } private: ImageWidgetTransferFunction(const Self&); //purposely not implemented @@ -90,9 +93,9 @@ private: */ template <class TPixel> class ITK_EXPORT ImageWidgetAffineTransferFunction - : public ImageWidgetTransferFunction<TPixel> + : public ImageWidgetTransferFunction<TPixel> { - public: +public: /** Standard typedefs */ typedef ImageWidgetAffineTransferFunction Self; typedef ImageWidgetTransferFunction<TPixel> Superclass; @@ -109,26 +112,26 @@ class ITK_EXPORT ImageWidgetAffineTransferFunction typedef TPixel PixelType; virtual unsigned char Map(PixelType value) - { - if(value<this->GetLowerBound()) - { - return 0; - } - else if(value>this->GetUpperBound()) { - return 255; - } - else - { - return static_cast<unsigned char>(vcl_floor(255.*(value-this->GetLowerBound())/(this->GetUpperBound()-this->GetLowerBound())+0.5)); - } - + if (value<this->GetLowerBound()) + { + return 0; } - protected: + else if (value>this->GetUpperBound()) + { + return 255; + } + else + { + return static_cast<unsigned char>(vcl_floor(255.*(value-this->GetLowerBound())/(this->GetUpperBound()-this->GetLowerBound())+0.5)); + } + + } +protected: /** Constructor and destructor */ - ImageWidgetAffineTransferFunction(){} - ~ImageWidgetAffineTransferFunction(){} - private: + ImageWidgetAffineTransferFunction() {} + ~ImageWidgetAffineTransferFunction() {} +private: ImageWidgetAffineTransferFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; @@ -139,9 +142,9 @@ class ITK_EXPORT ImageWidgetAffineTransferFunction */ template <class TPixel> class ITK_EXPORT ImageWidgetSquareRootTransferFunction - : public ImageWidgetTransferFunction<TPixel> + : public ImageWidgetTransferFunction<TPixel> { - public: +public: /** Standard typedefs */ typedef ImageWidgetSquareRootTransferFunction Self; typedef ImageWidgetTransferFunction<TPixel> Superclass; @@ -158,28 +161,28 @@ class ITK_EXPORT ImageWidgetSquareRootTransferFunction typedef TPixel PixelType; virtual unsigned char Map(PixelType value) - { - if(value<this->GetLowerBound()) - { - return 0; - } - else if(value>this->GetUpperBound()) { - return 255; - } - else - { - double b = vcl_sqrt(static_cast<double>(this->GetLowerBound())); - double a = 255. /(vcl_sqrt(static_cast<double>(this->GetUpperBound()))-b); - return static_cast<unsigned char>(vcl_floor(a * (vcl_sqrt(static_cast<double>(value))-b)+0.5)); - } - + if (value<this->GetLowerBound()) + { + return 0; } - protected: + else if (value>this->GetUpperBound()) + { + return 255; + } + else + { + double b = vcl_sqrt(static_cast<double>(this->GetLowerBound())); + double a = 255. /(vcl_sqrt(static_cast<double>(this->GetUpperBound()))-b); + return static_cast<unsigned char>(vcl_floor(a * (vcl_sqrt(static_cast<double>(value))-b)+0.5)); + } + + } +protected: /** Constructor and destructor */ - ImageWidgetSquareRootTransferFunction(){} - ~ImageWidgetSquareRootTransferFunction(){} - private: + ImageWidgetSquareRootTransferFunction() {} + ~ImageWidgetSquareRootTransferFunction() {} +private: ImageWidgetSquareRootTransferFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; @@ -190,9 +193,9 @@ class ITK_EXPORT ImageWidgetSquareRootTransferFunction */ template <class TPixel> class ITK_EXPORT ImageWidgetLogTransferFunction - : public ImageWidgetTransferFunction<TPixel> + : public ImageWidgetTransferFunction<TPixel> { - public: +public: /** Standard typedefs */ typedef ImageWidgetLogTransferFunction Self; typedef ImageWidgetTransferFunction<TPixel> Superclass; @@ -209,28 +212,28 @@ class ITK_EXPORT ImageWidgetLogTransferFunction typedef TPixel PixelType; virtual unsigned char Map(PixelType value) - { - if(value<this->GetLowerBound()) - { - return 0; - } - else if(value>this->GetUpperBound()) - { - return 255; - } - else { - double b = vcl_log(1.+static_cast<double>(this->GetLowerBound())); - double a = 255. /(vcl_log(1.+static_cast<double>(this->GetUpperBound()))-b); - return static_cast<unsigned char>(vcl_floor(a * (vcl_log(1.+static_cast<double>(value))-b)+0.5)); - } - + if (value<this->GetLowerBound()) + { + return 0; + } + else if (value>this->GetUpperBound()) + { + return 255; + } + else + { + double b = vcl_log(1.+static_cast<double>(this->GetLowerBound())); + double a = 255. /(vcl_log(1.+static_cast<double>(this->GetUpperBound()))-b); + return static_cast<unsigned char>(vcl_floor(a * (vcl_log(1.+static_cast<double>(value))-b)+0.5)); } - protected: + + } +protected: /** Constructor and destructor */ - ImageWidgetLogTransferFunction(){} - ~ImageWidgetLogTransferFunction(){} - private: + ImageWidgetLogTransferFunction() {} + ~ImageWidgetLogTransferFunction() {} +private: ImageWidgetLogTransferFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; @@ -240,9 +243,9 @@ class ITK_EXPORT ImageWidgetLogTransferFunction */ template <class TPixel> class ITK_EXPORT ImageWidgetSquareTransferFunction - : public ImageWidgetTransferFunction<TPixel> + : public ImageWidgetTransferFunction<TPixel> { - public: +public: /** Standard typedefs */ typedef ImageWidgetSquareTransferFunction Self; typedef ImageWidgetTransferFunction<TPixel> Superclass; @@ -260,28 +263,28 @@ class ITK_EXPORT ImageWidgetSquareTransferFunction virtual unsigned char Map(PixelType value) - { - if(value<this->GetLowerBound()) - { - return 0; - } - else if(value>this->GetUpperBound()) - { - return 255; - } - else { - double b = vcl_pow(static_cast<double>(this->GetLowerBound()),2); - double a = 255. /(vcl_pow(static_cast<double>(this->GetUpperBound()),2)-b); - return static_cast<unsigned char>(vcl_floor(a * (vcl_pow(static_cast<double>(value),2)-b)+0.5)); - } - + if (value<this->GetLowerBound()) + { + return 0; + } + else if (value>this->GetUpperBound()) + { + return 255; + } + else + { + double b = vcl_pow(static_cast<double>(this->GetLowerBound()),2); + double a = 255. /(vcl_pow(static_cast<double>(this->GetUpperBound()),2)-b); + return static_cast<unsigned char>(vcl_floor(a * (vcl_pow(static_cast<double>(value),2)-b)+0.5)); } - protected: + + } +protected: /** Constructor and destructor */ - ImageWidgetSquareTransferFunction(){} - ~ImageWidgetSquareTransferFunction(){} - private: + ImageWidgetSquareTransferFunction() {} + ~ImageWidgetSquareTransferFunction() {} +private: ImageWidgetSquareTransferFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; diff --git a/Code/Visu/otbVectorImageToColorAnaglyphVectorImageFilter.h b/Code/Visu/otbVectorImageToColorAnaglyphVectorImageFilter.h index edfe96e6d5a21d06f36065204bbbe14a9a6413bd..5a40a427baef8987b4ed1b5478d3a60a898536ce 100644 --- a/Code/Visu/otbVectorImageToColorAnaglyphVectorImageFilter.h +++ b/Code/Visu/otbVectorImageToColorAnaglyphVectorImageFilter.h @@ -24,104 +24,104 @@ PURPOSE. See the above copyright notices for more information. namespace otb { namespace Functor - { - /** \class ColorAnaglyphFunctor - * \brief This functor implements the pixel-wise color anaglyph composition. - * The output pixel is a vector pixel of size 3, where the first component contains the - * value of the first component from the second input pixel, the second component contains - * the value of the second component from the first input pixel, and the third component - * contains the value of the third component of the first input pixel. - * - * the channels indices for the composition can be changed to fit the channel order from - * a specific sensor. - */ - template <class TInputPixel1,class TInputPixel2,class TOutputPixel> - class ColorAnaglyphFunctor - { - public: +{ +/** \class ColorAnaglyphFunctor + * \brief This functor implements the pixel-wise color anaglyph composition. + * The output pixel is a vector pixel of size 3, where the first component contains the + * value of the first component from the second input pixel, the second component contains + * the value of the second component from the first input pixel, and the third component + * contains the value of the third component of the first input pixel. + * + * the channels indices for the composition can be changed to fit the channel order from + * a specific sensor. + */ +template <class TInputPixel1,class TInputPixel2,class TOutputPixel> +class ColorAnaglyphFunctor +{ +public: /// Constructor ColorAnaglyphFunctor() - { - m_RedChannelIndex = 0; - m_GreenChannelIndex = 1; - m_BlueChannelIndex = 2; - }; + { + m_RedChannelIndex = 0; + m_GreenChannelIndex = 1; + m_BlueChannelIndex = 2; + }; /// Destructor - ~ColorAnaglyphFunctor(){}; + ~ColorAnaglyphFunctor() {}; inline TOutputPixel operator()(const TInputPixel1& pixel1, const TInputPixel2& pixel2) - { - TOutputPixel result(3); - result[0]=static_cast<typename TOutputPixel::ValueType>(pixel1[m_RedChannelIndex]); - result[1]=static_cast<typename TOutputPixel::ValueType>(pixel2[m_GreenChannelIndex]); - result[2]=static_cast<typename TOutputPixel::ValueType>(pixel2[m_BlueChannelIndex]); - return result; - } + { + TOutputPixel result(3); + result[0]=static_cast<typename TOutputPixel::ValueType>(pixel1[m_RedChannelIndex]); + result[1]=static_cast<typename TOutputPixel::ValueType>(pixel2[m_GreenChannelIndex]); + result[2]=static_cast<typename TOutputPixel::ValueType>(pixel2[m_BlueChannelIndex]); + return result; + } void SetRedChannelIndex(unsigned int index) - { - m_RedChannelIndex = index; - } + { + m_RedChannelIndex = index; + } void SetGreenChannelIndex(unsigned int index) - { - m_GreenChannelIndex = index; - } + { + m_GreenChannelIndex = index; + } void SetBlueChannelIndex(unsigned int index) - { - m_BlueChannelIndex = index; - } + { + m_BlueChannelIndex = index; + } unsigned int GetRedChannelIndex(void) - { - return m_RedChannelIndex; - } + { + return m_RedChannelIndex; + } unsigned int GetGreenChannelIndex(void) - { - return m_GreenChannelIndex; - } + { + return m_GreenChannelIndex; + } unsigned int GetBlueChannelIndex(void) - { - return m_BlueChannelIndex; - } - private: + { + return m_BlueChannelIndex; + } +private: /// Color composition channels indices unsigned int m_RedChannelIndex; unsigned int m_GreenChannelIndex; unsigned int m_BlueChannelIndex; - }; - } - /** \class VectorImageToColorAnaglyphVectorImageFilter - * \brief This filter implements the synthesis of a grayscale anaglyph image from - * a pair of stereoscopic images. - * The output image is a VectorImage with 3 channels, where the first channel is the first - * channel of the second input image, and the two last channels are the two last channel - * of the first input image. - * - * the channels indices for the composition can be changed to fit the channel order from - * a specific sensor. - * - * \note TOutputImage is supposed to be of type VectorImage. - */ +}; +} +/** \class VectorImageToColorAnaglyphVectorImageFilter + * \brief This filter implements the synthesis of a grayscale anaglyph image from + * a pair of stereoscopic images. + * The output image is a VectorImage with 3 channels, where the first channel is the first + * channel of the second input image, and the two last channels are the two last channel + * of the first input image. + * + * the channels indices for the composition can be changed to fit the channel order from + * a specific sensor. + * + * \note TOutputImage is supposed to be of type VectorImage. + */ template <class TInputImage1, class TInputImage2, class TOutputImage> class ITK_EXPORT VectorImageToColorAnaglyphVectorImageFilter - : public itk::BinaryFunctorImageFilter - < TInputImage1,TInputImage2,TOutputImage, - Functor::ColorAnaglyphFunctor< - typename TInputImage1::PixelType, - typename TInputImage2::PixelType, - typename TOutputImage::PixelType - > > - { - public: + : public itk::BinaryFunctorImageFilter + < TInputImage1,TInputImage2,TOutputImage, + Functor::ColorAnaglyphFunctor< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType + > > +{ +public: /** Standard typedefs */ typedef VectorImageToColorAnaglyphVectorImageFilter Self; typedef itk::BinaryFunctorImageFilter < TInputImage1,TInputImage2,TOutputImage, - Functor::ColorAnaglyphFunctor< - typename TInputImage1::PixelType, - typename TInputImage2::PixelType, - typename TOutputImage::PixelType - > > Superclass; + Functor::ColorAnaglyphFunctor< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType + > > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; @@ -132,10 +132,10 @@ class ITK_EXPORT VectorImageToColorAnaglyphVectorImageFilter itkTypeMacro(VectorImageToColorAnaglyphVectorImageFilter, BinaryFunctorImageFilter); virtual void GenerateOutputInformation(void) - { - Superclass::GenerateOutputInformation(); - this->GetOutput()->SetNumberOfComponentsPerPixel(3); - } + { + Superclass::GenerateOutputInformation(); + this->GetOutput()->SetNumberOfComponentsPerPixel(3); + } itkSetMacro(RedChannelIndex,unsigned int); itkGetMacro(RedChannelIndex,unsigned int); @@ -147,26 +147,26 @@ class ITK_EXPORT VectorImageToColorAnaglyphVectorImageFilter protected: /** Constructor */ VectorImageToColorAnaglyphVectorImageFilter() - { - m_RedChannelIndex = 0; - m_GreenChannelIndex = 1; - m_BlueChannelIndex = 2; - }; + { + m_RedChannelIndex = 0; + m_GreenChannelIndex = 1; + m_BlueChannelIndex = 2; + }; virtual void BeforeThreadedGenerateData(void) - { - this->GetFunctor().SetRedChannelIndex(m_RedChannelIndex); - this->GetFunctor().SetGreenChannelIndex(m_GreenChannelIndex); - this->GetFunctor().SetBlueChannelIndex(m_BlueChannelIndex); - }; + { + this->GetFunctor().SetRedChannelIndex(m_RedChannelIndex); + this->GetFunctor().SetGreenChannelIndex(m_GreenChannelIndex); + this->GetFunctor().SetBlueChannelIndex(m_BlueChannelIndex); + }; /** Destructor */ virtual ~VectorImageToColorAnaglyphVectorImageFilter() {}; - /**PrintSelf method */ + /**PrintSelf method */ virtual void PrintSelf(std::ostream& os, itk::Indent indent) const - { - Superclass::PrintSelf(os,indent); - }; + { + Superclass::PrintSelf(os,indent); + }; private: VectorImageToColorAnaglyphVectorImageFilter(const Self&); //purposely not implemented diff --git a/Code/Visu/otbZoomableImageWidget.h b/Code/Visu/otbZoomableImageWidget.h index f762fb0a1dc131f2f5901bbd972077c6b44cfaa2..47da893a8ae50c98f763a975f97a6c0d37053ae0 100644 --- a/Code/Visu/otbZoomableImageWidget.h +++ b/Code/Visu/otbZoomableImageWidget.h @@ -28,9 +28,9 @@ namespace otb */ template <class TPixel> class ZoomableImageWidget - : public ImageWidgetBase<TPixel> + : public ImageWidgetBase<TPixel> { - public: +public: /** Standard class typedefs */ typedef ZoomableImageWidget Self; typedef ImageWidgetBase<TPixel> Superclass; @@ -70,17 +70,17 @@ class ZoomableImageWidget void SetZoomUpperLeftCorner(IndexType index); itkGetMacro(ZoomUpperLeftCorner,IndexType); - protected: +protected: /** Constructor. */ - ZoomableImageWidget(); - /** Destructor. */ - ~ZoomableImageWidget(); + ZoomableImageWidget(); + /** Destructor. */ + ~ZoomableImageWidget(); - private: - ZoomableImageWidget(const Self&);// purposely not implemented - void operator=(const Self&);// purposely not implemented +private: + ZoomableImageWidget(const Self&);// purposely not implemented + void operator=(const Self&);// purposely not implemented - IndexType m_ZoomUpperLeftCorner; + IndexType m_ZoomUpperLeftCorner; }; } // end namespace otb #ifndef OTB_MANUAL_INSTANTIATION diff --git a/Code/Visu/otbZoomableImageWidget.txx b/Code/Visu/otbZoomableImageWidget.txx index afbd728c6f9ecb3fbc0b261443b381d03b4a0769..e9811c946ba93625d5b51217b0fbdcfd4cea3d11 100644 --- a/Code/Visu/otbZoomableImageWidget.txx +++ b/Code/Visu/otbZoomableImageWidget.txx @@ -49,20 +49,20 @@ void ZoomableImageWidget<TPixel> ::Init(int x, int y, int w, int h, const char * l) { - if(!this->GetInput()) - { - itkExceptionMacro("No input image!"); - } + if (!this->GetInput()) + { + itkExceptionMacro("No input image!"); + } else - { - Superclass::Init(x,y,w,h,l); + { + Superclass::Init(x,y,w,h,l); // if(this->GetImageOverlayVisible()) // { // this->GetInputOverlay()->Update(); // } - this->label(l); - this->resize(x, y, w, h); - } + this->label(l); + this->resize(x, y, w, h); + } } /** * Resize the widget. @@ -98,7 +98,7 @@ ZoomableImageWidget<TPixel> IndexType bufferedULCorner = buffered.GetIndex(); IndexType viewedRDCorner = viewed.GetIndex()+viewed.GetSize(); IndexType bufferedRDCorner = buffered.GetIndex()+buffered.GetSize(); - // return ( viewedULCorner[0]<bufferedULCorner[0] +// return ( viewedULCorner[0]<bufferedULCorner[0] // ||viewedULCorner[1]<bufferedULCorner[1] // ||viewedRDCorner[0]>bufferedRDCorner[0] // ||viewedRDCorner[1]>bufferedRDCorner[1]); @@ -125,7 +125,7 @@ void ZoomableImageWidget<TPixel> ::SetZoomFactor(double zoomFactor) { - if(zoomFactor<1) + if (zoomFactor<1) itkExceptionMacro(<<"Zoom factor must be >1 !"); RegionType region = this->GetViewedRegion(); @@ -139,11 +139,11 @@ ZoomableImageWidget<TPixel> newRegion.SetIndex(m_ZoomUpperLeftCorner); newRegion.SetSize(newSize); /// Bug correction, segfault zooming out too much - if(this->GetInput() && this->GetInput()->GetLargestPossibleRegion().IsInside(newRegion)) - { - this->SetViewedRegion(newRegion); - this->SetOpenGlIsotropicZoom(zoomFactor); - } + if (this->GetInput() && this->GetInput()->GetLargestPossibleRegion().IsInside(newRegion)) + { + this->SetViewedRegion(newRegion); + this->SetOpenGlIsotropicZoom(zoomFactor); + } } /** * Set a new zoom factor (>1).