otbLSMSSegmentation.cxx 26.5 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 66 67
  typedef otb::ImageFileReader<ImageType> ImageReaderType;
  typedef otb::ImageFileWriter<ImageType> ImageWriterType;
  typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType;
  typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType;  
  typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType;
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
    
79 80
  typedef otb::ConcatenateVectorImageFilter <ImageType,ImageType,ImageType> ConcatenateType;  

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

85 86 87
private:      
  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 119 120 121 122 123 124 125 126 127 128
  std::string WriteTile(LabelImageType::Pointer img, unsigned int row, unsigned int column, std::string label)
  { 
    std::string currentFile = CreateFileName(row,column,label);
    
    LabelImageWriterType::Pointer imageWriter = LabelImageWriterType::New();
    imageWriter->SetInput(img);
    imageWriter->SetFileName(currentFile);
    imageWriter->Update();    

    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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

    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;

     for(unsigned int column = 0; column < nbTilesX ; ++column)
      {
      for(unsigned int row = 0; row < nbTilesY ; ++row)
        {
        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;
  }
183 184 185 186

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

189 190
    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.");
191 192
    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");
193
    SetDocSeeAlso("MeanShiftSmoothing, LSMSSmallRegionsMerging, LSMSVectorization");
194 195 196 197 198 199 200 201 202 203
    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");
204
    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." );
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

    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");
    SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is deleted.");  
    SetDefaultParameterInt("minsize", 0);
    SetMinimumParameterIntValue("minsize", 0);
    MandatoryOff("minsize");
    
224 225 226 227 228 229 230 231 232
    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);
233 234 235 236 237 238

    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");

239 240
    AddParameter(ParameterType_Empty,"cleanup","Temporary files cleaning");
    EnableParameter("cleanup");
241 242 243 244 245 246 247 248 249 250
    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");
251 252
    SetDocExampleParameterValue("tilesizex","256");
    SetDocExampleParameterValue("tilesizey","256");
253 254 255 256 257 258 259 260 261
    
  }

  void DoUpdateParameters()
  {      
  }

  void DoExecute()
  {
262 263
    m_FilesToRemoveAfterExecute.clear();

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


    // Ensure that temporary directory exists if activated:
    if(IsParameterEnabled("tmpdir"))
      {
278 279 280 281
      if(!itksys::SystemTools::FileExists(GetParameterString("tmpdir").c_str()))
        {
        m_TmpDirCleanup = true;
        }
282 283 284 285 286 287 288 289 290 291 292
      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;
        
293
    if(HasValue("inpos"))
294
      {
295
      spatialIn = GetParameterImage("inpos");
296 297 298 299 300
      }

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

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

306 307 308 309 310
    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);

311 312
    unsigned long regionCount = 0;
  
313 314 315
    //Segmentation by the connected component per tile and label
    //shifting
    otbAppLogINFO(<<"Tile shifting ...");
316
      
317 318
    for(unsigned int row = 0; row < nbTilesY ; ++row)
      for(unsigned int column = 0; column < nbTilesX ; ++column)
319
        {		
320 321 322 323 324
        // 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);
325
	    
326 327 328 329 330 331 332 333 334 335
        //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();

336
        //- the spatial image (final positions) if available
337 338
        MultiChannelExtractROIFilterType::Pointer extractROIFilter2 = MultiChannelExtractROIFilterType::New();
        ConcatenateType::Pointer concat = ConcatenateType::New();
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        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();
	  
          //Concatenation of the two input images
          concat->SetInput1(extractROIFilter->GetOutput());
          concat->SetInput2(extractROIFilter2->GetOutput());
          concat->Update();
          
          ccFilter->SetInput(concat->GetOutput());
          }
        else
          {
	  ccFilter->SetInput(extractROIFilter->GetOutput());
          }
        
362 363 364 365 366
        //Expression 1 : radiometric distance < ranger
        std::stringstream expr;
        expr<<"sqrt((p1b1-p2b1)*(p1b1-p2b1)";
        for(unsigned int i=1;i<nbComp;i++)
          expr<<"+(p1b"<<i+1<<"-p2b"<<i+1<<")*(p1b"<<i+1<<"-p2b"<<i+1<<")";
367
        expr<<")"<<"<"<<ranger;
368

369 370 371 372 373 374 375
        if(HasValue("inpos"))
          {
          //Expression 2 : final positions < spatialr
          expr<<" and sqrt((p1b"<<nbComp+1<<"-p2b"<<nbComp+1<<")*(p1b"<<nbComp+1<<"-p2b"<<nbComp+1<<")+";
          expr<<"(p1b"<<nbComp+2<<"-p2b"<<nbComp+2<<")*(p1b"<<nbComp+2<<"-p2b"<<nbComp+2<<"))"<<"<"<<spatialr; 
          }
        
376 377 378
        //Segmentation
        ccFilter->GetFunctor().SetExpression(expr.str());
        ccFilter->Update();	    
379
    
380 381
        std::stringstream ssexpr;
        ssexpr<<"label+"<<regionCount;
382
	    
383 384 385 386 387 388 389 390 391 392 393 394
        //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();
        stats->SetInput(ccFilter->GetOutput());	
        stats->Update();
        regionCount+=stats->GetMaximum();

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

399 400
    // Step 2: create the look-up table for all overlaps
    otbAppLogINFO(<<"LUT creation ...");
401 402 403 404 405
    std::vector<LabelImagePixelType> LUT; 
    LUT.clear();
    LUT.resize(regionCount+1);
    for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel)
      LUT[curLabel] = curLabel;
406
      
407
    for(unsigned int row = 0; row < nbTilesY ; row++)
408
      {
409 410 411 412 413 414
      for(unsigned int column = 0; column < nbTilesX ; column++)
        {
        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);
415
      
416
        std::string tileIn = CreateFileName(row,column,"SEG");
417

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

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        // Analyse intersection between in and up tiles
        if(row>0)
          {
          std::string tileUp = CreateFileName(row-1,column,"SEG");
	  LabelImageReaderType::Pointer tileUpReader = LabelImageReaderType::New();
	  tileUpReader->SetFileName(tileUp);
          tileUpReader->Update();

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

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

          for(pixelIndexIn[0]=0;pixelIndexIn[0]<static_cast<long>(sizeX-1);++pixelIndexIn[0])
            {
            pixelIndexUp[0] = pixelIndexIn[0];

            LabelImagePixelType curCanLabel = tileInReader->GetOutput()->GetPixel(pixelIndexIn);
	    while(LUT[curCanLabel] != curCanLabel) 
              {
              curCanLabel = LUT[curCanLabel];
              }
	    LabelImagePixelType adjCanLabel = tileUpReader->GetOutput()->GetPixel(pixelIndexUp);
            
	    while(LUT[adjCanLabel] != adjCanLabel)
              {
              adjCanLabel = LUT[adjCanLabel];
              }
	    if(curCanLabel < adjCanLabel) 
              {
              LUT[adjCanLabel] = curCanLabel;
              }
	    else
              {
              LUT[LUT[curCanLabel]] = adjCanLabel; LUT[curCanLabel] = adjCanLabel;
              }
            }
          }
462

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        // Analyse intersection between in and left tiles
         if(column>0)
          {
          std::string tileLeft = CreateFileName(row,column-1,"SEG");
	  LabelImageReaderType::Pointer tileLeftReader = LabelImageReaderType::New();
	  tileLeftReader->SetFileName(tileLeft);
          tileLeftReader->Update();

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

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

          for(pixelIndexIn[1]=0;pixelIndexIn[1]<static_cast<long>(sizeY-1);++pixelIndexIn[1])
            {
            pixelIndexUp[1] = pixelIndexIn[1];

            LabelImagePixelType curCanLabel = tileInReader->GetOutput()->GetPixel(pixelIndexIn);
	    while(LUT[curCanLabel] != curCanLabel) 
              {
              curCanLabel = LUT[curCanLabel];
              }
	    LabelImagePixelType adjCanLabel = tileLeftReader->GetOutput()->GetPixel(pixelIndexUp);
	    while(LUT[adjCanLabel] != adjCanLabel)
              { 
              adjCanLabel = LUT[adjCanLabel];
              }
	    if(curCanLabel < adjCanLabel) 
              {
              LUT[adjCanLabel] = curCanLabel;
              }
	    else
              {
              LUT[LUT[curCanLabel]] = adjCanLabel; LUT[curCanLabel] = adjCanLabel;
              }
            }
          }
501 502
        }
      }
