otbLSGRM.cxx 10.37 KiB
#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"
// LSGRM
#include <iostream>
#include "lsgrmBaatzSegmenter.h"
#include "lsgrmSpringSegmenter.h"
#include "lsgrmFullLambdaScheduleSegmenter.h"
#include "lsgrmController.h"
// Vectorization
#include "otbLabelImageToVectorDataFilter.h"
// system tools
#include <itksys/SystemTools.hxx>
namespace otb
namespace Wrapper
class LSGRM : public Application
public:
  /** Standard class typedefs. */
  typedef LSGRM                         Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;
  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(LSGRM, Application);
  /** Useful typedefs */
  typedef otb::VectorImage<float, 2>                    ImageType;
  typedef lsgrm::BaatzSegmenter<ImageType>              BaatzSegmenterType;
  typedef lsgrm::SpringSegmenter<ImageType>             SpringSegmenterType;
  typedef lsgrm::FullLambdaScheduleSegmenter<ImageType> FLSSegmenterType;
  /** Vectorization typedefs */
  typedef otb::LabelImageToVectorDataFilter<UInt32ImageType> VectorizeLabelFilterType;
private:
  /* Tiling mode choice */
  enum TilingMode
    TILING_AUTO,
    TILING_USER,
    TILING_NONE
  /* Criterion choice */
  enum Criterion
    CRITERION_BAATZ,
    CRITERION_SPRING,
    CRITERION_FLS
