otbZonalStatistics.cxx 12.7 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/*
 * 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"

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 */
54
  typedef Int32ImageType                LabelImageType;
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
      FloatVectorImageType>             VectorDataReprojFilterType;
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
      LabelImageType>                   RasterizeFilterType;
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
                                        TreeIteratorType;
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
                                        PolygonListPointerType;
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
      LabelImageType>                   StatsFilterType;
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
                                        StatsWriterType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

  void DoInit()
  {

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

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
        "The application inputs one input multiband image, and a label input. "
        "If the label input is a raster, the output statistics are exported in a XML file. If the label "
        "input is a vector data, the output statistics are exported in a new vector data with statistics "
        "in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
    SetDocLimitations("The shapefile must fit in memory");
    SetDocAuthors("Remi Cresson");

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

    // Input image
    AddParameter(ParameterType_InputImage, "in",  "Input Image");

98 99 100 101
    // 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");
102 103

    // Input for vector mode
104 105 106
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

107 108

    // Input for label image mode
109 110 111 112 113 114 115 116 117 118 119 120 121 122
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    SetDefaultParameterInt                ("inzone.labelimage.nodata", 0);
    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");
    AddParameter(ParameterType_String, "out.xml.filename", "");
    AddChoice("out.raster", "Output raster image");
    AddParameter(ParameterType_OutputImage, "out.raster.filename", "");
123 124 125 126 127

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
128 129
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


  }

  void DoUpdateParameters()
  {
    // 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();
    FloatVectorImageType::PixelType pix;
    pix.SetSize(nBands);
    pix.Fill(0);
    return pix;
  }

  void DoExecute()
  {

    // Get input image
    FloatVectorImageType::Pointer img = GetParameterImage("in");

    // Statistics filter
    m_StatsFilter = StatsFilterType::New();
    m_StatsFilter->SetInput(img);
    m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
    AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");

169 170
    // Select zone definition mode
    if (GetParameterAsString("inzone") == "labelimage")
171
      {
172 173 174 175 176 177 178 179 180
      otbAppLogINFO("Zone definition: label image");

      // Computing stats
      m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
      m_StatsFilter->Update();
      }
    else if (GetParameterAsString("inzone") == "vector")
      {
      otbAppLogINFO("Zone definition: vector");
181 182

      otbAppLogINFO("Loading vector data...");
183
      VectorDataType* shp = GetParameterVectorData("inzone.vector.in");
184 185

      // Reproject vector data
186
      if (GetParameterInt("inzone.vector.reproject") != 0)
187 188 189 190 191 192 193 194 195 196 197 198 199 200
        {
        otbAppLogINFO("Vector data reprojection enabled");
        m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
        m_VectorDataReprojectionFilter->SetInputVectorData(shp);
        m_VectorDataReprojectionFilter->SetInputImage(img);
        AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
        m_VectorDataReprojectionFilter->Update();
        m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
        }
      else
        {
        m_VectorDataSrc = shp;
        }

201 202 203
      // Internal no-data value
      const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();

204 205 206 207 208 209 210 211
      // Rasterize vector data
      m_RasterizeFilter = RasterizeFilterType::New();
      m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
      m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
      m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
      m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
      m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
      m_RasterizeFilter->SetBurnAttribute("________");
212
      m_RasterizeFilter->SetDefaultBurnValue(0);
213 214 215 216 217 218
      m_RasterizeFilter->SetGlobalWarningDisplay(false);
      m_RasterizeFilter->SetBackgroundValue(intNoData);

      // Computing stats
      m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
      m_StatsFilter->Update();
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      }
    else
      {
      otbAppLogFATAL("Unknown zone definition mode");
      }

    // Remove the no-data entry
    StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
    StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
    StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
    StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
    StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      // Internal no-data value
      const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();
      if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata")))
        GetParameterInt("inzone.labelimage.nodata");

      otbAppLogINFO("Using no-data value: " << intNoData);
240 241 242 243 244 245

      countMap.erase(intNoData);
      meanMap.erase(intNoData);
      stdMap.erase(intNoData);
      minMap.erase(intNoData);
      maxMap.erase(intNoData);
246 247
      }

248

249 250 251 252 253 254
    if (GetParameterAsString("out") == "vector")
      {
      if (GetParameterAsString("inzone") == "vector")
        {
        // Add a statistics fields
        otbAppLogINFO("Writing output vector data");
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
      LabelValueType internalFID = 0;
      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();

          // Add the geometry with the new fields
          if (countMap.count(internalFID) > 0)
            {
            currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
            for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
              {
              currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), meanMap[internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), minMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), maxMap [internalFID][band] );
              }
            m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
            }

          internalFID++;
          }
        ++itVector;
        } // next feature

294 295 296
      SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
        }
      else if (GetParameterAsString("inzone") == "labelimage")
297
        {
298 299
          //vectorize the image
        otbAppLogFATAL("Vector output from labelimage input not implemented yet");
300
        }
301 302 303
      }
    else if (GetParameterAsString("out") == "xml")
      {
304
      // Write stats
305
      const std::string outXMLFile = this->GetParameterString("out.xml.filename");
306 307 308 309 310 311 312 313 314 315 316 317 318
      otbAppLogINFO("Writing " + outXMLFile)
      StatsWriterType::Pointer statWriter = StatsWriterType::New();
      statWriter->SetFileName(outXMLFile);
      statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
      statWriter->Update();

      }
    else
      {
319
      otbAppLogFATAL("Unknown output mode");
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
      }

  }

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )