otbDimensionalityReduction.cxx 18.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$


  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.


     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"


#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbNAPCAImageFilter.h"
#include "otbLocalActivityVectorImageFilter.h"
#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbFastICAImageFilter.h"

//#include "otbVirtualDimensionality.h"

#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

namespace otb
{
namespace Wrapper
{

38
class DimensionalityReduction: public Application
39 40 41
{
public:
  /** Standard class typedefs. */
42
  typedef DimensionalityReduction Self;
43 44 45 46
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

47
  // Dimensionality reduction typedef
48 49
  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType;

50
  typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

  // Reduction dimensio filters
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType;
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType;
  //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD >

  typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType;

  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD>
      NAPCAForwardFilterType;
  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE>
      NAPCAInverseFilterType;

  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType;

  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD>
      ICAForwardFilterType;
  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE>
      ICAInverseFilterType;

71 72 73
  typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType;

  typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType                 MatrixType;
74 75 76 77 78 79 80 81 82
  //typedef otb::VirtualDimensionality<double> VDFilterType;


  // output rescale
  typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
  typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;

  /** Standard macro */
  itkNewMacro(Self)
OTB Bot's avatar
OTB Bot committed
83
;
84

85
  itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application)
OTB Bot's avatar
OTB Bot committed
86
;
87 88

private:
89
  void DoInit() ITK_OVERRIDE
90
  {
91
    SetName("DimensionalityReduction");
92
    SetDescription("Perform Dimension reduction of the input image.");
93
    SetDocName("Dimensionality reduction");
94 95
    SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.");
    SetDocLimitations("This application does not provide the inverse transform and the transformation matrix export for the MAF.");
96 97 98 99 100 101 102 103
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(
                  "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)");

    AddDocTag(Tags::DimensionReduction);
    AddDocTag(Tags::Filter);

    AddParameter(ParameterType_InputImage, "in", "Input Image");
104
    SetParameterDescription("in", "The input image to apply dimensionality reduction.");
105 106
    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues.");
107
    MandatoryOff("out");
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    AddParameter(ParameterType_Group, "rescale", "Rescale Output.");

    MandatoryOff("rescale");
    //  AddChoice("rescale.no","No rescale");
    // AddChoice("rescale.minmax","rescale to min max value");

    AddParameter(ParameterType_Float, "rescale.outmin", "Output min value");
    AddParameter(ParameterType_Float, "rescale.outmax", "Output max value");
    SetDefaultParameterFloat("rescale.outmin", 0.0);
    SetParameterDescription("rescale.outmin", "Minimum value of the output image.");
    SetDefaultParameterFloat("rescale.outmax", 255.0);
    SetParameterDescription("rescale.outmax", "Maximum value of the output image.");

    AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image");
    SetParameterDescription("outinv", "reconstruct output image.");
    MandatoryOff("outinv");

    AddParameter(ParameterType_Choice, "method", "Algorithm");
    SetParameterDescription("method", "Selection of the reduction dimension method.");

    AddChoice("method.pca", "PCA");
    SetParameterDescription("method.pca", "Principal Component Analysis.");
    AddChoice("method.napca", "NA-PCA");
    SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis.");
    AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusx", 1);
    SetDefaultParameterInt("method.napca.radiusx", 1);
    AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusy", 1);
    SetDefaultParameterInt("method.napca.radiusy", 1);

    AddChoice("method.maf", "MAF");
    SetParameterDescription("method.maf", "Maximum Autocorrelation Factor.");
    AddChoice("method.ica", "ICA");
142
    SetParameterDescription("method.ica", "Independent Component Analysis.");
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations ");
    SetMinimumParameterIntValue("method.ica.iter", 1);
    SetDefaultParameterInt("method.ica.iter", 20);
    MandatoryOff("method.ica.iter");

    AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]");
    SetMinimumParameterFloatValue("method.ica.mu", 0.);
    SetMaximumParameterFloatValue("method.ica.mu", 1.);
    SetDefaultParameterFloat("method.ica.mu", 1.);
    MandatoryOff("method.ica.mu");

    //AddChoice("method.vd","virual Dimension");
    //SetParameterDescription("method.vd","Virtual Dimension.");
    //MandatoryOff("method");

    AddParameter(ParameterType_Int, "nbcomp", "Number of Components.");
Jonathan Guinet's avatar
Jonathan Guinet committed
159
    SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept.");
160 161 162 163 164
    SetDefaultParameterInt("nbcomp", 0);
    MandatoryOff("nbcomp");
    SetMinimumParameterIntValue("nbcomp", 0);