7172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
/* Output mode */ enum OutMode { OUTPUT_MODE_VECTOR, OUTPUT_MODE_RASTER }; void DoInit() { SetName("GenericRegionMerging"); SetDescription("This application allows to use the Large Scale Generic Region Merging library " "(LSGRM) and provides currently 3 homogeneity criteria: Euclidean Distance, " "Full Lambda Schedule and Baatz & Schape criterion."); // Input image AddParameter(ParameterType_InputImage, "in", "Input Image"); // Outputs AddParameter(ParameterType_Choice, "mode", "output mode"); AddChoice("mode.vector", "Output is a vector layer"); AddChoice("mode.raster", "Output is a label image"); AddParameter(ParameterType_OutputImage, "mode.raster.out", "Ouput Label Image"); SetDefaultOutputPixelType("mode.raster.out", ImagePixelType_uint32); AddParameter(ParameterType_OutputVectorData, "mode.vector.out", "Output vector layer"); // 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"); // Generic parameters AddParameter(ParameterType_Float, "threshold", "Threshold for the criterion"); AddParameter(ParameterType_Int, "niter", "Maximum number of iterations"); SetDefaultParameterInt("niter", 75); MandatoryOff("niter"); // 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"); // For large scale AddParameter(ParameterType_Directory, "tmpdir", "Directory for temporary files"); MandatoryOff("tmpdir"); 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"); AddParameter(ParameterType_Int, "memory", "Restrict memory use (mb)"); MandatoryOff("memory"); } void DoUpdateParameters() { } /* * Return a prefix for temporary files */ std::string GetTemporaryFilesPrefix() {
141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
// Get output filename (without extension) std::string outfname; if (GetParameterInt("mode") == OUTPUT_MODE_RASTER) { outfname = GetParameterAsString("mode.raster.out"); } else if (GetParameterInt("mode") == OUTPUT_MODE_VECTOR) { outfname = GetParameterAsString("mode.vector.out"); } else { otbAppLogFATAL("Unknown output mode"); } std::string outbfname = itksys::SystemTools::GetFilenameWithoutExtension(outfname.c_str()); // Get specified temporary directory std::string tmpdir; if (HasValue("tmpdir")) { tmpdir= GetParameterAsString("tmpdir"); } else { tmpdir = itksys::SystemTools::GetFilenamePath(outfname); if (tmpdir.empty()) { tmpdir = itksys::SystemTools::GetCurrentWorkingDirectory(true); } } if (!tmpdir.empty()) { // 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); } // Return the prefix std::string prefix = tmpdir + outbfname; return prefix; } /* * This function sets the generic parameters of a controller and runs the segmentation */ template<class TSegmenter> UInt32ImageType::Pointer SetGenericParametersAndRunSegmentation(const typename TSegmenter::ParamType params){ // Instantiate the controller typedef typename lsgrm::Controller<TSegmenter> ControlerType; typename ControlerType::Pointer controller = ControlerType::New(); // Set specific parameters controller->SetSpecificParameters(params); // Set input image controller->SetInputImage(GetParameterFloatVectorImage("in"));
211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
// Set threshold float thres = GetParameterFloat("threshold"); controller->SetThreshold(thres*thres); // Set number of iterations controller->SetNumberOfIterations(GetParameterInt("niter")); // Set temporary files prefix controller->SetTemporaryFilesPrefix(this->GetTemporaryFilesPrefix()); // Switch tiling mode int inputTilingMode = GetParameterInt("tiling"); if (inputTilingMode == TILING_AUTO) { // Automatic mode controller->SetTilingModeAuto(); } else if (inputTilingMode == TILING_USER) { // User mode controller->SetTilingModeUser(); controller->SetTileWidth(GetParameterInt("tiling.user.sizex")); controller->SetTileHeight(GetParameterInt("tiling.user.sizey")); controller->SetNumberOfFirstIterations(GetParameterInt("tiling.user.nfirstiter")); } else if (inputTilingMode == TILING_NONE) { // None mode controller->SetTilingModeNone(); } else { otbAppLogFATAL("Unknown tiling mode!"); } // Input RAM value? if (HasValue("memory")) { otbAppLogINFO("Setting maximum memory to " << GetParameterInt("memory") << " MBytes"); controller->SetInternalMemoryAvailable(GetParameterInt("memory")); } // Run the segmentation controller->RunSegmentation(); // Get temporary files list m_TemporaryFilesList = controller->GetTemporaryFilesList(); // Return the label image return controller->GetLabeledClusteredOutput(); } void DoExecute() { /* TODO: the output directory in case the global graph cannot fit in memory (lsgrmController.txx) */ // Input image ImageType::Pointer inputImage = GetParameterFloatVectorImage("in"); // Output image UInt32ImageType::Pointer labelImage = UInt32ImageType::New(); // Switch criterion int inputCriterion = GetParameterInt("criterion"); if (inputCriterion == CRITERION_BAATZ) { grm::BaatzParam params;
281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
params.m_SpectralWeight = GetParameterFloat("criterion.bs.cw"); params.m_ShapeWeight = GetParameterFloat("criterion.bs.sw"); labelImage = SetGenericParametersAndRunSegmentation<BaatzSegmenterType>(params); } else if (inputCriterion == CRITERION_SPRING) { grm::SpringParam params; labelImage = SetGenericParametersAndRunSegmentation<SpringSegmenterType>(params); } else if (inputCriterion == CRITERION_FLS) { grm::FLSParam params; labelImage = SetGenericParametersAndRunSegmentation<FLSSegmenterType>(params); } else { otbAppLogFATAL("Unknow criterion!") } // Set output image projection, origin and spacing for labelImage labelImage->SetProjectionRef(inputImage->GetProjectionRef()); labelImage->SetOrigin(inputImage->GetOrigin()); labelImage->SetSpacing(inputImage->GetSpacing()); if (GetParameterInt("mode") == OUTPUT_MODE_RASTER) { SetParameterOutputImage<UInt32ImageType>("mode.raster.out", labelImage); } else if (GetParameterInt("mode") == OUTPUT_MODE_VECTOR) { VectorizeLabelFilterType::Pointer vectorizeFilter = VectorizeLabelFilterType::New(); vectorizeFilter->SetInput(labelImage); vectorizeFilter->SetInputMask(labelImage); vectorizeFilter->Update(); SetParameterOutputVectorData("mode.vector.out", vectorizeFilter->GetOutput()); } } void AfterExecuteAndWriteOutputs() { #ifdef OTB_USE_MPI // When MPI is activated, only the master thread proceed if (otb::MPIConfig::Instance()->GetMyRank() != 0) return; #endif // Delete temporary files for (unsigned int i = 0 ; i < m_TemporaryFilesList.size() ; i++) { if( remove(m_TemporaryFilesList.at(i).c_str() ) != 0 ) { otbAppLogWARNING( "Error deleting file " << m_TemporaryFilesList.at(i) ); } } } private: std::vector<std::string> m_TemporaryFilesList; }; // app class } // end of namespace wrapper } // end of namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::LSGRM)