otbZonalStatistics.cxx 19.2 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
/*
 * Copyright (C) 2017 National Research Institute of Science and
 * Technology for Environment and Agriculture (IRSTEA)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "itkFixedArray.h"
#include "itkObjectFactory.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"

// Application engine
#include "otbStandardFilterWatcher.h"

// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"

38 39 40 41
// Raster --> Vector
#include "otbLabelImageToVectorDataFilter.h"
#include "itkBinaryThresholdImageFilter.h"

42 43
#include "otbUnaryFunctorImageFilter.h"

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
namespace otb
{

namespace Wrapper
{

class ZonalStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ZonalStatistics               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /* Typedefs */
60
  typedef Int32ImageType                LabelImageType;
61 62 63
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
64
                                                   FloatVectorImageType>             VectorDataReprojFilterType;
65
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
66
                                            LabelImageType>                   RasterizeFilterType;
67 68
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
69
  TreeIteratorType;
70 71
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
72
  PolygonListPointerType;
73
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
74
                                                          LabelImageType>                   StatsFilterType;
75
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
76
  StatsWriterType;
77
  typedef otb::LabelImageToVectorDataFilter<LabelImageType>
78
  LabelImageToVectorFilterType;
79
  typedef itk::BinaryThresholdImageFilter<LabelImageType,
80
                                          LabelImageType>                   ThresholdFilterType;
81

82 83 84 85 86 87 88 89
  struct EncoderFunctorType
  {
    StatsFilterType::LabelPopulationMapType* m_CountMap;
    StatsFilterType::PixelValueMapType* m_MeanMap;
    StatsFilterType::PixelValueMapType* m_StdMap;
    StatsFilterType::PixelValueMapType* m_MinMap;
    StatsFilterType::PixelValueMapType* m_MaxMap;
    size_t m_NbInputComponents;
90 91 92 93
    LabelValueType m_InNoData;
    LabelValueType m_OutBvValue;
    static constexpr size_t m_NbStatsPerBand{4};
    static constexpr size_t m_NbGlobalStats{1};
94 95 96

    size_t GetOutputSize()
    {
97
      return m_NbInputComponents*m_NbStatsPerBand+m_NbGlobalStats;
98 99 100 101 102
    }

    FloatVectorImageType::PixelType operator()(LabelValueType const &pix)
    {
      FloatVectorImageType::PixelType outPix(GetOutputSize());
103 104
      outPix.Fill(m_OutBvValue);
      if(pix != m_InNoData)
105
        {
106 107 108 109 110 111 112 113
        outPix[0] = (*m_CountMap)[pix];
        for(size_t i=0; i<m_NbInputComponents; ++i)
          {
          outPix[i*m_NbStatsPerBand+1] = (*m_MeanMap)[pix][i];
          outPix[i*m_NbStatsPerBand+2] = (*m_StdMap)[pix][i];
          outPix[i*m_NbStatsPerBand+3] = (*m_MinMap)[pix][i];
          outPix[i*m_NbStatsPerBand+4] = (*m_MaxMap)[pix][i];
          }
114 115 116
        }
      return outPix;
    }
117

118 119
    bool operator != (const EncoderFunctorType& other)
    {
120 121 122 123 124 125 126 127 128 129
      if ( m_CountMap != other.m_CountMap||
           m_MeanMap != other.m_MeanMap||
           m_StdMap != other.m_StdMap||
           m_MinMap != other.m_MinMap||
           m_MaxMap != other.m_MaxMap||
           m_NbInputComponents != other.m_NbInputComponents ||
           m_InNoData != other.m_InNoData ||
           m_OutBvValue != other.m_OutBvValue )
        return true;
      else return false;
130 131 132 133 134
    }
  };
  typedef otb::UnaryFunctorImageFilter<LabelImageType, 
                                       FloatVectorImageType, 
                                       EncoderFunctorType> EncoderFilterType;
135 136 137 138
  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

139
  void DoInit() override
140 141 142 143 144 145 146 147
  {

    SetName("ZonalStatistics");
    SetDescription("This application computes zonal statistics");

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
148 149 150 151 152 153 154 155 156 157
                          "The application inputs one input multiband image, and another input for zones definition. "
                          "Zones can be defined with a label image (inzone.labelimage.in) or a vector data layer "
                          "(inzone.vector.in). The following statistics are computed over each zones: mean, min, max, "
                          "and standard deviation. Statistics can be exported in a vector layer (if the input zone "
                          "definition is a label image, it will be vectorized) or in a XML file");
    SetDocLimitations("1) The inzone.vector.in must fit in memory (if \"inzone\" is \"vector\"). 2) The vectorized label "
                      "image must also fit in memory (if \"out\" is \"vector\"): if not, consider using \"out\" to "
                      "\"xml\"");
    SetDocAuthors("Remi Cresson, Jordi Inglada");
    SetDocSeeAlso("ComputeImagesStatistics");
158 159 160 161 162

    AddDocTag(Tags::Manip);
    AddDocTag(Tags::Analysis);

    // Input image
163 164
    AddParameter(ParameterType_InputImage, "in",   "Input Image");
    AddParameter(ParameterType_Float,      "inbv", "Background value to ignore in statistics computation");
165
    MandatoryOff                          ("inbv");
166

167 168 169 170
    // Input zone mode
    AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
    AddChoice("inzone.vector",     "Input objects from vector data");
    AddChoice("inzone.labelimage", "Input objects from label image");
171 172

    // Input for vector mode
173 174 175
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

176 177

    // Input for label image mode
178 179 180 181 182 183 184 185 186 187
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    MandatoryOff                          ("inzone.labelimage.nodata");


    // Output stats mode
    AddParameter(ParameterType_Choice, "out", "Format of the output stats");
    AddChoice("out.vector", "Output vector data");
    AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
    AddChoice("out.xml", "Output XML file");
188
    AddParameter(ParameterType_String, "out.xml.filename", "Filename for the output xml file");
189
   AddChoice("out.raster", "Output raster image");
190 191 192
   AddParameter(ParameterType_OutputImage, "out.raster.filename", "File name for the raster image");    
   AddParameter(ParameterType_Float,      "out.raster.bv", "Background value for the output raster");
   MandatoryOff                          ("out.raster.bv");
193

194
   AddRAMParameter();
195 196 197

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
198 199
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");
200

201
    SetOfficialDocLink();
202 203
  }

204
  void DoUpdateParameters() override
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
  {
    // Nothing to do here : all parameters are independent
  }

  // Returns a string of the kind "prefix_i"
  const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
  {
    std::stringstream ss;
    ss << prefix << "_" << i;
    return ss.str();
  }

  // Returns a null pixel which has the same number of components per pixels as img
  FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
  {
    const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
221
    FloatVectorImageType::PixelType pix(nBands);
222 223 224 225
    pix.Fill(0);
    return pix;
  }

226 227 228 229 230 231 232 233 234
  void GetStats()
  {
    m_CountMap = m_StatsFilter->GetLabelPopulationMap();
    m_MeanMap = m_StatsFilter->GetMeanValueMap();
    m_StdMap = m_StatsFilter->GetStandardDeviationValueMap();
    m_MinMap = m_StatsFilter->GetMinValueMap();
    m_MaxMap = m_StatsFilter->GetMaxValueMap();
  }

235
  void PrepareForLabelImageInput()
236
  {
237 238 239 240 241 242 243
    otbAppLogINFO("Zone definition: label image");
    // Computing stats
    m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
    m_StatsFilter->Update();
    // In this zone definition mode, the user can provide a no-data value for the labels
    if (HasUserValue("inzone.labelimage.nodata"))
      m_IntNoData = GetParameterInt("inzone.labelimage.nodata");
244
    GetStats();
245
  }
246

247 248 249 250
  void PrepareForVectorDataInput()
  {
    otbAppLogINFO("Zone definition: vector");
    otbAppLogINFO("Loading vector data...");
251
    m_VectorDataSrc = GetParameterVectorData("inzone.vector.in");
252 253 254 255 256 257
    // Reproject vector data
    if (GetParameterInt("inzone.vector.reproject") != 0)
      {
      ReprojectVectorDataIntoInputImage();
      }
    RasterizeInputVectorData();
258 259 260
    // Computing stats
    m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
    m_StatsFilter->Update();
261
    GetStats();
262 263 264 265 266 267
  }

  void ReprojectVectorDataIntoInputImage()
  {
    otbAppLogINFO("Vector data reprojection enabled");
    m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
268
    m_VectorDataReprojectionFilter->SetInputVectorData(m_VectorDataSrc.GetPointer());
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    m_VectorDataReprojectionFilter->SetInputImage(m_InputImage);
    AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
    m_VectorDataReprojectionFilter->Update();
    m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
  }

  void RasterizeInputVectorData()
  {
    // Rasterize vector data
    m_RasterizeFilter = RasterizeFilterType::New();
    m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
    m_RasterizeFilter->SetOutputOrigin(m_InputImage->GetOrigin());
    m_RasterizeFilter->SetOutputSpacing(m_InputImage->GetSignedSpacing());
    m_RasterizeFilter->SetOutputSize(m_InputImage->GetLargestPossibleRegion().GetSize());
    m_RasterizeFilter->SetOutputProjectionRef(m_InputImage->GetProjectionRef());
    m_RasterizeFilter->SetBurnAttribute("________");
    m_RasterizeFilter->SetDefaultBurnValue(0);
    m_RasterizeFilter->SetGlobalWarningDisplay(false);
    m_RasterizeFilter->SetBackgroundValue(m_IntNoData);
288
    AddProcess(m_RasterizeFilter, "Rasterize input vector data");
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  }

  void RemoveNoDataEntry()
  {
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      otbAppLogINFO("Removing entries for label value " << m_IntNoData);

      m_CountMap.erase(m_IntNoData);
      m_MeanMap.erase(m_IntNoData);
      m_StdMap.erase(m_IntNoData);
      m_MinMap.erase(m_IntNoData);
      m_MaxMap.erase(m_IntNoData);
      }
  }


307
  void GenerateVectorDataFromLabelImage()
308 309 310 311 312 313 314 315 316 317
  {    
    // Mask for label image
    m_InputThresholdFilter = ThresholdFilterType::New();
    m_InputThresholdFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
    m_InputThresholdFilter->SetInsideValue(0);
    m_InputThresholdFilter->SetOutsideValue(1);
    m_InputThresholdFilter->SetLowerThreshold(m_IntNoData);
    m_InputThresholdFilter->SetUpperThreshold(m_IntNoData);
    m_InputThresholdFilter->UpdateOutputInformation();
    AddProcess(m_InputThresholdFilter, "Threshold label image");
318 319 320
    // Vectorize the image
    m_LabelImageToVectorFilter = LabelImageToVectorFilterType::New();
    m_LabelImageToVectorFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
321
    m_LabelImageToVectorFilter->SetInputMask(m_InputThresholdFilter->GetOutput());
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    m_LabelImageToVectorFilter->SetFieldName("polygon_id");
    AddProcess(m_LabelImageToVectorFilter, "Vectorize label image");
    m_LabelImageToVectorFilter->Update();
    // The source vector data is the vectorized label image
    m_VectorDataSrc = m_LabelImageToVectorFilter->GetOutput();
  }

  void WriteVectorData()
  {
    // Add statistics fields
    otbAppLogINFO("Writing output vector data");
    LabelValueType internalFID = -1;
    m_NewVectorData = VectorDataType::New();
    DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
    DataNodeType::Pointer document = DataNodeType::New();
    document->SetNodeType(otb::DOCUMENT);
    m_NewVectorData->GetDataTree()->Add(document, root);
    DataNodeType::Pointer folder = DataNodeType::New();
    folder->SetNodeType(otb::FOLDER);
    m_NewVectorData->GetDataTree()->Add(folder, document);
    m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
    TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
    itVector.GoToBegin();

    while (!itVector.IsAtEnd())
      {
      if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
        {

        DataNodeType::Pointer currentGeometry = itVector.Get();
        if (m_FromLabelImage)
          internalFID = currentGeometry->GetFieldAsInt("polygon_id");
        else
          internalFID++;

        // Add the geometry with the new fields
        if (m_CountMap.count(internalFID) > 0)
          {
          currentGeometry->SetFieldAsDouble("count", m_CountMap[internalFID] );
          for (unsigned int band = 0 ; band < m_InputImage->GetNumberOfComponentsPerPixel() ; band++)
            {
            currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), m_MeanMap[internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), m_StdMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), m_MinMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), m_MaxMap [internalFID][band] );
            }
          m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
          }
        }
      ++itVector;
      } // next feature
373

374 375 376
    SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
  }

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  void SetOutBvValue()
  {
    if (HasUserValue("out.raster.bv"))
      {
      m_OutBvValue = GetParameterFloat("out.raster.bv");
      }
    else if(HasUserValue("inbv"))
      {
      m_OutBvValue = GetParameterFloat("inbv");
      }
    else
      {
      m_OutBvValue = m_IntNoData;
      }
  }

393
  void WriteRasterData()
394
  {
395 396
    
    otbAppLogINFO("Writing output raster data");
397 398
    SetOutBvValue();
    m_OutputThresholdFilter = ThresholdFilterType::New();
399 400
    m_EncoderFilter = EncoderFilterType::New();
    if(m_FromLabelImage)
401 402 403
        {
        m_EncoderFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
        }
404 405
    else
      {
406
      m_EncoderFilter->SetInput(m_RasterizeFilter->GetOutput());
407
      }
408 409 410 411 412 413 414

    m_EncoderFilter->SetFunctor(EncoderFunctorType{&m_CountMap, &m_MeanMap, &m_StdMap,
                                                   &m_MinMap, &m_MaxMap, 
                                                   m_InputImage->GetNumberOfComponentsPerPixel(),
                                                   m_IntNoData, m_OutBvValue });
    otbAppLogINFO("Output raster image will have " << 
                  (m_EncoderFilter->GetFunctor()).GetOutputSize() << " bands\n");
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    AddProcess(m_EncoderFilter, "Encode output raster image");
    SetParameterOutputImage("out.raster.filename", m_EncoderFilter->GetOutput());
  }

  void WriteXMLStatsFile()
  {
    // Write statistics in XML file
    const std::string outXMLFile = this->GetParameterString("out.xml.filename");
    otbAppLogINFO("Writing " + outXMLFile)
        StatsWriterType::Pointer statWriter = StatsWriterType::New();
      statWriter->SetFileName(outXMLFile);
      statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",m_CountMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",m_MeanMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",m_StdMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",m_MinMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",m_MaxMap);
      statWriter->Update();
    }

434
    void DoExecute() override
435 436 437 438 439 440 441
    {
      // Get input image
      m_InputImage = GetParameterImage("in");
      // Statistics filter
      m_StatsFilter = StatsFilterType::New();
      m_StatsFilter->SetInput(m_InputImage);
      if (HasUserValue("inbv"))
442
        {
443 444
        m_StatsFilter->SetUseNoDataValue(true);
        m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
445
        }
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
     m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
     AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
     // Select zone definition mode
     m_FromLabelImage = (GetParameterAsString("inzone") == "labelimage");
     if (m_FromLabelImage) PrepareForLabelImageInput();
     else if (GetParameterAsString("inzone") == "vector") PrepareForVectorDataInput();
     else otbAppLogFATAL("Unknown zone definition mode");
     // Remove the no-data entry
     RemoveNoDataEntry();
     // Generate output
     if (GetParameterAsString("out") == "xml") WriteXMLStatsFile();
     else     // vector or raster
        {
        if (m_FromLabelImage) GenerateVectorDataFromLabelImage();
        if (GetParameterAsString("out") == "vector") WriteVectorData(); 
        else if (GetParameterAsString("out") == "raster") WriteRasterData();
        else otbAppLogFATAL("Unknown output mode");
        }
    }
465 466 467 468 469 470

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;
471
  LabelImageToVectorFilterType::Pointer m_LabelImageToVectorFilter;
472 473
  ThresholdFilterType::Pointer m_InputThresholdFilter;
  ThresholdFilterType::Pointer m_OutputThresholdFilter;
474
  FloatVectorImageType::Pointer m_InputImage;
475
  LabelValueType m_IntNoData = itk::NumericTraits<LabelValueType>::max();
476
  LabelValueType m_OutBvValue = itk::NumericTraits<LabelValueType>::max(); 
477
  bool m_FromLabelImage = false;
478 479 480 481 482
  StatsFilterType::LabelPopulationMapType m_CountMap;
  StatsFilterType::PixelValueMapType m_MeanMap;
  StatsFilterType::PixelValueMapType m_StdMap;
  StatsFilterType::PixelValueMapType m_MinMap;
  StatsFilterType::PixelValueMapType m_MaxMap;
483
  EncoderFilterType::Pointer m_EncoderFilter;
484 485 486 487 488 489

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )