otbLSMSSegmentation.cxx 26.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
/*=========================================================================

 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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"
#include "otbExtractROI.h"
#include "otbConnectedComponentMuParserFunctor.h"
#include "itkConnectedComponentFunctorImageFilter.h"
#include "otbBandMathImageFilter.h"
#include "itkStatisticsImageFilter.h"
#include "itkChangeLabelImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkScalarConnectedComponentImageFilter.h"
#include "otbConcatenateVectorImageFilter.h"

#include "otbMultiToMonoChannelExtractROI.h"
32
#include "otbImportGeoInformationImageFilter.h"
33 34 35 36 37 38 39 40 41 42

#include <time.h>
#include <vcl_algorithm.h>

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStandardWriterWatcher.h"
#include <itksys/SystemTools.hxx>

43

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
namespace otb
{
namespace Wrapper
{
class LSMSSegmentation : public Application
{
public:
  typedef LSMSSegmentation Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;
  itkNewMacro(Self);

  itkTypeMacro(MeanShiftSegmentation, otb::Application);

59 60 61
  typedef FloatVectorImageType              ImageType;
  typedef ImageType::InternalPixelType      ImagePixelType;
  typedef UInt32ImageType                   LabelImageType;
62
  typedef LabelImageType::InternalPixelType LabelImagePixelType;
63 64 65
  typedef otb::ImageFileReader<ImageType> ImageReaderType;
  typedef otb::ImageFileWriter<ImageType> ImageWriterType;
  typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType;
OTB Bot's avatar
STYLE  
OTB Bot committed
66
  typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType;
67
  typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType;
OTB Bot's avatar
STYLE  
OTB Bot committed
68
  typedef otb::ExtractROI<LabelImagePixelType,LabelImagePixelType> ExtractROIFilterType;
69 70 71 72 73 74 75
  typedef otb::MultiToMonoChannelExtractROI<ImagePixelType,LabelImagePixelType> MultiToMonoChannelExtractROIFilterType;
  typedef otb::Functor::ConnectedComponentMuParserFunctor<ImageType::PixelType>  CCFunctorType;
  typedef itk::ConnectedComponentFunctorImageFilter<ImageType, LabelImageType, CCFunctorType, otb::Image<unsigned int> > CCFilterType;
  typedef itk::ScalarConnectedComponentImageFilter<LabelImageType, LabelImageType> ScalarCCFilterType;
  typedef otb::BandMathImageFilter<LabelImageType> BandMathImageFilterType;
  typedef itk::StatisticsImageFilter<LabelImageType> StatisticsImageFilterType;
  typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType> ChangeLabelImageFilterType;
76
  typedef otb::ImportGeoInformationImageFilter<LabelImageType,ImageType> ImportGeoInformationImageFilterType;
77
  typedef itk::ImageRegionConstIterator<LabelImageType> LabelImageIterator;
78
    
OTB Bot's avatar
STYLE  
OTB Bot committed
79
  typedef otb::ConcatenateVectorImageFilter <ImageType,ImageType,ImageType> ConcatenateType;
80

81 82 83 84
  LSMSSegmentation(): m_FinalReader(),m_ImportGeoInformationFilter(),m_FilesToRemoveAfterExecute(),m_TmpDirCleanup(false){}
  
  virtual ~LSMSSegmentation(){}

OTB Bot's avatar
STYLE  
OTB Bot committed
85
private:
86 87
  LabelImageReaderType::Pointer m_FinalReader;
  ImportGeoInformationImageFilterType::Pointer m_ImportGeoInformationFilter;
88 89
  std::vector<string> m_FilesToRemoveAfterExecute;
  bool m_TmpDirCleanup;
90 91 92 93 94 95 96 97 98 99 100 101 102

  std::string CreateFileName(unsigned int row, unsigned int column, std::string label)
  {;
    // TODO: Beware of file extensions with more than 3 chars
    std::string outfname = GetParameterString("out");
    std::string tilesname = outfname.substr(0,outfname.size() - itksys::SystemTools::GetFilenameExtension(outfname.c_str()).size());
    
    std::stringstream tileOut;
    tileOut<<tilesname<<"_"<<row<<"_"<<column<<"_"<<label<<".tif";
    
    std::vector<std::string> joins;
    if(IsParameterEnabled("tmpdir"))
      {
103 104 105 106 107 108 109
      std::string tmpdir = GetParameterString("tmpdir");
      
      if(tmpdir.size() > 1 && tmpdir[tmpdir.size()-1] != '/')
        {
        tmpdir.append("/");
        }
      joins.push_back(tmpdir);
110 111 112 113 114 115 116
      }
    joins.push_back(tileOut.str());
    
    std::string currentFile =itksys::SystemTools::JoinPath(joins);

    return currentFile;
  }
117
  
118
  std::string WriteTile(LabelImageType::Pointer img, unsigned int row, unsigned int column, std::string label)
OTB Bot's avatar
STYLE  
OTB Bot committed
119
  {
120 121 122 123 124
    std::string currentFile = CreateFileName(row,column,label);
    
    LabelImageWriterType::Pointer imageWriter = LabelImageWriterType::New();
    imageWriter->SetInput(img);
    imageWriter->SetFileName(currentFile);
OTB Bot's avatar
STYLE  
OTB Bot committed
125
    imageWriter->Update();
126 127 128

    return currentFile;
  }
129

130
  void RemoveFile(std::string tile)
131 132 133 134 135 136
  {
    // Cleanup
    if(IsParameterEnabled("cleanup"))
      {
        // Try to remove the geom file if existing
      std::string geomfile = tile.substr(0,tile.size() - itksys::SystemTools::GetFilenameExtension(tile.c_str()).size()).append(".geom");
137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      if(itksys::SystemTools::FileExists(geomfile.c_str()))
        {
        itksys::SystemTools::RemoveFile(geomfile.c_str());
        }
      if(itksys::SystemTools::FileExists(tile.c_str()))
        {
        itksys::SystemTools::RemoveFile(tile.c_str());
        }
      }
  }

  std::string WriteVRTFile(unsigned int nbTilesX,unsigned int nbTilesY, unsigned long tileSizeX,unsigned long tileSizeY, unsigned long imageSizeX,unsigned long imageSizeY)
  {
    ImageType::Pointer imageIn = GetParameterImage("in");

    std::string outfname = GetParameterString("out");
    std::string vrtfname = outfname.substr(0,outfname.size() - itksys::SystemTools::GetFilenameExtension(outfname.c_str()).size()).append(".vrt");

156
    otbAppLogINFO(<<"Creating temporary vrt file: "<<vrtfname);
157 158 159 160 161 162 163

    std::ofstream ofs(vrtfname.c_str());

    ofs<<"<VRTDataset rasterXSize=\""<<imageSizeX<<"\" rasterYSize=\""<<imageSizeY<<"\">"<<std::endl;
    ofs<<"\t<VRTRasterBand dataType=\"UInt32\" band=\"1\">"<<std::endl;
    ofs<<"\t\t<ColorInterp>Gray</ColorInterp>"<<std::endl;

OTB Bot's avatar
STYLE  
OTB Bot committed
164
     for(unsigned int column = 0; column < nbTilesX; ++column)
165
      {
OTB Bot's avatar
STYLE  
OTB Bot committed
166
      for(unsigned int row = 0; row < nbTilesY; ++row)
167
        {
Julien Michel's avatar
Julien Michel committed
168 169
        std::cout<<"Row: "<<row<<", column: "<<column<<std::endl;

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        ofs<<"\t\t<SimpleSource>"<<std::endl;
        ofs<<"\t\t\t<SourceFilename relativeToVRT=\"1\">"<<CreateFileName(row,column,"FINAL")<<"</SourceFilename>"<<std::endl;
        ofs<<"\t\t\t<SourceBand>1</SourceBand>"<<std::endl;
        ofs<<"\t\t\t<SrcRect xOff=\""<<0<<"\" yOff=\""<<0<<"\" xSize=\""<<tileSizeX<<"\" ySize=\""<<tileSizeY<<"\"/>"<<std::endl;
        ofs<<"\t\t\t<DstRect xOff=\""<<column*tileSizeX<<"\" yOff=\""<<row*tileSizeY<<"\" xSize=\""<<tileSizeX<<"\" ySize=\""<<tileSizeY<<"\"/>"<<std::endl;
        ofs<<"\t\t</SimpleSource>"<<std::endl;
        }
      }
     ofs<<"\t</VRTRasterBand>"<<std::endl;
     ofs<<"</VRTDataset>"<<std::endl;

    ofs.close();

    return vrtfname;
  }
185 186 187 188

  void DoInit()
  {
    SetName("LSMSSegmentation");
189
    SetDescription("Second step of the exact Large-Scale Mean-Shift segmentation workflow.");
190

191 192
    SetDocName("Exact Large-Scale Mean-Shift segmentation, step 2");
    SetDocLongDescription("This application performs the second step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Filtered range image and spatial image should be created with the MeanShiftSmoothing application, with modesearch parameter disabled. If spatial image is not set, the application will only process the range image and spatial radius parameter will not be taken into account. This application will produce a labeled image where neighbor pixels whose range distance is bellow range radius (and optionnaly spatial distance bellow spatial radius) will be grouped together into the same cluster. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results. Please note that this application will generate a lot of temporary files (as many as the number of tiles), and will therefore require twice the size of the final result in term of disk space. The cleanup option (activated by default) allows to remove all temporary file as soon as they are not needed anymore (if cleanup is activated, tmpdir set and tmpdir does not exists before running the application, it will be removed as well during cleanup). The tmpdir option allows to define a directory where to write the temporary files. Please also note that the output image type should be set to uint32 to ensure that there are enough labels available.");
193 194
    SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
    SetDocAuthors("David Youssefi");
195
    SetDocSeeAlso("MeanShiftSmoothing, LSMSSmallRegionsMerging, LSMSVectorization");
196 197 198 199 200 201 202 203 204 205
    AddDocTag(Tags::Segmentation);
    AddDocTag("LSMS");

    AddParameter(ParameterType_InputImage,  "in",    "Filtered image");
    SetParameterDescription( "in", "The filtered image (cf. Adaptive MeanShift Smoothing application)." );
    AddParameter(ParameterType_InputImage,  "inpos",    "Spatial image");
    SetParameterDescription( "inpos", " The spatial image. Spatial input is the displacement map (output of the Adaptive MeanShift Smoothing application)." );
    MandatoryOff("inpos");

    AddParameter(ParameterType_OutputImage, "out", "Output Image");
206
    SetParameterDescription( "out", "The output image. The output image is the segmentation of the filtered image. It is recommanded to set the pixel type to uint32." );
207 208 209 210 211 212 213 214 215 216 217 218 219 220

    AddParameter(ParameterType_Float, "ranger", "Range radius");
    SetParameterDescription("ranger", "Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space.");
    SetDefaultParameterFloat("ranger", 15);
    SetMinimumParameterFloatValue("ranger", 0);
    MandatoryOff("ranger");

    AddParameter(ParameterType_Float, "spatialr", "Spatial radius");
    SetParameterDescription("spatialr", "Spatial radius of the neighborhood.");
    SetDefaultParameterFloat("spatialr", 5);
    SetMinimumParameterFloatValue("spatialr", 0);
    MandatoryOff("spatialr");

    AddParameter(ParameterType_Int, "minsize", "Minimum Region Size");
OTB Bot's avatar
STYLE  
OTB Bot committed
221
    SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is deleted.");
222 223 224 225
    SetDefaultParameterInt("minsize", 0);
    SetMinimumParameterIntValue("minsize", 0);
    MandatoryOff("minsize");
    
226 227 228 229 230 231 232 233 234
    AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
    SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
    SetDefaultParameterInt("tilesizex", 500);
    SetMinimumParameterIntValue("tilesizex", 1);

    AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
    SetDefaultParameterInt("tilesizey", 500);
    SetMinimumParameterIntValue("tilesizey", 1);
235 236 237 238 239 240

    AddParameter(ParameterType_Directory,"tmpdir","Directory where to write temporary files");
    SetParameterDescription("tmpdir","This applications need to write some temporary files for each tile. This parameters allows to choose the path where to write those files. If disabled, the current path will be used.");
    MandatoryOff("tmpdir");
    DisableParameter("tmpdir");

241 242
    AddParameter(ParameterType_Empty,"cleanup","Temporary files cleaning");
    EnableParameter("cleanup");
243 244 245 246 247 248 249 250 251 252
    SetParameterDescription("cleanup","If activated, the application will try to clean all temporary files it created");
    MandatoryOff("cleanup");

    // Doc example parameter settings
    SetDocExampleParameterValue("in","smooth.tif");
    SetDocExampleParameterValue("inpos","position.tif");
    SetDocExampleParameterValue("out","segmentation.tif");
    SetDocExampleParameterValue("ranger","15");
    SetDocExampleParameterValue("spatialr","5");
    SetDocExampleParameterValue("minsize","0");
253 254
    SetDocExampleParameterValue("tilesizex","256");
    SetDocExampleParameterValue("tilesizey","256");
255 256 257 258
    
  }

  void DoUpdateParameters()
OTB Bot's avatar
STYLE  
OTB Bot committed
259
  {
260 261 262 263
  }

  void DoExecute()
  {
264 265
    m_FilesToRemoveAfterExecute.clear();

266 267
    clock_t tic = clock();
  
268 269
    const float ranger         = GetParameterFloat("ranger");
    const float spatialr       = GetParameterFloat("spatialr");
270
    
271
    unsigned int minRegionSize = GetParameterInt("minsize");
272
    
273 274
    unsigned long sizeTilesX   = GetParameterInt("tilesizex");
    unsigned long sizeTilesY   = GetParameterInt("tilesizey");
275 276 277 278 279


    // Ensure that temporary directory exists if activated:
    if(IsParameterEnabled("tmpdir"))
      {
280 281 282 283
      if(!itksys::SystemTools::FileExists(GetParameterString("tmpdir").c_str()))
        {
        m_TmpDirCleanup = true;
        }
284 285 286 287 288 289 290 291 292 293 294
      otbAppLogINFO(<<"Temporary directory "<<GetParameterString("tmpdir")<<" will be used");
      itksys::SystemTools::MakeDirectory(GetParameterString("tmpdir").c_str());
      }

    //Three steps :
    // 1-Tiles segmentation
    // 2-Tiles relabelling
    // 3-Minimal size region suppression

    ImageType::Pointer spatialIn;
        
295
    if(HasValue("inpos"))
296
      {
297
      spatialIn = GetParameterImage("inpos");
298 299 300 301 302
      }

    //Acquisition of the input image dimensions
    ImageType::Pointer imageIn = GetParameterImage("in");
    imageIn->UpdateOutputInformation();
303 304 305 306

    unsigned long sizeImageX = imageIn->GetLargestPossibleRegion().GetSize()[0];
    unsigned long sizeImageY = imageIn->GetLargestPossibleRegion().GetSize()[1];
    unsigned int nbComp      = imageIn->GetNumberOfComponentsPerPixel();
307

308 309 310 311 312
    unsigned int nbTilesX = sizeImageX/sizeTilesX + (sizeImageX%sizeTilesX > 0 ? 1 : 0);
    unsigned int nbTilesY = sizeImageY/sizeTilesY + (sizeImageY%sizeTilesY > 0 ? 1 : 0);

    otbAppLogINFO(<<"Number of tiles: "<<nbTilesX<<" x "<<nbTilesY);

313 314
    unsigned long regionCount = 0;
  
315 316 317
    //Segmentation by the connected component per tile and label
    //shifting
    otbAppLogINFO(<<"Tile shifting ...");
318
      
OTB Bot's avatar
STYLE  
OTB Bot committed
319 320 321
    for(unsigned int row = 0; row < nbTilesY; ++row)
      for(unsigned int column = 0; column < nbTilesX; ++column)
        {
322 323 324 325 326
        // Compute extraction parameters
        unsigned long startX = column*sizeTilesX;
        unsigned long startY = row*sizeTilesY;
        unsigned long sizeX = vcl_min(sizeTilesX+1,sizeImageX-startX+1);
        unsigned long sizeY = vcl_min(sizeTilesY+1,sizeImageY-startY+1);
OTB Bot's avatar
STYLE  
OTB Bot committed
327
           
328 329 330 331 332 333 334 335 336 337
        //Tiles extraction of :
        //- the input image (filtering image)
        MultiChannelExtractROIFilterType::Pointer extractROIFilter = MultiChannelExtractROIFilterType::New();
        extractROIFilter->SetInput(imageIn);
        extractROIFilter->SetStartX(startX);
        extractROIFilter->SetStartY(startY);
        extractROIFilter->SetSizeX(sizeX);
        extractROIFilter->SetSizeY(sizeY);
        extractROIFilter->Update();

338
        //- the spatial image (final positions) if available
339 340
        MultiChannelExtractROIFilterType::Pointer extractROIFilter2 = MultiChannelExtractROIFilterType::New();
        ConcatenateType::Pointer concat = ConcatenateType::New();
341 342 343 344 345 346 347 348 349 350
        CCFilterType::Pointer ccFilter = CCFilterType::New();

        if(HasValue("inpos"))
          {
          extractROIFilter2->SetInput(spatialIn);
          extractROIFilter2->SetStartX(startX);
          extractROIFilter2->SetStartY(startY);
          extractROIFilter2->SetSizeX(sizeX);
          extractROIFilter2->SetSizeY(sizeY);
          extractROIFilter2->Update();
OTB Bot's avatar
STYLE  
OTB Bot committed
351
         
352 353 354 355 356 357 358 359 360
          //Concatenation of the two input images
          concat->SetInput1(extractROIFilter->GetOutput());
          concat->SetInput2(extractROIFilter2->GetOutput());
          concat->Update();
          
          ccFilter->SetInput(concat->GetOutput());
          }
        else
          {
OTB Bot's avatar
STYLE  
OTB Bot committed
361
         ccFilter->SetInput(extractROIFilter->GetOutput());
362 363
          }
        
364 365 366
        //Expression 1 : radiometric distance < ranger
        std::stringstream expr;
        expr<<"sqrt((p1b1-p2b1)*(p1b1-p2b1)";
OTB Bot's avatar
STYLE  
OTB Bot committed
367
        for(unsigned int i=1; i<nbComp; i++)
368
          expr<<"+(p1b"<<i+1<<"-p2b"<<i+1<<")*(p1b"<<i+1<<"-p2b"<<i+1<<")";
369
        expr<<")"<<"<"<<ranger;
370

371 372 373 374
        if(HasValue("inpos"))
          {
          //Expression 2 : final positions < spatialr
          expr<<" and sqrt((p1b"<<nbComp+1<<"-p2b"<<nbComp+1<<")*(p1b"<<nbComp+1<<"-p2b"<<nbComp+1<<")+";
OTB Bot's avatar
STYLE  
OTB Bot committed
375
          expr<<"(p1b"<<nbComp+2<<"-p2b"<<nbComp+2<<")*(p1b"<<nbComp+2<<"-p2b"<<nbComp+2<<"))"<<"<"<<spatialr;
376 377
          }
        
378 379
        //Segmentation
        ccFilter->GetFunctor().SetExpression(expr.str());
OTB Bot's avatar
STYLE  
OTB Bot committed
380
        ccFilter->Update();
381
    
382 383
        std::stringstream ssexpr;
        ssexpr<<"label+"<<regionCount;
OTB Bot's avatar
STYLE  
OTB Bot committed
384
           
385 386 387 388 389 390 391 392
        //Shifting
        BandMathImageFilterType::Pointer labelBandMath = BandMathImageFilterType::New();
        labelBandMath->SetNthInput(0,ccFilter->GetOutput(),"label");
        labelBandMath->SetExpression(ssexpr.str());
        labelBandMath->Update();

        //Maximum label calculation for the shifting
        StatisticsImageFilterType::Pointer stats = StatisticsImageFilterType::New();
OTB Bot's avatar
STYLE  
OTB Bot committed
393
        stats->SetInput(ccFilter->GetOutput());
394 395 396
        stats->Update();
        regionCount+=stats->GetMaximum();

397
        std::string filename = WriteTile(labelBandMath->GetOutput(),row,column,"SEG");
398 399
        }
    
400

401 402
    // Step 2: create the look-up table for all overlaps
    otbAppLogINFO(<<"LUT creation ...");
OTB Bot's avatar
STYLE  
OTB Bot committed
403
    std::vector<LabelImagePixelType> LUT;
404 405 406 407
    LUT.clear();
    LUT.resize(regionCount+1);
    for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel)
      LUT[curLabel] = curLabel;
408
      
OTB Bot's avatar
STYLE  
OTB Bot committed
409
    for(unsigned int row = 0; row < nbTilesY; row++)
410
      {
OTB Bot's avatar
STYLE  
OTB Bot committed
411
      for(unsigned int column = 0; column < nbTilesX; column++)
412 413 414 415 416
        {
        unsigned long startX = column*sizeTilesX;
        unsigned long startY = row*sizeTilesY;
        unsigned long sizeX = vcl_min(sizeTilesX+1,sizeImageX-startX+1);
        unsigned long sizeY = vcl_min(sizeTilesY+1,sizeImageY-startY+1);
417
      
418
        std::string tileIn = CreateFileName(row,column,"SEG");
419

420 421 422 423
        // Read current tile
        LabelImageReaderType::Pointer tileInReader = LabelImageReaderType::New();
        tileInReader->SetFileName(tileIn);
        tileInReader->Update();
424

425 426 427 428
        // Analyse intersection between in and up tiles
        if(row>0)
          {
          std::string tileUp = CreateFileName(row-1,column,"SEG");
OTB Bot's avatar
STYLE  
OTB Bot committed
429 430
         LabelImageReaderType::Pointer tileUpReader = LabelImageReaderType::New();
         tileUpReader->SetFileName(tileUp);
431 432 433 434 435 436 437 438
          tileUpReader->Update();

          LabelImageType::IndexType pixelIndexIn;
          LabelImageType::IndexType pixelIndexUp;

          pixelIndexIn[1] = 0;
          pixelIndexUp[1] = sizeTilesY;

OTB Bot's avatar
STYLE  
OTB Bot committed
439
          for(pixelIndexIn[0]=0; pixelIndexIn[0]<static_cast<long>(sizeX-1); ++pixelIndexIn[0])
440 441 442 443
            {
            pixelIndexUp[0] = pixelIndexIn[0];

            LabelImagePixelType curCanLabel = tileInReader->GetOutput()->GetPixel(pixelIndexIn);
OTB Bot's avatar
STYLE  
OTB Bot committed
444
           while(LUT[curCanLabel] != curCanLabel)
445 446 447
              {
              curCanLabel = LUT[curCanLabel];
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
448
           LabelImagePixelType adjCanLabel = tileUpReader->GetOutput()->GetPixel(pixelIndexUp);
449
            
OTB Bot's avatar
STYLE  
OTB Bot committed
450
           while(LUT[adjCanLabel] != adjCanLabel)
451 452 453
              {
              adjCanLabel = LUT[adjCanLabel];
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
454
           if(curCanLabel < adjCanLabel)
455 456 457
              {
              LUT[adjCanLabel] = curCanLabel;
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
458
           else
459 460 461 462 463
              {
              LUT[LUT[curCanLabel]] = adjCanLabel; LUT[curCanLabel] = adjCanLabel;
              }
            }
          }
464

465 466 467 468
        // Analyse intersection between in and left tiles
         if(column>0)
          {
          std::string tileLeft = CreateFileName(row,column-1,"SEG");
OTB Bot's avatar
STYLE  
OTB Bot committed
469 470
         LabelImageReaderType::Pointer tileLeftReader = LabelImageReaderType::New();
         tileLeftReader->SetFileName(tileLeft);
471 472 473 474 475 476 477 478
          tileLeftReader->Update();

          LabelImageType::IndexType pixelIndexIn;
          LabelImageType::IndexType pixelIndexUp;

          pixelIndexIn[0] = 0;
          pixelIndexUp[0] = sizeTilesX;

OTB Bot's avatar
STYLE  
OTB Bot committed
479
          for(pixelIndexIn[1]=0; pixelIndexIn[1]<static_cast<long>(sizeY-1); ++pixelIndexIn[1])
480 481 482 483
            {
            pixelIndexUp[1] = pixelIndexIn[1];

            LabelImagePixelType curCanLabel = tileInReader->GetOutput()->GetPixel(pixelIndexIn);
OTB Bot's avatar
STYLE  
OTB Bot committed
484
           while(LUT[curCanLabel] != curCanLabel)
485 486 487
              {
              curCanLabel = LUT[curCanLabel];
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
488 489 490
           LabelImagePixelType adjCanLabel = tileLeftReader->GetOutput()->GetPixel(pixelIndexUp);
           while(LUT[adjCanLabel] != adjCanLabel)
              {
491 492
              adjCanLabel = LUT[adjCanLabel];
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
493
           if(curCanLabel < adjCanLabel)
494 495 496
              {
              LUT[adjCanLabel] = curCanLabel;
              }
OTB Bot's avatar
STYLE  
OTB Bot committed
497
           else
498 499 500 501 502
              {
              LUT[LUT[curCanLabel]] = adjCanLabel; LUT[curCanLabel] = adjCanLabel;
              }
            }
          }
503 504
        }
      }
505
    
506
    // Reduce LUT to canonical labels
507
    for(LabelImagePixelType label = 1; label < regionCount+1; ++label)
OTB Bot's avatar
STYLE  
OTB Bot committed
508
      {
509
      LabelImagePixelType can = label;
OTB Bot's avatar
STYLE  
OTB Bot committed
510
      while(LUT[can] != can)
511 512 513
        {
        can = LUT[can];
        }
514 515
      LUT[label] = can;
      }
516
    otbAppLogINFO(<<"LUT size: "<<LUT.size()<<" segments");
517
 
518 519 520
    // These variables will be used to estimate the size of each
    // region on the flow
    std::vector<unsigned long> sizePerRegion(regionCount+1,0);
521

522
    otbAppLogINFO(<<"Tiles relabelisation ...");
OTB Bot's avatar
STYLE  
OTB Bot committed
523
    for(unsigned int column = 0; column < nbTilesX; ++column)
524
      {
OTB Bot's avatar
STYLE  
OTB Bot committed
525
      for(unsigned int row = 0; row < nbTilesY; ++row)
526
        {
OTB Bot's avatar
STYLE  
OTB Bot committed
527
       unsigned long startX = column*sizeTilesX;
528
        unsigned long startY = row*sizeTilesY;
OTB Bot's avatar
STYLE  
OTB Bot committed
529
       unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX);
530 531 532 533 534 535 536 537 538
        unsigned long sizeY = vcl_min(sizeTilesY,sizeImageY-startY);

        std::string tileIn = CreateFileName(row,column,"SEG");

        LabelImageReaderType::Pointer readerIn = LabelImageReaderType::New();
        readerIn->SetFileName(tileIn);

        // Remove extra margin now that lut is built
        ExtractROIFilterType::Pointer labelImage = ExtractROIFilterType::New();
OTB Bot's avatar
STYLE  
OTB Bot committed
539 540 541 542 543
       labelImage->SetInput(readerIn->GetOutput());
       labelImage->SetStartX(0);
       labelImage->SetStartY(0);
       labelImage->SetSizeX(sizeX);
       labelImage->SetSizeY(sizeY);
544 545 546
        
        // Relabel tile according to look-up table
        ChangeLabelImageFilterType::Pointer changeLabel = ChangeLabelImageFilterType::New();
OTB Bot's avatar
STYLE  
OTB Bot committed
547 548
       changeLabel->SetInput(labelImage->GetOutput());
       
549
        // Fill LUT
OTB Bot's avatar
STYLE  
OTB Bot committed
550
        for(LabelImagePixelType label = 1; label<regionCount+1; ++label)
551
          {
OTB Bot's avatar
STYLE  
OTB Bot committed
552
         if(label!=LUT[label])
553 554 555 556 557 558 559 560 561 562 563
            {
            changeLabel->SetChange(label,LUT[label]);
            }
          }

        // Here we need to update the filter to be able to update
        // region sizes table
        changeLabel->Update();

        // Update region sizes
        LabelImageIterator it( changeLabel->GetOutput(), changeLabel->GetOutput()->GetLargestPossibleRegion());
OTB Bot's avatar
STYLE  
OTB Bot committed
564
       for (it = it.Begin(); !it.IsAtEnd(); ++it)
565
          {
566
          sizePerRegion[it.Value()]+=1;
567
          }
568 569 570 571 572

        // Write tile
        WriteTile(changeLabel->GetOutput(),row,column,"RELAB");

        // Remove previous tile (not needed anymore)
573
        RemoveFile(tileIn);
574
        }
575
      }
576

577 578
    // Clear lut, we do not need it anymore
    LUT.clear();
579

580 581
    unsigned int smallCount = 0;

582 583 584 585 586
      // Create the LUT to filter small regions and assign min labels
      otbAppLogINFO(<<"Small regions pruning ...");
      LabelImagePixelType newLab=1;
      std::vector<LabelImagePixelType> newLabels(regionCount+1,0);
      for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel)
587
        {
OTB Bot's avatar
STYLE  
OTB Bot committed
588
        if(sizePerRegion[curLabel]<minRegionSize)
589
          {
590
          newLabels[curLabel]=0;
591
          ++smallCount;
592
          }
593
        else
594
          {
595 596
          newLabels[curLabel]=newLab;
          newLab+=1;
597 598 599
          }
        }

600
      otbAppLogINFO(<<smallCount<<" small regions will be removed");
601

602 603 604
      // Clear sizePerRegion, we do not need it anymore
      sizePerRegion.clear();
     
OTB Bot's avatar
STYLE  
OTB Bot committed
605
      for(unsigned int column = 0; column < nbTilesX; ++column)
606
        {
OTB Bot's avatar
STYLE  
OTB Bot committed
607
        for(unsigned int row = 0; row < nbTilesY; ++row)
608 609 610 611 612 613 614 615
          {
          std::string tileIn = CreateFileName(row,column,"RELAB");

          LabelImageReaderType::Pointer readerIn = LabelImageReaderType::New();
          readerIn->SetFileName(tileIn);

          ChangeLabelImageFilterType::Pointer changeLabel = ChangeLabelImageFilterType::New();
          changeLabel->SetInput(readerIn->GetOutput());
OTB Bot's avatar
STYLE  
OTB Bot committed
616
          for(LabelImagePixelType label = 1; label<regionCount+1; ++label)
617 618 619 620 621 622 623 624
            {
            if(label != newLabels[label])
              {
              changeLabel->SetChange(label,newLabels[label]);
              }
            }
          
          // Write the relabeled tile
625
          std::string tmpfile = WriteTile(changeLabel->GetOutput(),row,column,"FINAL");
626 627
          m_FilesToRemoveAfterExecute.push_back(tmpfile);

628
          // Clean previous tiles (not needed anymore)
629
          RemoveFile(tileIn);
630
          }
631
        }
632 633 634

      // Clear newLabels, we do not need it anymore
      newLabels.clear();
635
  
636 637
      // Here we write a temporary vrt file that will be used to
      // stitch together all the tiles
Julien Michel's avatar
Julien Michel committed
638
      std::string vrtfile = WriteVRTFile(nbTilesX,nbTilesY,sizeTilesX,sizeTilesY,sizeImageX,sizeImageY);
639

640 641
      m_FilesToRemoveAfterExecute.push_back(vrtfile);

642 643 644
      clock_t toc = clock();
      
      otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
645

646 647 648
      // Final writing
      m_FinalReader = LabelImageReaderType::New();
      m_FinalReader->SetFileName(vrtfile);
649

650 651 652
      m_ImportGeoInformationFilter = ImportGeoInformationImageFilterType::New();
      m_ImportGeoInformationFilter->SetInput(m_FinalReader->GetOutput());
      m_ImportGeoInformationFilter->SetSource(imageIn);
653

654
      SetParameterOutputImage("out",m_ImportGeoInformationFilter->GetOutput());
655
  }
656 657 658 659 660 661 662 663

  void AfterExecuteAndWriteOutputs()
  {
    if(IsParameterEnabled("cleanup"))
      {
      otbAppLogINFO(<<"Final clean-up ...");

      for(std::vector<std::string>::iterator it = m_FilesToRemoveAfterExecute.begin();
OTB Bot's avatar
STYLE  
OTB Bot committed
664
          it!=m_FilesToRemoveAfterExecute.end(); ++it)
665 666 667 668 669 670 671 672 673 674 675 676
        {
        RemoveFile(*it);
        }

      if(IsParameterEnabled("tmpdir") && m_TmpDirCleanup)
        {
        otbAppLogINFO(<<"Removing tmp directory "<<GetParameterString("tmpdir")<<", since it has been created by the application");
        itksys::SystemTools::RemoveADirectory(GetParameterString("tmpdir").c_str());
        }
      }

    m_FilesToRemoveAfterExecute.clear();
677
    m_TmpDirCleanup = false;
678
  }
679 680 681 682 683 684 685
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSSegmentation)