otbLSGRM.cxx 10.3 KB
Newer Older
remicres's avatar
remicres committed
1
2
3
4
5
6
7
8
9
10
11
12
#include "itkFixedArray.h"
#include "itkObjectFactory.h"

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

// Application engine
#include "otbStandardFilterWatcher.h"
#include "itkFixedArray.h"
#include "itkImageSource.h"

remicres's avatar
remicres committed
13
// LSGRM
14
#include <iostream>
15
16
17
#include "lsgrmBaatzSegmenter.h"
#include "lsgrmSpringSegmenter.h"
#include "lsgrmFullLambdaScheduleSegmenter.h"
18
19
#include "lsgrmController.h"

20
21
22
23
// Graph to label image (streaming version)
#include "otbStreamingGraphToImageFilter.h"
#include "otbStreamingImageVirtualWriter.h"

24
25
26
// system tools
#include <itksys/SystemTools.hxx>

remicres's avatar
remicres committed
27
28
29
30
31
32
33
namespace otb
{

namespace Wrapper
{

class LSGRM : public Application
34
{
remicres's avatar
remicres committed
35
36
public:
  /** Standard class typedefs. */
37
  typedef LSGRM                         Self;
remicres's avatar
remicres committed
38
39
40
41
42
43
44
45
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

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

46
47
48
49
50
51
  /** Useful typedefs */
  typedef otb::VectorImage<float, 2>                    ImageType;
  typedef lsgrm::BaatzSegmenter<ImageType>              BaatzSegmenterType;
  typedef lsgrm::SpringSegmenter<ImageType>             SpringSegmenterType;
  typedef lsgrm::FullLambdaScheduleSegmenter<ImageType> FLSSegmenterType;

remicres's avatar
remicres committed
52
53
private:

54
55
56
57
58
59
60
61
  /* Tiling mode choice */
  enum TilingMode
  {
    TILING_AUTO,
    TILING_USER,
    TILING_NONE
  };

62
63
64
65
66
67
68
69
  /* Criterion choice */
  enum Criterion
  {
    CRITERION_BAATZ,
    CRITERION_SPRING,
    CRITERION_FLS
  };

remicres's avatar
remicres committed
70
71
  void DoInit()
  {
72

73
    SetName("GenericRegionMerging");
remicres's avatar
remicres committed
74
75
    SetDescription("This application allows to use the Large Scale Generic Region Merging library "
        "(LSGRM) and provides currently 3 homogeneity criteria: Euclidean Distance, "
76
77
        "Full Lambda Schedule and Baatz & Schape criterion.");

78
    // Input and Output images
79
80
81
82
    AddParameter(ParameterType_InputImage, "in", "Input Image");
    AddParameter(ParameterType_OutputImage, "out", "Ouput Label Image");
    SetDefaultOutputPixelType("out", ImagePixelType_uint32);

83
84
85
86
87
    // Criterion choice
    AddParameter(ParameterType_Choice, "criterion", "Homogeneity criterion to use");
    AddChoice("criterion.bs", "Baatz & Schape");
    AddChoice("criterion.ed", "Euclidean Distance");
    AddChoice("criterion.fls", "Full Lambda Schedule");
88

89
    // Generic parameters
90
91
92
93
94
    AddParameter(ParameterType_Float, "threshold", "Threshold for the criterion");
    AddParameter(ParameterType_Int, "niter", "Maximum number of iterations");
    SetDefaultParameterInt("niter", 75);
    MandatoryOff("niter");

95
96
97
98
99
100
101
    // Specific parameters for Baatz & Schape
    AddParameter(ParameterType_Float, "criterion.bs.cw", "Weight for the spectral homogeneity");
    SetDefaultParameterFloat("criterion.bs.cw", 0.5);
    MandatoryOff("criterion.bs.cw");
    AddParameter(ParameterType_Float, "criterion.bs.sw", "Weight for the spatial homogeneity");
    SetDefaultParameterFloat("criterion.bs.sw", 0.5);
    MandatoryOff("criterion.bs.sw");
102
103

    // For large scale
104
    AddParameter(ParameterType_Directory, "tmpdir", "Directory for temporary files");
105
    MandatoryOff("tmpdir");
106
107
108
109
110
111
112
    AddParameter(ParameterType_Choice, "tiling", "Tiling layout for the large scale segmentation");
    AddChoice("tiling.auto", "Automatic tiling layout");
    AddChoice("tiling.user", "User tiling layout");
    AddParameter(ParameterType_Int, "tiling.user.sizex", "Tiles width");
    AddParameter(ParameterType_Int, "tiling.user.sizey", "Tiles height");
    AddParameter(ParameterType_Int, "tiling.user.nfirstiter", "Number of first iterations");
    AddChoice("tiling.none", "No tiling layout");
113
114
115

    AddParameter(ParameterType_Int, "memory", "Restrict memory use (mb)");
    MandatoryOff("memory");
116
117
118
119
120
121
122
123
124
125
	
	AddParameter(ParameterType_Bool, "resume", "Activate resume mode");
	SetDefaultParameterBool("resume", false);
	AddParameter(ParameterType_Int, "resume.tilerow", "Starting tile row in resume mode");
	AddParameter(ParameterType_Int, "resume.tilecol", "Starting tile column in resume mode");
	SetDefaultParameterInt("resume.tilerow", 0);
	SetDefaultParameterInt("resume.tilecol", 0);
	//MandatoryOff("resume");
	//MandatoryOff("resume.tilex");
	//MandatoryOff("resume.tiley");
remicres's avatar
remicres committed
126
127
128
129
130
131
  }

  void DoUpdateParameters()
  {
  }

132
133
134
135
136
137
138
139
140
141
142
  /*
   * Return a prefix for temporary files
   */
  std::string GetTemporaryFilesPrefix()
  {

    // Get output filename (without extension)
    std::string outfname = GetParameterString("out");
    std::string outbfname = itksys::SystemTools::GetFilenameWithoutExtension(outfname.c_str());

    // Get specified temporary directory
143
144
145
    std::string tmpdir;
    if (HasValue("tmpdir"))
      {
146
        tmpdir= GetParameterAsString("tmpdir");
147
148
149
      }
    else
      {
150
        tmpdir = itksys::SystemTools::GetFilenamePath(outfname);
151
152
      }

153
154
    if (!tmpdir.empty())
      {
155
156
157
158
159
160
161
162
163
164
165
166
167
        // A temporary directory is specified: we check that it ends with a POSIX separator
        if (tmpdir[tmpdir.size()-1] != '/')
          {
            // If not, we add the separator
            tmpdir.append("/");
          }

        // Check that the directory exists
        if (!itksys::SystemTools::FileExists(tmpdir.c_str(),false))
          {
            otbAppLogFATAL("The directory " << tmpdir << " does not exist.");
          }
        otbAppLogINFO("Using temporary directory " << tmpdir);
remicres's avatar
remicres committed
168
      }
169

remicres's avatar
remicres committed
170
171

    // Return the prefix
172
173
174
175
    std::string prefix = tmpdir + outbfname;
    return prefix;
  }

176
177
178
  /*
   * This function sets the generic parameters of a controller and runs the segmentation
   */
remicres's avatar
remicres committed
179
  template<class TSegmenter>
180
181
  void
  SetGenericParametersAndRunSegmentation(const typename TSegmenter::ParamType params){
remicres's avatar
remicres committed
182
183
184
185

    // Instantiate the controller
    typedef typename lsgrm::Controller<TSegmenter> ControlerType;
    typename ControlerType::Pointer controller = ControlerType::New();
186
    using GraphType = typename ControlerType::GraphType;
remicres's avatar
remicres committed
187
188
189
190

    // Set specific parameters
    controller->SetSpecificParameters(params);

191
    // Set input image
192
193
    ImageType::Pointer inputImage = GetParameterFloatVectorImage("in");
    controller->SetInputImage(inputImage);
remicres's avatar
remicres committed
194

195
196
197
    // Set threshold
    float thres = GetParameterFloat("threshold");
    controller->SetThreshold(thres*thres);
remicres's avatar
remicres committed
198

199
200
    // Set number of iterations
    controller->SetNumberOfIterations(GetParameterInt("niter"));
remicres's avatar
remicres committed
201

202
203
    // Set temporary files prefix
    controller->SetTemporaryFilesPrefix(this->GetTemporaryFilesPrefix());
remicres's avatar
remicres committed
204

205
    // Switch tiling mode
206
207
    int inputTilingMode = GetParameterInt("tiling");
    if (inputTilingMode == TILING_AUTO)
remicres's avatar
remicres committed
208
      {
209
210
        // Automatic mode
        controller->SetTilingModeAuto();
remicres's avatar
remicres committed
211
      }
212
    else if (inputTilingMode == TILING_USER)
remicres's avatar
remicres committed
213
      {
214
215
216
217
218
        // User mode
        controller->SetTilingModeUser();
        controller->SetTileWidth(GetParameterInt("tiling.user.sizex"));
        controller->SetTileHeight(GetParameterInt("tiling.user.sizey"));
        controller->SetNumberOfFirstIterations(GetParameterInt("tiling.user.nfirstiter"));
remicres's avatar
remicres committed
219
      }
220
221
    else if (inputTilingMode == TILING_NONE)
      {
222
223
        // None mode
        controller->SetTilingModeNone();
224
225
226
      }
    else
      {
227
        otbAppLogFATAL("Unknown tiling mode!");
228
229
230
231
232
      }

    // Input RAM value?
    if (HasValue("memory"))
      {
233
234
        otbAppLogINFO("Setting maximum memory to " << GetParameterInt("memory") << " MBytes");
        controller->SetInternalMemoryAvailable(GetParameterInt("memory"));
235
      }
236
237
238
239
240
241
	  
	 // Resume mode?
	 if (GetParameterBool("resume"))
	  {
		controller.SetResumingMode(GetParameterInt("resume.tilerow"),GetParameterInt("resume.tilecol"));
	  }
remicres's avatar
remicres committed
242

remicres's avatar
remicres committed
243
    // Run the segmentation
244
    controller->RunSegmentation();
remicres's avatar
remicres committed
245

246
247
248
249
250
251
    // Prepare the label image source
    typedef lsgrm::StreamingGraphToImageFilter<GraphType, UInt32ImageType> LabelImageSourceType;
    typename LabelImageSourceType::Pointer labelImageSource = LabelImageSourceType::New();
    labelImageSource->SetGraph(controller->GetOutputGraph());
    labelImageSource->SetOutputSize(inputImage->GetLargestPossibleRegion().GetSize());
    labelImageSource->SetOutputOrigin(inputImage->GetOrigin());
252
    labelImageSource->SetOutputSpacing(inputImage->GetSignedSpacing());
253
254
255
256
257
258
259
260
261
262
263
    labelImageSource->SetOutputProjectionRef(inputImage->GetProjectionRef());
    labelImageSource->GenerateOutputInformation();

    m_LabelImageSource = static_cast<itk::ImageSource<UInt32ImageType>*>(labelImageSource);

    SetParameterOutputImage<UInt32ImageType>("out", m_LabelImageSource->GetOutput());

    // TODO: find an intelligent value of RAM
    if (dynamic_cast<OutputImageParameter*>(GetParameterByKey("out")))
      {
      OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(GetParameterByKey("out"));
264
      paramDown->SetRAMValue(1024);
265
266
      }

267
268
269
270
271
272
273
274
275
276
277
278
279
280
    // Get temporary files list
    m_TemporaryFilesList = controller->GetTemporaryFilesList();

  }

  void DoExecute()
  {

    ImageType::Pointer inputImage = GetParameterFloatVectorImage("in");

    // Switch criterion
    int inputCriterion = GetParameterInt("criterion");
    if (inputCriterion == CRITERION_BAATZ)
      {
281
282
283
284
        grm::BaatzParam params;
        params.m_SpectralWeight = GetParameterFloat("criterion.bs.cw");
        params.m_ShapeWeight = GetParameterFloat("criterion.bs.sw");
        SetGenericParametersAndRunSegmentation<BaatzSegmenterType>(params);
285
286
287
      }
    else if (inputCriterion == CRITERION_SPRING)
      {
288
289
        grm::SpringParam params;
        SetGenericParametersAndRunSegmentation<SpringSegmenterType>(params);
290
291
292
      }
    else if (inputCriterion == CRITERION_FLS)
      {
293
294
        grm::FLSParam params;
        SetGenericParametersAndRunSegmentation<FLSSegmenterType>(params);
295
296
297
      }
    else
      {
298
        otbAppLogFATAL("Unknow criterion!")
299
      }
remicres's avatar
remicres committed
300

remicres's avatar
remicres committed
301
302
303
304
  }

  void AfterExecuteAndWriteOutputs()
  {
remicres's avatar
remicres committed
305
306
307
308
309
310
311

#ifdef OTB_USE_MPI
    // When MPI is activated, only the master thread proceed
    if (otb::MPIConfig::Instance()->GetMyRank() != 0)
      return;
#endif

312
313
314
    // Delete temporary files
    for (unsigned int i = 0 ; i < m_TemporaryFilesList.size() ; i++)
      {
315
316
317
318
        if( remove(m_TemporaryFilesList.at(i).c_str() ) != 0  )
          {
            otbAppLogWARNING( "Error deleting file " << m_TemporaryFilesList.at(i) );
          }
319
      }
remicres's avatar
remicres committed
320
321
  }

322
323
private:
  std::vector<std::string> m_TemporaryFilesList;
324
  itk::ImageSource<UInt32ImageType>::Pointer m_LabelImageSource;
325

remicres's avatar
remicres committed
326
327
328
329
330
}; // app class
} // end of namespace wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::LSGRM)