503
    
504
    // Reduce LUT to canonical labels
505
    for(LabelImagePixelType label = 1; label < regionCount+1; ++label)
506
      {             
507
      LabelImagePixelType can = label;
508 509 510 511
      while(LUT[can] != can) 
        {
        can = LUT[can];
        }
512 513
      LUT[label] = can;
      }
514
    otbAppLogINFO(<<"LUT size: "<<LUT.size()<<" segments");
515
 
516 517 518
    // These variables will be used to estimate the size of each
    // region on the flow
    std::vector<unsigned long> sizePerRegion(regionCount+1,0);
519

520
    otbAppLogINFO(<<"Tiles relabelisation ...");
521 522 523
    for(unsigned int column = 0; column < nbTilesX ; ++column)
      {
      for(unsigned int row = 0; row < nbTilesY ; ++row)
524
        {
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	unsigned long startX = column*sizeTilesX;
        unsigned long startY = row*sizeTilesY;
	unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX);
        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();
	labelImage->SetInput(readerIn->GetOutput());
	labelImage->SetStartX(0);
	labelImage->SetStartY(0);
	labelImage->SetSizeX(sizeX);
	labelImage->SetSizeY(sizeY);
        
        // Relabel tile according to look-up table
        ChangeLabelImageFilterType::Pointer changeLabel = ChangeLabelImageFilterType::New();
	changeLabel->SetInput(labelImage->GetOutput());
546
	
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        // Fill LUT
        for(LabelImagePixelType label = 1;label<regionCount+1; ++label)
          {
	  if(label!=LUT[label]) 
            {
            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());
	for (it = it.Begin(); !it.IsAtEnd(); ++it) 
563
          {
564
          sizePerRegion[it.Value()]+=1;
565
          }
566 567 568 569 570

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

        // Remove previous tile (not needed anymore)
571
        RemoveFile(tileIn);
572
        }
573
      }
574

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

578 579
    unsigned int smallCount = 0;

580 581 582 583 584
      // 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)
585
        {
586
        if(sizePerRegion[curLabel]<minRegionSize) 
587
          {
588
          newLabels[curLabel]=0;
589
          ++smallCount;
590
          }
591
        else
592
          {
593 594
          newLabels[curLabel]=newLab;
          newLab+=1;
595 596 597
          }
        }

598
      otbAppLogINFO(<<smallCount<<" small regions will be removed");
599

600 601 602 603
      // Clear sizePerRegion, we do not need it anymore
      sizePerRegion.clear();
     
      for(unsigned int column = 0; column < nbTilesX ; ++column)
604
        {
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        for(unsigned int row = 0; row < nbTilesY ; ++row)
          {
          std::string tileIn = CreateFileName(row,column,"RELAB");

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

          ChangeLabelImageFilterType::Pointer changeLabel = ChangeLabelImageFilterType::New();
          changeLabel->SetInput(readerIn->GetOutput());
          for(LabelImagePixelType label = 1;label<regionCount+1; ++label)
            {
            if(label != newLabels[label])
              {
              changeLabel->SetChange(label,newLabels[label]);
              }
            }
          
          // Write the relabeled tile
623
          std::string tmpfile = WriteTile(changeLabel->GetOutput(),row,column,"FINAL");
624 625
          m_FilesToRemoveAfterExecute.push_back(tmpfile);

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

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

638 639
      m_FilesToRemoveAfterExecute.push_back(vrtfile);

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

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

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

652
      SetParameterOutputImage("out",m_ImportGeoInformationFilter->GetOutput());
653
  }
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

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

      for(std::vector<std::string>::iterator it = m_FilesToRemoveAfterExecute.begin();
          it!=m_FilesToRemoveAfterExecute.end();++it)
        {
        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();
  }
676 677 678 679 680 681 682
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSSegmentation)