lsgrmGraphOperations.txx 30.7 KB
Newer Older
remicres's avatar
remicres committed
1 2
//#include "lsgrmGraphOperations.h"
#include <unistd.h>
3 4 5 6

namespace lsgrm
{

remicres's avatar
remicres committed
7 8 9 10 11
template<class TSegmenter>
typename TSegmenter::ImageType::Pointer ReadImageRegion(
    typename TSegmenter::ImageType * inputPtr,
    typename TSegmenter::ImageType::RegionType region)
{
12

remicres's avatar
remicres committed
13 14 15 16 17 18 19
  typedef typename otb::MultiChannelExtractROI<typename TSegmenter::ImageType::InternalPixelType,
      typename TSegmenter::ImageType::InternalPixelType> ExtractROIFilterType;
  typename ExtractROIFilterType::Pointer filter = ExtractROIFilterType::New();
  filter->SetInput(inputPtr);
  filter->SetExtractionRegion(region);
  filter->SetReleaseDataFlag(true);
  filter->Update();
20

remicres's avatar
remicres committed
21 22
  return filter->GetOutput();
}
23

remicres's avatar
remicres committed
24
template<class TSegmenter>
remicres's avatar
remicres committed
25 26
typename TSegmenter::LabelImageType::Pointer
MergeAllGraphsAndAchieveSegmentation(
remicres's avatar
remicres committed
27 28 29 30 31 32 33
    const typename TSegmenter::ParameterType& params,
    const float& threshold,
    std::vector<ProcessingTile>& tiles,
    const unsigned int nbTilesX,
    const unsigned int nbTilesY,
    const unsigned int imageWidth,
    const unsigned int imageHeight,
34 35
    const unsigned int imageBands,
    unsigned int numberOfIterations)
remicres's avatar
remicres committed
36
{
37

38 39 40
  std::cout << "--- Graph aggregation...\n" << std::endl;

  // TODO parallelize this ?
remicres's avatar
remicres committed
41 42 43 44
#ifdef OTB_USE_MPI
  if (otb::MPIConfig::Instance()->GetMyRank() != 0)
    return;
#endif
45

remicres's avatar
remicres committed
46
  TSegmenter segmenter;
47 48


remicres's avatar
remicres committed
49 50
  std::cout << "Reading graphs" << std::endl;

remicres's avatar
remicres committed
51 52 53 54
  for(unsigned int row = 0; row < nbTilesY; ++row)
    {
    for(unsigned int col = 0; col < nbTilesX; col++)
      {
remicres's avatar
remicres committed
55 56
      std::cout << "\tImporting graph of tile " << (row*nbTilesX + col) << " / " << (nbTilesX*nbTilesY) << std::endl;

57
      InsertNodesFromTile<TSegmenter>(segmenter.m_Graph, tiles[row*nbTilesX + col], false);
remicres's avatar
remicres committed
58 59
      }
    }
60

remicres's avatar
remicres committed
61
  std::cout << "Removing duplicated nodes and updating neighbors" << std::endl;
62

remicres's avatar
remicres committed
63 64 65 66 67
  // TODO this might be parallelized...
  for(unsigned int row = 0; row < nbTilesY; ++row)
    {
    for(unsigned int col = 0; col < nbTilesX; col++)
      {
remicres's avatar
remicres committed
68
      std::cout << "Cleaning nodes of tile " << (row*nbTilesX + col) << " / " << (nbTilesX*nbTilesY) << std::endl;
69

remicres's avatar
remicres committed
70 71
      std::unordered_map<long unsigned int,
      std::vector<typename TSegmenter::NodePointerType> > borderPixelMap;
72

remicres's avatar
remicres committed
73
      std::cout << "\tBuildBorderPixelMap..." << std::endl;
74

remicres's avatar
remicres committed
75 76
      BuildBorderPixelMap<TSegmenter>(segmenter.m_Graph, tiles[row*nbTilesX + col], row, col,
          nbTilesX, nbTilesY, borderPixelMap, imageWidth);
77

remicres's avatar
remicres committed
78
      std::cout << "\tRemoveDuplicatedNodes..." << std::endl;
79

remicres's avatar
remicres committed
80
      RemoveDuplicatedNodes<TSegmenter>(borderPixelMap, segmenter.m_Graph, imageWidth);
81

remicres's avatar
remicres committed
82
      std::cout << "\tUpdateNeighborsOfNoneDuplicatedNodes..." << std::endl;
83

remicres's avatar
remicres committed
84
      UpdateNeighborsOfNoneDuplicatedNodes<TSegmenter>(borderPixelMap, imageWidth, imageHeight);
remicres's avatar
remicres committed
85 86 87
      }
    }

remicres's avatar
remicres committed
88
  std::cout << "Achieve segmentation process" ;
remicres's avatar
remicres committed
89 90 91 92 93 94 95 96

  // Segmentation of the graph
  segmenter.SetImageWidth(imageWidth);
  segmenter.SetImageHeight(imageHeight);
  segmenter.SetNumberOfComponentsPerPixel(imageBands);
  segmenter.SetParam(params);
  segmenter.SetThreshold(threshold);
  segmenter.SetDoBFSegmentation(true);
97
  segmenter.SetNumberOfIterations(numberOfIterations);
remicres's avatar
remicres committed
98 99 100

  lsrm::GraphOperations<TSegmenter>::PerfomAllIterationsWithLMBFAndConstThreshold(segmenter);

remicres's avatar
remicres committed
101 102
  //  // Write output graph to the output graph directory
  //  WriteGraph<TSegmenter>(segmenter.m_Graph, tmpDir, 0, 0);
remicres's avatar
remicres committed
103

remicres's avatar
remicres committed
104
  return segmenter.GetLabeledClusteredOutput();
105

106 107
}

remicres's avatar
remicres committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
template<class TSegmenter>
long long unsigned int RunPartialSegmentation(const typename TSegmenter::ParameterType& params,
    const float& threshold,
    const unsigned int niter,
    std::vector<ProcessingTile>& tiles,
    const unsigned int nbTilesX,
    const unsigned int nbTilesY,
    const unsigned int imageWidth,
    const unsigned int imageHeight,
    const unsigned int imageBands,
    bool& isFusion)
{
  long long unsigned int accumulatedMemory = 0;
  isFusion = false;

  const unsigned int numberOfNeighborLayers = static_cast<unsigned int>(pow(2, niter + 1) - 2);

  std::cout << "--- Running partial segmentations...\nNumber of neighbor layers " << numberOfNeighborLayers << std::endl;

  for(unsigned int row = 0; row < nbTilesY; ++row)
    {
    for(unsigned int col = 0; col < nbTilesX; col++)
      {
      if (MyTurn(row*nbTilesX + col))
        {
133 134 135
        // Get the current tile
        ProcessingTile currentTile = tiles[row*nbTilesX + col];

remicres's avatar
remicres committed
136
        TSegmenter segmenter;
137
        std::cout << "Processing tile " << row << ", " << col << std::endl;
remicres's avatar
remicres committed
138
        std::cout << "\tLoad graph..." << std::endl;
139

remicres's avatar
remicres committed
140
        // Load the graph
141
        ReadGraph<TSegmenter>(segmenter.m_Graph, currentTile.nodeFileName, currentTile.edgeFileName);
remicres's avatar
remicres committed
142 143 144 145

        // Add stability margin to the graph
        {
          std::cout << "\tAdd stability margin..." << std::endl;
146
          AddStabilityMargin<TSegmenter>(segmenter.m_Graph, tiles,
remicres's avatar
remicres committed
147
              row, col, nbTilesX, nbTilesY);
remicres's avatar
remicres committed
148 149 150 151 152

          std::unordered_map<long unsigned int,
          std::vector<typename TSegmenter::NodePointerType> > borderPixelMap;

          std::cout << "\tBuild border pixel map..." << std::endl;
153
          BuildBorderPixelMap<TSegmenter>(segmenter.m_Graph, currentTile, row, col,
remicres's avatar
remicres committed
154 155 156 157 158 159 160 161 162 163 164
              nbTilesX, nbTilesY, borderPixelMap, imageWidth);

          std::cout << "\tRemove duplicated nodes..." << std::endl;
          RemoveDuplicatedNodes<TSegmenter>(borderPixelMap, segmenter.m_Graph, imageWidth);

          std::cout << "\tUpdate neighbors.." << std::endl;
          UpdateNeighborsOfNoneDuplicatedNodes<TSegmenter>(borderPixelMap,
              imageWidth,
              imageHeight);

          std::cout << "\tRemove useless.." << std::endl;
165
          RemoveUselessNodes<TSegmenter>(currentTile, segmenter.m_Graph,
remicres's avatar
remicres committed
166 167 168 169 170 171 172 173 174 175 176 177 178
              row, col, nbTilesX, nbTilesY, imageWidth, numberOfNeighborLayers);

        }

        // Segmentation of the graph
        segmenter.SetImageWidth(imageWidth);
        segmenter.SetImageHeight(imageHeight);
        segmenter.SetNumberOfComponentsPerPixel(imageBands);
        segmenter.SetParam(params);
        segmenter.SetThreshold(threshold);
        segmenter.SetDoBFSegmentation(false);
        segmenter.SetNumberOfIterations(niter);

179
        std::cout << "\tPartial segmentation";
remicres's avatar
remicres committed
180 181 182 183 184 185
        auto merge = lsrm::GraphOperations<TSegmenter>::PerfomAllIterationsWithLMBFAndConstThreshold(segmenter);

        if(merge == true)
          isFusion = true;

        // Remove unstable segments
186
        std::cout << "\tRemove unstable segments..." << std::endl;
187
        RemoveUnstableSegments<TSegmenter>(segmenter.m_Graph, currentTile, imageWidth);
remicres's avatar
remicres committed
188 189

        // Retrieve the amount of memory to store this graph
190
        std::cout << "\tGet graph memory..." << std::endl;
191
        accumulatedMemory += segmenter.GetGraphMemory();
remicres's avatar
remicres committed
192

193
        // Write graph to temporay directory
194
        std::cout << "\tWrite graph..." << std::endl;
195
        WriteGraph<TSegmenter>(segmenter.m_Graph, currentTile.nodeFileName, currentTile.edgeFileName);
remicres's avatar
remicres committed
196 197 198 199 200 201
        }
      }
    }

#ifdef OTB_USE_MPI
  otb::MPIConfig::Instance()->barrier();
202 203
#endif

remicres's avatar
remicres committed
204 205 206 207 208 209 210 211 212
  std::cout << "Add stability margins to graph for the next round..."<< std::endl;

  // During this step we extract the stability margin for the next round
  for(unsigned int row = 0; row < nbTilesY; ++row)
    {
    for(unsigned int col = 0; col < nbTilesX; col++)
      {
      if (MyTurn(row*nbTilesX + col))
        {
213 214
        // Get current tile
        ProcessingTile currentTile = tiles[row*nbTilesX + col];
remicres's avatar
remicres committed
215 216

        // Load the graph
217 218
        typename TSegmenter::GraphType graph;
        ReadGraph<TSegmenter>(graph, currentTile.nodeFileName, currentTile.edgeFileName);
remicres's avatar
remicres committed
219 220 221 222 223 224

        // Extract stability margin for all borders different from 0 imageWidth-1 et imageHeight -
        // and write them to the stability margin
        {
          std::unordered_map<typename TSegmenter::NodePointerType, unsigned int> borderNodeMap;

225
          DetectBorderNodes<TSegmenter>(graph, currentTile,
remicres's avatar
remicres committed
226 227 228 229
              borderNodeMap, imageWidth, imageHeight);

          ExtractStabilityMargin<TSegmenter>(borderNodeMap, numberOfNeighborLayers);

230
          WriteStabilityMargin<TSegmenter>(borderNodeMap, currentTile.nodeMarginFileName, currentTile.edgeMarginFileName);
remicres's avatar
remicres committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 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 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 501 502 503 504 505 506 507 508 509
        }
        std::cout << "Process finished on tile " << (row*nbTilesX + col) << std::endl;
        }
      }
    }
  std::cout << std::endl;

  return accumulatedMemory;
}

template<class TSegmenter>
void RemoveUselessNodes(ProcessingTile& tile,
    typename TSegmenter::GraphType& graph,
    const unsigned int rowTile,
    const unsigned int colTile,
    const unsigned int nbTilesX,
    const unsigned int nbTilesY,
    const unsigned int imageWidth,
    const unsigned int numberOfLayers)
{
  using NPtr = typename TSegmenter::NodePointerType;
  using UI = unsigned int;
  unsigned int rowPixel, colPixel;
  std::unordered_map<NPtr, UI> marginNodes;

  for(auto& node : graph.m_Nodes)
    {
    if(node->m_Bbox.m_UX > tile.columns[0] &&
        node->m_Bbox.m_UY > tile.rows[0] &&
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[1] &&
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[1])
      continue;
    else if(node->m_Bbox.m_UX > tile.columns[1] ||
        node->m_Bbox.m_UY > tile.rows[1] ||
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[0] ||
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[0])
      continue;
    else
      {
      lp::CellLists borderpixels;
      lp::ContourOperations::GenerateBorderCells(borderpixels, node->m_Contour, node->m_Id, imageWidth);

      for(auto& pix : borderpixels)
        {
        rowPixel = pix / imageWidth;
        colPixel = pix % imageWidth;

        if(rowPixel == tile.rows[0] || rowPixel == tile.rows[1])
          {
          if(colPixel >= tile.columns[0] && colPixel <= tile.columns[1])
            {
            marginNodes.insert(std::pair<NPtr, UI>(node, 0));
            break;
            }
          }
        else if(colPixel == tile.columns[0] || colPixel == tile.columns[1])
          {
          if(rowPixel >= tile.rows[0] && rowPixel <= tile.rows[1])
            {
            marginNodes.insert(std::pair<NPtr, UI>(node, 0));
            break;
            }
          }
        else
          continue;
        }
      }
    }

  ExtractStabilityMargin<TSegmenter>(marginNodes, numberOfLayers);

  for(auto& node : graph.m_Nodes)
    {
    if(node->m_Bbox.m_UX > tile.columns[0] &&
        node->m_Bbox.m_UY > tile.rows[0] &&
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[1] &&
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[1])
      continue;
    else if(marginNodes.find(node) == marginNodes.end())
      {
      RemoveEdgeToUnstableNode<TSegmenter>(node);
      node->m_Expired = true;
      }
    else
      continue;
    }

  lsrm::GraphOperations<TSegmenter>::RemoveExpiredNodes(graph);
}

template<class TSegmenter>
void UpdateNeighborsOfNoneDuplicatedNodes(std::unordered_map<long unsigned int,
    std::vector<typename TSegmenter::NodePointerType> >& borderPixelMap,
    const unsigned int imageWidth,
    const unsigned int imageHeight)
{
  using EdgeType = typename TSegmenter::EdgeType;
  unsigned int boundary;

  for(auto& pn : borderPixelMap)
    {
    long int neighborhood[4];
    lsrm::FOURNeighborhood(neighborhood, pn.first, imageWidth, imageHeight);

    for(short j = 0; j < 4; ++j)
      {
      if(neighborhood[j] > -1)
        {
        auto isNeigh = borderPixelMap.find(neighborhood[j]);
        if(isNeigh != borderPixelMap.end())
          {
          auto currNode = pn.second.front();
          auto neigh = isNeigh->second.front();

          if(currNode != neigh)
            {
            auto toNeigh = lsrm::GraphOperations<TSegmenter>::FindEdge(currNode, neigh);

            if(toNeigh == currNode->m_Edges.end())
              {
              boundary = 0;

              lp::CellLists borderPixels;
              lp::ContourOperations::GenerateBorderCells(borderPixels, currNode->m_Contour, currNode->m_Id, imageWidth);

              for(auto pix : borderPixels)
                {
                if(borderPixelMap.find(pix) != borderPixelMap.end())
                  {
                  long int pixNeighborhood[4];
                  lsrm::FOURNeighborhood(pixNeighborhood, pix, imageWidth, imageHeight);

                  for(short k = 0; k < 4; k++)
                    {
                    if(pixNeighborhood[k] > -1)
                      {
                      auto isNeighPix = borderPixelMap.find(pixNeighborhood[k]);

                      if(isNeighPix != borderPixelMap.end() && isNeighPix->second.front() == neigh)
                        boundary++;
                      }
                    }
                  }
                }

              currNode->m_Edges.push_back(EdgeType(neigh, 0, boundary));
              neigh->m_Edges.push_back(EdgeType(currNode, 0, boundary));
              }
            }
          }
        }
      }
    }
}

template<class TSegmenter>
void RemoveDuplicatedNodes(std::unordered_map<long unsigned int,
    std::vector<typename TSegmenter::NodePointerType> >& borderPixelMap,
    typename TSegmenter::GraphType& graph,
    const unsigned int imageWidth)
{
  using EdgeType = typename TSegmenter::EdgeType;
  unsigned int boundary;

  // Explore the border nodes
  for(auto& pn : borderPixelMap)
    {
    // no valid nodes are those who have already been considered.
    if(pn.second.size() > 1)
      {
      auto refNode = pn.second.front();

      // Explore duplicated nodes
      for(auto nit = pn.second.begin() + 1; nit != pn.second.end(); ++nit)
        {
        // Explore their edges
        for(auto& edg : (*nit)->m_Edges)
          {
          auto neighNit = edg.GetRegion();

          auto toNit = lsrm::GraphOperations<TSegmenter>::FindEdge(neighNit, *nit);

          assert(toNit != edg.GetRegion()->m_Edges.end());

          boundary = edg.m_Boundary;

          neighNit->m_Edges.erase(toNit);

          auto toRefNode = lsrm::GraphOperations<TSegmenter>::FindEdge(neighNit, refNode);

          if(toRefNode == neighNit->m_Edges.end())
            {
            // Create an edge neighNit -> refNode
            neighNit->m_Edges.push_back(EdgeType(refNode, 0, boundary));
            // Create an edge refNode -> neighNit
            refNode->m_Edges.push_back(EdgeType(neighNit, 0, boundary));
            }
          }

        (*nit)->m_Expired = true;
        }

      lp::CellLists borderPixels;
      lp::ContourOperations::GenerateBorderCells(borderPixels, refNode->m_Contour, refNode->m_Id, imageWidth);

      for(auto& pix : borderPixels)
        {
        if(borderPixelMap.find(pix) != borderPixelMap.end())
          {
          borderPixelMap[pix].clear();
          borderPixelMap[pix].push_back(refNode);
          }
        }
      }
    }

  lsrm::GraphOperations<TSegmenter>::RemoveExpiredNodes(graph);
}

// Build the map assigning for each border pixel on the borders the node it belongs to.
template<class TSegmenter>
void BuildBorderPixelMap(typename TSegmenter::GraphType& graph,
    ProcessingTile& tile,
    const unsigned int rowTile,
    const unsigned int colTile,
    const unsigned int nbTilesX,
    const unsigned int nbTilesY,
    std::unordered_map<long unsigned int,
    std::vector<typename TSegmenter::NodePointerType> >& borderPixelMap,
    const unsigned int imageWidth)
{
  unsigned int rowPixel, colPixel;
  unsigned int rowMin = (tile.rows[0] > 0) ? tile.rows[0] - 1 : tile.rows[0];
  unsigned int rowMax = tile.rows[1] + 1;
  unsigned int colMin = (tile.columns[0] > 0) ? tile.columns[0] - 1 : tile.columns[0];
  unsigned int colMax = tile.columns[1] + 1;

  for(auto& node : graph.m_Nodes)
    {
    if(node->m_Bbox.m_UX > tile.columns[0] &&
        node->m_Bbox.m_UY > tile.rows[0] &&
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[1] &&
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[1])
      {
      continue;
      }
    else
      {
      lp::CellLists borderPixels;
      lp::ContourOperations::GenerateBorderCells(borderPixels, node->m_Contour, node->m_Id, imageWidth);

      for(auto& pix : borderPixels)
        {
        rowPixel = pix / imageWidth;
        colPixel = pix % imageWidth;

        if(rowTile > 0 && (rowPixel == tile.rows[0] || rowPixel == rowMin))
          {
          borderPixelMap[pix].push_back(node);
          }
        else if(colTile < nbTilesX - 1 && ( colPixel == tile.columns[1] || colPixel == colMax))
          {
          borderPixelMap[pix].push_back(node);
          }
        else if(rowTile < nbTilesY - 1 && (rowPixel == tile.rows[1] || rowPixel == rowMax))
          {
          borderPixelMap[pix].push_back(node);
          }
        else if(colTile > 0 && ( colPixel == tile.columns[0] || colPixel == colMin))
          {
          borderPixelMap[pix].push_back(node);
          }
        else
          continue;
        }
      }
    }
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
template<class TSegmenter>
void InsertNodesFromTile(typename TSegmenter::GraphType& graph,
    ProcessingTile& tile, bool margin = true)
{
  typename TSegmenter::GraphType subgraph;
  if (margin)
    {
    ReadGraph<TSegmenter>(subgraph, tile.nodeMarginFileName, tile.edgeMarginFileName);
    }
  else
    {
    ReadGraph<TSegmenter>(subgraph, tile.nodeFileName, tile.edgeFileName);
    }

  graph.m_Nodes.insert(graph.m_Nodes.end(), subgraph.m_Nodes.begin(), subgraph.m_Nodes.end());

}

remicres's avatar
remicres committed
528 529
template<class TSegmenter>
void AddStabilityMargin(typename TSegmenter::GraphType& graph,
530
    std::vector<ProcessingTile>& tiles,
remicres's avatar
remicres committed
531 532 533
    const unsigned int row,
    const unsigned int col,
    const unsigned int nbTilesX,
remicres's avatar
remicres committed
534
    const unsigned int nbTilesY)
remicres's avatar
remicres committed
535 536 537 538 539
{

  // Margin to retrieve at top
  if(row > 0)
    {
540
    InsertNodesFromTile<TSegmenter>(graph, tiles[(row-1) * nbTilesX + col]);
remicres's avatar
remicres committed
541 542 543 544 545
    }

  // Margin to retrieve at right
  if(col < nbTilesX - 1)
    {
546
    InsertNodesFromTile<TSegmenter>(graph, tiles[row * nbTilesX + (col+1)]);
remicres's avatar
remicres committed
547 548 549 550 551
    }

  // Margin to retrieve at bottom
  if(row < nbTilesY - 1)
    {
552
    InsertNodesFromTile<TSegmenter>(graph, tiles[(row+1) * nbTilesX + col]);
remicres's avatar
remicres committed
553
    }
554

remicres's avatar
remicres committed
555 556 557
  // Margin to retrieve at left
  if(col > 0)
    {
558
    InsertNodesFromTile<TSegmenter>(graph, tiles[row * nbTilesX + (col-1)]);
remicres's avatar
remicres committed
559 560 561 562 563
    }

  // Margin to retrieve at top right
  if(row > 0 && col < nbTilesX - 1)
    {
564
    InsertNodesFromTile<TSegmenter>(graph, tiles[(row-1) * nbTilesX + (col+1)]);
remicres's avatar
remicres committed
565 566 567 568 569
    }

  // Margin to retrieve at bottom right
  if(row < nbTilesY - 1 && col < nbTilesX - 1)
    {
570
    InsertNodesFromTile<TSegmenter>(graph, tiles[ (row+1) * nbTilesX + (col+1)]);
remicres's avatar
remicres committed
571 572 573 574 575
    }

  // Margin to retrieve at bottom left
  if(row < nbTilesY - 1 && col > 0)
    {
576
    InsertNodesFromTile<TSegmenter>(graph, tiles[ (row+1) * nbTilesX + (col-1)]);
remicres's avatar
remicres committed
577 578 579 580 581
    }

  // Margin to retrieve at top left
  if(row > 0 && col > 0)
    {
582
    InsertNodesFromTile<TSegmenter>(graph, tiles[ (row-1) * nbTilesX + (col-1)]);
remicres's avatar
remicres committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    }
}

template<class TSegmenter>
long long unsigned int RunFirstPartialSegmentation(
    typename TSegmenter::ImageType * inputPtr,
    const typename TSegmenter::ParameterType& params,
    const float& threshold,
    const unsigned int niter,
    const unsigned int niter2,
    std::vector<ProcessingTile>& tiles,
    const unsigned int nbTilesX,
    const unsigned int nbTilesY,
    const unsigned int tileWidth,
    const unsigned int tileHeight,
    bool& isFusion)
{

  using ImageType = typename TSegmenter::ImageType;
602 603
  const unsigned int imageWidth = inputPtr->GetLargestPossibleRegion().GetSize()[0];
  const unsigned int imageHeight = inputPtr->GetLargestPossibleRegion().GetSize()[1];
remicres's avatar
remicres committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

  long long unsigned int accumulatedMemory = 0;
  isFusion = false;

  const unsigned int numberOfNeighborLayers = static_cast<unsigned int>(pow(2, niter2 + 1) - 2);

  std::cout << "--- Running fist partial segmentation...\nNumber of neighbor layers " << numberOfNeighborLayers << std::endl;

  for(unsigned int row = 0; row < nbTilesY; ++row)
    {
    for(unsigned int col = 0; col < nbTilesX; col++)
      {
      if (MyTurn(row*nbTilesX + col))
        {
        // Reading images
        ProcessingTile currentTile = tiles[row*nbTilesX + col];
620

621
        std::cout << "Processing tile " <<  (row*nbTilesX + col) << " / " << (nbTilesX*nbTilesY) <<
remicres's avatar
remicres committed
622 623 624 625 626 627 628
            " (" << col << ", " << row << ")" <<
            " start: [" << currentTile.region.GetIndex()[0] << ", " << currentTile.region.GetIndex()[1] <<
            "] size: [" << currentTile.region.GetSize()[0] << ", " << currentTile.region.GetSize()[1] << "]" << std::endl;

        typename ImageType::Pointer imageTile = ReadImageRegion<TSegmenter>(inputPtr, currentTile.region);

        // Segmenting image
remicres's avatar
remicres committed
629
        std::cout << "\tSegmenting";
remicres's avatar
remicres committed
630 631 632 633 634 635 636 637 638 639 640 641
        TSegmenter segmenter;
        segmenter.SetParam(params);
        segmenter.SetThreshold(threshold);
        segmenter.SetDoBFSegmentation(false);
        segmenter.SetNumberOfIterations(niter);
        segmenter.SetInput(imageTile);
        segmenter.Update();

        if(segmenter.GetComplete() == false)
          isFusion = true;

        // Rescale the graph to be in the reference of the image
642
        std::cout << "\tRescaling graph..." << std::endl;
remicres's avatar
remicres committed
643
        RescaleGraph<TSegmenter>(segmenter.m_Graph,
644
            currentTile,
remicres's avatar
remicres committed
645 646 647 648 649 650 651
            row,
            col,
            tileWidth,
            tileHeight,
            imageWidth);

        // Remove unstable segments
652
        std::cout << "\tRemoving unstable segments..." << std::endl;
653
        RemoveUnstableSegments<TSegmenter>(segmenter.m_Graph, currentTile, imageWidth);
remicres's avatar
remicres committed
654 655

        // Retrieve the amount of memory to store this graph
656
        std::cout << "\tRetrieving graph memory..." << std::endl;
657
        accumulatedMemory += segmenter.GetGraphMemory();
remicres's avatar
remicres committed
658

659 660 661
        // Write graph to temporay directory
        std::cout << "\tWriting graph..." << currentTile.nodeFileName << " et " <<  currentTile.edgeFileName << std::endl;
        WriteGraph<TSegmenter>(segmenter.m_Graph, currentTile.nodeFileName, currentTile.edgeFileName);
remicres's avatar
remicres committed
662 663 664

        // Extract stability margin for all borders different from 0 imageWidth-1 et imageHeight -1
        // and write them to the stability margin
665
        std::cout << "\tComputing stability margin..." << std::endl;
remicres's avatar
remicres committed
666 667 668
        {
          std::unordered_map<typename TSegmenter::NodePointerType, unsigned int> borderNodeMap;

669
          DetectBorderNodes<TSegmenter>(segmenter.m_Graph, currentTile,
remicres's avatar
remicres committed
670 671 672 673
              borderNodeMap, imageWidth, imageHeight);

          ExtractStabilityMargin<TSegmenter>(borderNodeMap, numberOfNeighborLayers);

674
          WriteStabilityMargin<TSegmenter>(borderNodeMap, currentTile.nodeMarginFileName, currentTile.edgeMarginFileName);
remicres's avatar
remicres committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
        }
        }
      } // for each col
    } // for each row

  return accumulatedMemory;
}

template<class TSegmenter>
void ExtractStabilityMargin(std::unordered_map<typename TSegmenter::NodePointerType, unsigned int>& nodeMap,
    const unsigned int pmax)
{
  std::vector<typename TSegmenter::NodePointerType> startingNodes;
  startingNodes.reserve(nodeMap.size());
  for(auto& kv: nodeMap)
    startingNodes.push_back(kv.first);

  for(auto& n : startingNodes)
    {
    ExploreDFS<TSegmenter>(n, 0, nodeMap, pmax);
    }
}

template<class TSegmenter>
void ExploreDFS(typename TSegmenter::NodePointerType s,
    const unsigned int p,
    std::unordered_map<typename TSegmenter::NodePointerType, unsigned int>& Cb,
    const unsigned int pmax)
{
  if(p > pmax)
    return;
  else
    {
    if(Cb.find(s) != Cb.end())
      {
      if(p <= Cb[s])
        {
        Cb[s] = p;
        for(auto edg : s->m_Edges)
          {
          ExploreDFS<TSegmenter>(edg.GetRegion(), p + 1, Cb, pmax);
          }
        }
      else
        return;
      }
    else
      {
      Cb[s] = p;
      for(auto edg : s->m_Edges)
        {
        ExploreDFS<TSegmenter>(edg.GetRegion(), p + 1, Cb, pmax);
        }
      }
    }
}

template<class TSegmenter>
void DetectBorderNodes(typename TSegmenter::GraphType& graph,
    ProcessingTile& tile,
    std::unordered_map<typename TSegmenter::NodePointerType, unsigned int>& borderNodeMap,
    const unsigned int imageWidth,
    const unsigned int imageHeight)
{
  using NP = typename TSegmenter::NodePointerType;
  using Uint = unsigned int;
  unsigned int rowPixel, colPixel;

  for(auto& node : graph.m_Nodes)
    {
    if(node->m_Bbox.m_UX > tile.columns[0] &&
        node->m_Bbox.m_UY > tile.rows[0] &&
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[1] &&
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[1])
      continue;
    else
      {
      lp::CellLists borderpixels;
      lp::ContourOperations::GenerateBorderCells(borderpixels, node->m_Contour, node->m_Id, imageWidth);

      for(auto& pix : borderpixels)
        {
        rowPixel = pix / imageWidth;
        colPixel = pix % imageWidth;

        if(tile.rows[0] > 0 && rowPixel == tile.rows[0])
          {
          borderNodeMap.insert(std::pair<NP, Uint>(node, 0));
          break;
          }
        else if(tile.columns[1] < imageWidth - 1 && colPixel == tile.columns[1])
          {
          borderNodeMap.insert(std::pair<NP, Uint>(node, 0));
          break;
          }
        else if(tile.rows[1] < imageHeight - 1 && rowPixel == tile.rows[1])
          {
          borderNodeMap.insert(std::pair<NP, Uint>(node, 0));
          break;
          }
        else if(tile.columns[0] > 0 && colPixel == tile.columns[0])
          {
          borderNodeMap.insert(std::pair<NP, Uint>(node, 0));
          break;
          }
        else continue;
        }
      }
    }
}

786 787

// Generic
remicres's avatar
remicres committed
788
template<class TSegmenter>
789
void ReadGraph(TSegmenter& segmenter,
remicres's avatar
remicres committed
790 791 792 793 794 795 796 797
    const std::string& nodesPath,
    const std::string& edgesPath)
{
  FILE * nodeStream = fopen(nodesPath.c_str(), "r");
  assert(nodeStream != NULL);
  FILE * edgeStream = fopen(edgesPath.c_str(), "r");
  assert(edgeStream != NULL);

798
  segmenter.ReadGraph(nodeStream, edgeStream);
remicres's avatar
remicres committed
799

800
  fclose(nodeStream);
remicres's avatar
remicres committed
801 802 803
  fclose(edgeStream);
}

804 805 806 807 808 809 810 811 812 813
template<class TSegmenter>
void ReadGraph(typename TSegmenter::GraphType& graph,
    const std::string& nodesPath,
    const std::string& edgesPath)
{
  TSegmenter segmenter;
  ReadGraph<TSegmenter>(segmenter, nodesPath, edgesPath);
  graph = segmenter.m_Graph;
}

remicres's avatar
remicres committed
814 815 816 817 818 819 820 821 822 823 824 825 826
// Write stability margin
template<class TSegmenter>
void WriteStabilityMargin(std::unordered_map<
    typename TSegmenter::NodePointerType,
    unsigned int>& stabilityMargin,
    const std::string& nodesPath,
    const std::string& edgesPath)
{
  FILE * nodeStream = fopen(nodesPath.c_str(), "wb");
  assert(nodeStream != NULL);
  FILE * edgeStream = fopen(edgesPath.c_str(), "wb");
  assert(edgeStream != NULL);

827 828 829
  // Write number of nodes
  std::size_t size = stabilityMargin.size();
  fwrite(&size, sizeof(size), 1, nodeStream);
remicres's avatar
remicres committed
830

831
  TSegmenter seg;
remicres's avatar
remicres committed
832 833 834
  for(auto& kv : stabilityMargin)
    {
    auto node = kv.first;
835
    seg.WriteNode(node, nodeStream);
remicres's avatar
remicres committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849

    // Write only edges pointing to nodes which are in the stability margin.
    fwrite(&(node->m_Id), sizeof(node->m_Id), 1, edgeStream);
    std::size_t edgeSize = node->m_Edges.size();
    for(auto& edg : node->m_Edges)
      {
      if(stabilityMargin.find(edg.GetRegion()) == stabilityMargin.end())
        edgeSize--;
      }
    fwrite(&(edgeSize), sizeof(edgeSize), 1, edgeStream);
    for(auto& edg : node->m_Edges)
      {
      if(stabilityMargin.find(edg.GetRegion()) != stabilityMargin.end())
        {
850
        seg.WriteEdge(edg, edgeStream);
remicres's avatar
remicres committed
851 852 853 854 855 856 857 858
        }
      }
    }

  fclose(nodeStream);
  fclose(edgeStream);
}

859
// Write the graph
remicres's avatar
remicres committed
860 861
template<class TSegmenter>
void WriteGraph(typename TSegmenter::GraphType& graph,
862 863
    const std::string& nodeFile,
    const std::string& edgeFile)
remicres's avatar
remicres committed
864 865 866 867 868 869 870
{

  FILE * nodeStream = fopen(nodeFile.c_str(), "wb");
  assert(nodeStream != NULL);
  FILE * edgeStream = fopen(edgeFile.c_str(), "wb");
  assert(edgeStream != NULL);

871 872 873
  // Write number of nodes
  std::size_t size = graph.m_Nodes.size();
  fwrite(&size, sizeof(size), 1, nodeStream);
remicres's avatar
remicres committed
874

875
  TSegmenter seg;
remicres's avatar
remicres committed
876 877
  for(auto& node : graph.m_Nodes)
    {
878
    seg.WriteNode(node, nodeStream);
remicres's avatar
remicres committed
879 880 881 882 883 884 885

    // Write edges
    fwrite(&(node->m_Id), sizeof(node->m_Id), 1, edgeStream);
    std::size_t edgeSize = node->m_Edges.size();
    fwrite(&(edgeSize), sizeof(edgeSize), 1, edgeStream);
    for(auto& edg : node->m_Edges)
      {
886
      seg.WriteEdge(edg, edgeStream);
remicres's avatar
remicres committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
      }
    }

  fclose(nodeStream);
  fclose(edgeStream);
}

template<class TSegmenter>
void RemoveUnstableSegments(typename TSegmenter::GraphType& graph,
    ProcessingTile& tile,
    const unsigned int imageWidth)
{

  unsigned int rowPixel, colPixel;
  bool stable;

  for(auto& node : graph.m_Nodes)
    {
    if(node->m_Bbox.m_UX >= tile.columns[0] &&
        node->m_Bbox.m_UY >= tile.rows[0] &&
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 <= tile.columns[1] &&
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 <= tile.rows[1])
      continue;
    else if(node->m_Bbox.m_UX > tile.columns[1] ||
        node->m_Bbox.m_UY > tile.rows[1] ||
        node->m_Bbox.m_UX + node->m_Bbox.m_W - 1 < tile.columns[0] ||
        node->m_Bbox.m_UY + node->m_Bbox.m_H - 1 < tile.rows[0])
      {
      node->m_Expired = true;
      RemoveEdgeToUnstableNode<TSegmenter>(node);
      }
    else
      {
      lp::CellLists borderpixels;
      lp::ContourOperations::GenerateBorderCells(borderpixels, node->m_Contour, node->m_Id, imageWidth);
      stable = false;

      for(auto& pix : borderpixels)
        {
        rowPixel = pix / imageWidth;
        colPixel = pix % imageWidth;

        if(rowPixel >= tile.rows[0] &&
            rowPixel <= tile.rows[1] &&
            colPixel >= tile.columns[0] &&
            colPixel <= tile.columns[1])
          {
          stable = true;
          break;
          }
        }

      if(!stable)
        {
        node->m_Expired = true;
        RemoveEdgeToUnstableNode<TSegmenter>(node);
        }
      }
    }

  lsrm::GraphOperations<TSegmenter>::RemoveExpiredNodes(graph);
}

template<class TSegmenter>
void RemoveEdgeToUnstableNode(typename TSegmenter::NodePointerType nodePtr)
{
  for(auto& edg : nodePtr->m_Edges)
    {
    auto nodeNeighbor = edg.GetRegion();
    auto EdgeToNode = lsrm::GraphOperations<TSegmenter>::FindEdge(nodeNeighbor, nodePtr);
    assert(EdgeToNode != nodeNeighbor->m_Edges.end());
    nodeNeighbor->m_Edges.erase(EdgeToNode);
    }
}

template<class TSegmenter>
void RescaleGraph(typename TSegmenter::GraphType& graph,
    ProcessingTile& tile,
    const unsigned int rowTile,
    const unsigned int colTile,
    const unsigned int tileWidth,
    const unsigned int tileHeight,
    const unsigned int imageWidth)
{
  unsigned int rowNodeTile, colNodeTile;
  unsigned int rowNodeImg, colNodeImg;

  for(auto& node : graph.m_Nodes)
    {
976
    // Start pixel index of the node (in the tile)
977 978
    rowNodeTile = node->m_Id / tile.region.GetSize()[0];
    colNodeTile = node->m_Id % tile.region.GetSize()[0];
979 980

    // Start pixel index of the node (in the image)
981 982
    rowNodeImg = rowTile * tileHeight + rowNodeTile - tile.margin[0];
    colNodeImg = colTile * tileWidth + colNodeTile - tile.margin[3];
remicres's avatar
remicres committed
983 984 985
    node->m_Id = rowNodeImg * imageWidth + colNodeImg;

    // Change also its bounding box
986 987
    node->m_Bbox.m_UX = colTile * tileWidth + node->m_Bbox.m_UX - tile.margin[3];
    node->m_Bbox.m_UY = rowTile * tileHeight + node->m_Bbox.m_UY - tile.margin[0];
remicres's avatar
remicres committed
988
    }
989

remicres's avatar
remicres committed
990 991
}
}