    AddParameter(ParameterType_Empty, "normalize", "Normalize.");
165
    SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction.");
166 167
    MandatoryOff("normalize");

168
    AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output (text format)");
169 170 171
    SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)");
    MandatoryOff("outmatrix");

172 173 174 175 176 177
    // Doc example parameter settings
    SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
    SetDocExampleParameterValue("out", "FilterOutput.tif");
    SetDocExampleParameterValue("method", "pca");
  }

178
  void DoUpdateParameters() ITK_OVERRIDE
179
  {
OTB Bot's avatar
OTB Bot committed
180 181
              if (HasValue("in"))
              {
182
                     FloatVectorImageType::Pointer inImage = this->GetParameterImage("in");
OTB Bot's avatar
OTB Bot committed
183 184 185 186 187 188 189 190 191 192 193 194
                     inImage->UpdateOutputInformation();

                     // Update the values of the channels to be selected
                     unsigned int       nbComponents = inImage->GetNumberOfComponentsPerPixel();
                     unsigned int nbComp = static_cast<unsigned int> (GetParameterInt("nbcomp"));
                     if (nbComp > nbComponents)
                     {
                            SetParameterInt("nbcomp", nbComponents);
                            otbAppLogINFO( << "number of selected components can't exceed image dimension : "<<nbComponents );
                     }

              }
195 196
              if (GetParameterInt("method")==2) //maf
              {
OTB Bot's avatar
OTB Bot committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210
                     if (this->GetParameterString("outinv").size()!= 0)
                     {
                            otbAppLogWARNING(<<"This application only provides the forward transform for the MAF method.");
                            this->SetParameterString("outinv", "");
                     }
                     this->DisableParameter("outinv");

                     if (this->GetParameterString("outmatrix").size()!= 0)
                     {
                            otbAppLogWARNING(<<"No transformation matrix available for MAF method.");
                            this->SetParameterString("outmatrix", "");
                     }
                     this->DisableParameter("outmatrix");

211
                     FloatVectorImageType::Pointer inImage = this->GetParameterImage("in");
OTB Bot's avatar
OTB Bot committed
212 213 214 215 216 217 218 219 220 221 222 223
                     inImage->UpdateOutputInformation();

                     // Update the values of the channels to be selected
                     unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
                     unsigned int nbComp = static_cast<unsigned int> (GetParameterInt("nbcomp"));
                     if ((nbComp != 0) && (nbComp != nbComponents))
                     {
                            SetParameterInt("nbcomp", nbComponents);
                            otbAppLogINFO( << "all components are kept when using MAF filter method.");
                     }

              }
224 225
  }

226
  void DoExecute() ITK_OVERRIDE
227 228 229 230
  {

    // Get Parameters
    int nbComp = GetParameterInt("nbcomp");
231
    bool normalize = IsParameterEnabled("normalize");
232 233
    bool rescale = IsParameterEnabled("rescale");

234
    bool invTransform = HasValue("outinv") && IsParameterEnabled("outinv");
235 236 237 238 239
    switch (GetParameterInt("method"))
      {
      // PCA Algorithm
      case 0:
        {
240

241 242 243 244 245 246
        otbAppLogDEBUG( << "PCA Algorithm ");
        PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New();
        m_ForwardFilter = filter;
        PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New();
        m_InverseFilter = invFilter;

247

248 249
        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
250 251 252
        filter->SetUseNormalization(normalize);        
        m_ForwardFilter->GetOutput()->UpdateOutputInformation();
        
253
        if (invTransform)
254
          {  
255 256 257
          invFilter->SetInput(m_ForwardFilter->GetOutput());
          if (normalize)
            {
258
            otbAppLogINFO( << "Normalization MeanValue:"<<filter->GetMeanValues() );
259
            invFilter->SetMeanValues(filter->GetMeanValues());
260 261 262 263
            // By default normalization by std dev is deactivated in
            //forward filter, and GetStdDevValues() returns an empty
            //vector, which confuses the invFilter.
            //invFilter->SetStdDevValues(filter->GetStdDevValues());
264 265 266
            }

          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
267
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
268 269
          }

270
        m_TransformationMatrix = filter->GetTransformationMatrix();
271

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
        break;
        }
      case 1:
        {
        otbAppLogDEBUG( << "NA-PCA Algorithm ");

        // NA-PCA

        unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx"));
        unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy"));

        // Noise filtering
        NoiseFilterType::RadiusType radius = { { radiusX, radiusY } };

        NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New();
        m_ForwardFilter = filter;
        NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New();
        m_InverseFilter = invFilter;

291

292 293 294 295
        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetUseNormalization(normalize);
        filter->GetNoiseImageFilter()->SetRadius(radius);
296

297 298
        m_ForwardFilter->GetOutput()->UpdateOutputInformation();
        
299 300 301 302
        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());
303
          otbAppLogINFO( << "Normalization MeanValue:"<<filter->GetMeanValues() );
304 305 306
          invFilter->SetMeanValues(filter->GetMeanValues());
          if (normalize)
            {
307
            otbAppLogINFO( << "Normalization StdDevValue:"<<filter->GetStdDevValues() );
308
            invFilter->SetStdDevValues(filter->GetStdDevValues());
309
            
310
            }
311
          invFilter->SetUseNormalization(normalize);
312
          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
313
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
314
          }
315

316
        m_TransformationMatrix = filter->GetTransformationMatrix();
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

        break;
        }
      case 2:
        {
        otbAppLogDEBUG( << "MAF Algorithm ");
        MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New();
        m_ForwardFilter = filter;
        filter->SetInput(GetParameterFloatVectorImage("in"));
        otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() );

        break;
        }
      case 3:
        {
332
        otbAppLogDEBUG( << "Fast ICA Algorithm ");
333 334 335 336 337 338 339 340 341 342 343 344 345

        unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter"));
        double mu = static_cast<double> (GetParameterFloat("method.ica.mu"));

        ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New();
        m_ForwardFilter = filter;
        ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetNumberOfIterations(nbIterations);
        filter->SetMu(mu);
346

347 348
        m_ForwardFilter->GetOutput()->UpdateOutputInformation();
        
349 350 351 352
        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());
353 354 355 356
          otbAppLogINFO( << "Normalization MeanValue:"<<filter->GetMeanValues() );
          invFilter->SetMeanValues(filter->GetMeanValues());
          otbAppLogINFO( << "Normalization StdDevValue:"<<filter->GetStdDevValues() );
          invFilter->SetStdDevValues(filter->GetStdDevValues());
357 358 359 360

          invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix());
          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          }
361 362 363

        m_TransformationMatrix = filter->GetTransformationMatrix();

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
        break;
        }
        /* case 4:
         {
         otbAppLogDEBUG( << "VD Algorithm");

         break;
         }*/

      default:
        {
        otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl);
        break;

        }
        return;
      }

    if (invTransform)
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
386 387
        this->DisableParameter("outinv");
        otbAppLogWARNING(<<"This application only provides the forward transform for the MAF method.");
388 389 390 391
        }
      else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput());
      }

392
    //Write transformation matrix
393
    if (this->GetParameterString("outmatrix").size() != 0)
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
        otbAppLogWARNING(<<"No transformation matrix available for MAF.");
        }
      else
        {
        //Write transformation matrix
        std::ofstream outFile;
        outFile.open(this->GetParameterString("outmatrix").c_str());
        outFile << std::fixed;
        outFile.precision(10);

        outFile << m_TransformationMatrix;
        outFile.close();
        }
      }

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    if (!rescale)
      {
      SetParameterOutputImage("out", m_ForwardFilter->GetOutput());
      }
    else
      {
      otbAppLogDEBUG( << "Rescaling " )
      otbAppLogDEBUG( << "Starting Min/Max computation" )

      m_MinMaxFilter = MinMaxFilterType::New();
      m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput());
      m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50);

      AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
      m_MinMaxFilter->Update();

      otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
          << " max=" << m_MinMaxFilter->GetMaximum() )

      FloatVectorImageType::PixelType inMin, inMax;

      m_RescaleFilter = RescaleImageFilterType::New();
      m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput());
      m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum());
      m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum());

      FloatVectorImageType::PixelType outMin, outMax;
      outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMin.Fill(GetParameterFloat("rescale.outmin"));
      outMax.Fill(GetParameterFloat("rescale.outmax"));

      m_RescaleFilter->SetOutputMinimum(outMin);
      m_RescaleFilter->SetOutputMaximum(outMax);
      m_RescaleFilter->UpdateOutputInformation();

      SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
      }

451

452 453 454 455
  }

  MinMaxFilterType::Pointer               m_MinMaxFilter;
  RescaleImageFilterType::Pointer         m_RescaleFilter;
456 457 458
  DimensionalityReductionFilter::Pointer  m_ForwardFilter;
  DimensionalityReductionFilter::Pointer  m_InverseFilter;
  MatrixType                              m_TransformationMatrix;
459 460 461 462 463
};

}
}

464
OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction)