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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 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 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
|
/******************************************************************************
*
* Project: GDAL
* Purpose: Raster to Polygon Converter
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2008, Frank Warmerdam
* Copyright (c) 2009-2011, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "gdal_alg.h"
#include <cstring>
#include <algorithm>
#include <set>
#include <vector>
#include <utility>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_vsi.h"
#include "gdal.h"
#include "gdal_alg_priv.h"
#define MY_MAX_INT 2147483647
/*
* General Plan
*
* 1) make a pass with the polygon enumerator to build up the
* polygon map array. Also accumulate polygon size information.
*
* 2) Identify the polygons that need to be merged.
*
* 3) Make a pass with the polygon enumerator. For each "to be merged"
* polygon keep track of its largest neighbour.
*
* 4) Fix up remappings that would go to polygons smaller than the sieve
* size. Ensure these in term map to the largest neighbour of the
* "to be sieved" polygons.
*
* 5) Make another pass with the polygon enumerator. This time we remap
* the actual pixel values of all polygons to be merged.
*/
/************************************************************************/
/* GPMaskImageData() */
/* */
/* Mask out image pixels to a special nodata value if the mask */
/* band is zero. */
/************************************************************************/
static CPLErr GPMaskImageData(GDALRasterBandH hMaskBand, GByte *pabyMaskLine,
int iY, int nXSize, std::int64_t *panImageLine)
{
const CPLErr eErr = GDALRasterIO(hMaskBand, GF_Read, 0, iY, nXSize, 1,
pabyMaskLine, nXSize, 1, GDT_Byte, 0, 0);
if (eErr == CE_None)
{
for (int i = 0; i < nXSize; i++)
{
if (pabyMaskLine[i] == 0)
panImageLine[i] = GP_NODATA_MARKER;
}
}
return eErr;
}
// TODO: What is "eaches" supposed to be?
/************************************************************************/
/* CompareNeighbour() */
/* */
/* Compare two neighbouring polygons, and update eaches */
/* "biggest neighbour" if the other is larger than its current */
/* largest neighbour. */
/* */
/* Note that this should end up with each polygon knowing the */
/* id of its largest neighbour. No attempt is made to */
/* restrict things to small polygons that we will be merging, */
/* nor to exclude assigning "biggest neighbours" that are still */
/* smaller than our sieve threshold. */
/************************************************************************/
static inline void CompareNeighbour(int nPolyId1, int nPolyId2,
int *panPolyIdMap,
std::int64_t * /* panPolyValue */,
const std::vector<int> &anPolySizes,
std::vector<int> &anBigNeighbour)
{
// Nodata polygon do not need neighbours, and cannot be neighbours
// to valid polygons.
if (nPolyId1 < 0 || nPolyId2 < 0)
return;
// Make sure we are working with the final merged polygon ids.
nPolyId1 = panPolyIdMap[nPolyId1];
nPolyId2 = panPolyIdMap[nPolyId2];
if (nPolyId1 == nPolyId2)
return;
// Nodata polygon do not need neighbours, and cannot be neighbours
// to valid polygons.
// Should no longer happen with r28826 optimization.
// if( panPolyValue[nPolyId1] == GP_NODATA_MARKER
// || panPolyValue[nPolyId2] == GP_NODATA_MARKER )
// return;
if (anBigNeighbour[nPolyId1] == -1 ||
anPolySizes[anBigNeighbour[nPolyId1]] < anPolySizes[nPolyId2])
anBigNeighbour[nPolyId1] = nPolyId2;
if (anBigNeighbour[nPolyId2] == -1 ||
anPolySizes[anBigNeighbour[nPolyId2]] < anPolySizes[nPolyId1])
anBigNeighbour[nPolyId2] = nPolyId1;
}
/************************************************************************/
/* GDALSieveFilter() */
/************************************************************************/
/**
* Removes small raster polygons.
*
* The function removes raster polygons smaller than a provided
* threshold size (in pixels) and replaces them with the pixel value
* of the largest neighbour polygon.
*
* Polygon are determined (per GDALRasterPolygonEnumerator) as regions of
* the raster where the pixels all have the same value, and that are contiguous
* (connected).
*
* Pixels determined to be "nodata" per hMaskBand will not be treated as part
* of a polygon regardless of their pixel values. Nodata areas will never be
* changed nor affect polygon sizes.
*
* Polygons smaller than the threshold with no neighbours that are as large
* as the threshold will not be altered. Polygons surrounded by nodata areas
* will therefore not be altered.
*
* The algorithm makes three passes over the input file to enumerate the
* polygons and collect limited information about them. Memory use is
* proportional to the number of polygons (roughly 24 bytes per polygon), but
* is not directly related to the size of the raster. So very large raster
* files can be processed effectively if there aren't too many polygons. But
* extremely noisy rasters with many one pixel polygons will end up being
* expensive (in memory) to process.
*
* @param hSrcBand the source raster band to be processed.
* @param hMaskBand an optional mask band. All pixels in the mask band with a
* value other than zero will be considered suitable for inclusion in polygons.
* @param hDstBand the output raster band. It may be the same as hSrcBand
* to update the source in place.
* @param nSizeThreshold raster polygons with sizes smaller than this will
* be merged into their largest neighbour.
* @param nConnectedness either 4 indicating that diagonal pixels are not
* considered directly adjacent for polygon membership purposes or 8
* indicating they are.
* @param papszOptions algorithm options in name=value list form. None
* currently supported.
* @param pfnProgress callback for reporting algorithm progress matching the
* GDALProgressFunc() semantics. May be NULL.
* @param pProgressArg callback argument passed to pfnProgress.
*
* @return CE_None on success or CE_Failure if an error occurs.
*/
CPLErr CPL_STDCALL GDALSieveFilter(GDALRasterBandH hSrcBand,
GDALRasterBandH hMaskBand,
GDALRasterBandH hDstBand, int nSizeThreshold,
int nConnectedness,
CPL_UNUSED char **papszOptions,
GDALProgressFunc pfnProgress,
void *pProgressArg)
{
VALIDATE_POINTER1(hSrcBand, "GDALSieveFilter", CE_Failure);
VALIDATE_POINTER1(hDstBand, "GDALSieveFilter", CE_Failure);
if (pfnProgress == nullptr)
pfnProgress = GDALDummyProgress;
/* -------------------------------------------------------------------- */
/* Allocate working buffers. */
/* -------------------------------------------------------------------- */
int nXSize = GDALGetRasterBandXSize(hSrcBand);
int nYSize = GDALGetRasterBandYSize(hSrcBand);
auto panLastLineValKeeper = std::unique_ptr<std::int64_t, VSIFreeReleaser>(
static_cast<std::int64_t *>(
VSI_MALLOC2_VERBOSE(sizeof(std::int64_t), nXSize)));
auto panThisLineValKeeper = std::unique_ptr<std::int64_t, VSIFreeReleaser>(
static_cast<std::int64_t *>(
VSI_MALLOC2_VERBOSE(sizeof(std::int64_t), nXSize)));
auto panLastLineIdKeeper = std::unique_ptr<GInt32, VSIFreeReleaser>(
static_cast<GInt32 *>(VSI_MALLOC2_VERBOSE(sizeof(GInt32), nXSize)));
auto panThisLineIdKeeper = std::unique_ptr<GInt32, VSIFreeReleaser>(
static_cast<GInt32 *>(VSI_MALLOC2_VERBOSE(sizeof(GInt32), nXSize)));
auto panThisLineWriteValKeeper =
std::unique_ptr<std::int64_t, VSIFreeReleaser>(
static_cast<std::int64_t *>(
VSI_MALLOC2_VERBOSE(sizeof(std::int64_t), nXSize)));
auto pabyMaskLineKeeper = std::unique_ptr<GByte, VSIFreeReleaser>(
hMaskBand != nullptr ? static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize))
: nullptr);
auto panLastLineVal = panLastLineValKeeper.get();
auto panThisLineVal = panThisLineValKeeper.get();
auto panLastLineId = panLastLineIdKeeper.get();
auto panThisLineId = panThisLineIdKeeper.get();
auto panThisLineWriteVal = panThisLineWriteValKeeper.get();
auto pabyMaskLine = pabyMaskLineKeeper.get();
if (panLastLineVal == nullptr || panThisLineVal == nullptr ||
panLastLineId == nullptr || panThisLineId == nullptr ||
panThisLineWriteVal == nullptr ||
(hMaskBand != nullptr && pabyMaskLine == nullptr))
{
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* The first pass over the raster is only used to build up the */
/* polygon id map so we will know in advance what polygons are */
/* what on the second pass. */
/* -------------------------------------------------------------------- */
GDALRasterPolygonEnumerator oFirstEnum(nConnectedness);
std::vector<int> anPolySizes;
CPLErr eErr = CE_None;
for (int iY = 0; eErr == CE_None && iY < nYSize; iY++)
{
eErr = GDALRasterIO(hSrcBand, GF_Read, 0, iY, nXSize, 1, panThisLineVal,
nXSize, 1, GDT_Int64, 0, 0);
if (eErr == CE_None && hMaskBand != nullptr)
eErr = GPMaskImageData(hMaskBand, pabyMaskLine, iY, nXSize,
panThisLineVal);
if (eErr != CE_None)
break;
if (iY == 0)
eErr = oFirstEnum.ProcessLine(nullptr, panThisLineVal, nullptr,
panThisLineId, nXSize)
? CE_None
: CE_Failure;
else
eErr = oFirstEnum.ProcessLine(panLastLineVal, panThisLineVal,
panLastLineId, panThisLineId, nXSize)
? CE_None
: CE_Failure;
if (eErr != CE_None)
break;
/* --------------------------------------------------------------------
*/
/* Accumulate polygon sizes. */
/* --------------------------------------------------------------------
*/
if (oFirstEnum.nNextPolygonId > static_cast<int>(anPolySizes.size()))
anPolySizes.resize(oFirstEnum.nNextPolygonId);
for (int iX = 0; iX < nXSize; iX++)
{
const int iPoly = panThisLineId[iX];
if (iPoly >= 0 && anPolySizes[iPoly] < MY_MAX_INT)
anPolySizes[iPoly] += 1;
}
/* --------------------------------------------------------------------
*/
/* swap this/last lines. */
/* --------------------------------------------------------------------
*/
std::swap(panLastLineVal, panThisLineVal);
std::swap(panLastLineId, panThisLineId);
/* --------------------------------------------------------------------
*/
/* Report progress, and support interrupts. */
/* --------------------------------------------------------------------
*/
if (!pfnProgress(0.25 * ((iY + 1) / static_cast<double>(nYSize)), "",
pProgressArg))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
eErr = CE_Failure;
}
}
/* -------------------------------------------------------------------- */
/* Make a pass through the maps, ensuring every polygon id */
/* points to the final id it should use, not an intermediate */
/* value. */
/* -------------------------------------------------------------------- */
if (eErr == CE_None)
oFirstEnum.CompleteMerges();
/* -------------------------------------------------------------------- */
/* Check if there are polygons */
/* -------------------------------------------------------------------- */
if (!oFirstEnum.panPolyIdMap || !oFirstEnum.panPolyValue)
{
// Can happen if all pixels are masked
if (hSrcBand == hDstBand)
{
pfnProgress(1.0, "", pProgressArg);
return CE_None;
}
else
{
return GDALRasterBandCopyWholeRaster(hSrcBand, hDstBand, nullptr,
pfnProgress, pProgressArg);
}
}
/* -------------------------------------------------------------------- */
/* Push the sizes of merged polygon fragments into the */
/* merged polygon id's count. */
/* -------------------------------------------------------------------- */
for (int iPoly = 0; iPoly < oFirstEnum.nNextPolygonId; iPoly++)
{
if (oFirstEnum.panPolyIdMap[iPoly] != iPoly)
{
GIntBig nSize = anPolySizes[oFirstEnum.panPolyIdMap[iPoly]];
nSize += anPolySizes[iPoly];
if (nSize > MY_MAX_INT)
nSize = MY_MAX_INT;
anPolySizes[oFirstEnum.panPolyIdMap[iPoly]] =
static_cast<int>(nSize);
anPolySizes[iPoly] = 0;
}
}
/* -------------------------------------------------------------------- */
/* We will use a new enumerator for the second pass primarily */
/* so we can preserve the first pass map. */
/* -------------------------------------------------------------------- */
GDALRasterPolygonEnumerator oSecondEnum(nConnectedness);
std::vector<int> anBigNeighbour;
try
{
anBigNeighbour.resize(anPolySizes.size(), -1);
}
catch (const std::exception &)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s: Out of memory",
__FUNCTION__);
return CE_Failure;
}
/* ==================================================================== */
/* Second pass ... identify the largest neighbour for each */
/* polygon. */
/* ==================================================================== */
for (int iY = 0; eErr == CE_None && iY < nYSize; iY++)
{
/* --------------------------------------------------------------------
*/
/* Read the image data. */
/* --------------------------------------------------------------------
*/
eErr = GDALRasterIO(hSrcBand, GF_Read, 0, iY, nXSize, 1, panThisLineVal,
nXSize, 1, GDT_Int64, 0, 0);
if (eErr == CE_None && hMaskBand != nullptr)
eErr = GPMaskImageData(hMaskBand, pabyMaskLine, iY, nXSize,
panThisLineVal);
if (eErr != CE_None)
continue;
/* --------------------------------------------------------------------
*/
/* Determine what polygon the various pixels belong to (redoing */
/* the same thing done in the first pass above). */
/* --------------------------------------------------------------------
*/
if (iY == 0)
eErr = oSecondEnum.ProcessLine(nullptr, panThisLineVal, nullptr,
panThisLineId, nXSize)
? CE_None
: CE_Failure;
else
eErr = oSecondEnum.ProcessLine(panLastLineVal, panThisLineVal,
panLastLineId, panThisLineId, nXSize)
? CE_None
: CE_Failure;
if (eErr != CE_None)
continue;
/* --------------------------------------------------------------------
*/
/* Check our neighbours, and update our biggest neighbour map */
/* as appropriate. */
/* --------------------------------------------------------------------
*/
for (int iX = 0; iX < nXSize; iX++)
{
if (iY > 0)
{
CompareNeighbour(panThisLineId[iX], panLastLineId[iX],
oFirstEnum.panPolyIdMap,
oFirstEnum.panPolyValue, anPolySizes,
anBigNeighbour);
if (iX > 0 && nConnectedness == 8)
CompareNeighbour(panThisLineId[iX], panLastLineId[iX - 1],
oFirstEnum.panPolyIdMap,
oFirstEnum.panPolyValue, anPolySizes,
anBigNeighbour);
if (iX < nXSize - 1 && nConnectedness == 8)
CompareNeighbour(panThisLineId[iX], panLastLineId[iX + 1],
oFirstEnum.panPolyIdMap,
oFirstEnum.panPolyValue, anPolySizes,
anBigNeighbour);
}
if (iX > 0)
CompareNeighbour(panThisLineId[iX], panThisLineId[iX - 1],
oFirstEnum.panPolyIdMap,
oFirstEnum.panPolyValue, anPolySizes,
anBigNeighbour);
// We don't need to compare to next pixel or next line
// since they will be compared to us.
}
/* --------------------------------------------------------------------
*/
/* Swap pixel value, and polygon id lines to be ready for the */
/* next line. */
/* --------------------------------------------------------------------
*/
std::swap(panLastLineVal, panThisLineVal);
std::swap(panLastLineId, panThisLineId);
/* --------------------------------------------------------------------
*/
/* Report progress, and support interrupts. */
/* --------------------------------------------------------------------
*/
if (!pfnProgress(0.25 + 0.25 * ((iY + 1) / static_cast<double>(nYSize)),
"", pProgressArg))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
eErr = CE_Failure;
}
}
/* -------------------------------------------------------------------- */
/* If our biggest neighbour is still smaller than the */
/* threshold, then try tracking to that polygons biggest */
/* neighbour, and so forth. */
/* -------------------------------------------------------------------- */
int nFailedMerges = 0;
int nIsolatedSmall = 0;
int nSieveTargets = 0;
for (int iPoly = 0; iPoly < static_cast<int>(anPolySizes.size()); iPoly++)
{
if (oFirstEnum.panPolyIdMap[iPoly] != iPoly)
continue;
// Ignore nodata polygons.
if (oFirstEnum.panPolyValue[iPoly] == GP_NODATA_MARKER)
continue;
// Don't try to merge polygons larger than the threshold.
if (anPolySizes[iPoly] >= nSizeThreshold)
{
anBigNeighbour[iPoly] = -1;
continue;
}
nSieveTargets++;
// if we have no neighbours but we are small, what shall we do?
if (anBigNeighbour[iPoly] == -1)
{
nIsolatedSmall++;
continue;
}
std::set<int> oSetVisitedPoly;
oSetVisitedPoly.insert(iPoly);
// Walk through our neighbours until we find a polygon large enough.
int iFinalId = iPoly;
bool bFoundBigEnoughPoly = false;
while (true)
{
iFinalId = anBigNeighbour[iFinalId];
if (iFinalId < 0)
{
break;
}
// If the biggest neighbour is larger than the threshold
// then we are golden.
if (anPolySizes[iFinalId] >= nSizeThreshold)
{
bFoundBigEnoughPoly = true;
break;
}
// Check that we don't cycle on an already visited polygon.
if (oSetVisitedPoly.find(iFinalId) != oSetVisitedPoly.end())
break;
oSetVisitedPoly.insert(iFinalId);
}
if (!bFoundBigEnoughPoly)
{
nFailedMerges++;
anBigNeighbour[iPoly] = -1;
continue;
}
// Map the whole intermediate chain to it.
int iPolyCur = iPoly;
while (anBigNeighbour[iPolyCur] != iFinalId)
{
int iNextPoly = anBigNeighbour[iPolyCur];
anBigNeighbour[iPolyCur] = iFinalId;
iPolyCur = iNextPoly;
}
}
CPLDebug("GDALSieveFilter",
"Small Polygons: %d, Isolated: %d, Unmergable: %d", nSieveTargets,
nIsolatedSmall, nFailedMerges);
/* ==================================================================== */
/* Make a third pass over the image, actually applying the */
/* merges. We reuse the second enumerator but preserve the */
/* "final maps" from the first. */
/* ==================================================================== */
oSecondEnum.Clear();
for (int iY = 0; eErr == CE_None && iY < nYSize; iY++)
{
/* --------------------------------------------------------------------
*/
/* Read the image data. */
/* --------------------------------------------------------------------
*/
eErr = GDALRasterIO(hSrcBand, GF_Read, 0, iY, nXSize, 1, panThisLineVal,
nXSize, 1, GDT_Int64, 0, 0);
memcpy(panThisLineWriteVal, panThisLineVal,
sizeof(panThisLineVal[0]) * nXSize);
if (eErr == CE_None && hMaskBand != nullptr)
eErr = GPMaskImageData(hMaskBand, pabyMaskLine, iY, nXSize,
panThisLineVal);
if (eErr != CE_None)
continue;
/* --------------------------------------------------------------------
*/
/* Determine what polygon the various pixels belong to (redoing */
/* the same thing done in the first pass above). */
/* --------------------------------------------------------------------
*/
if (iY == 0)
oSecondEnum.ProcessLine(nullptr, panThisLineVal, nullptr,
panThisLineId, nXSize);
else
oSecondEnum.ProcessLine(panLastLineVal, panThisLineVal,
panLastLineId, panThisLineId, nXSize);
/* --------------------------------------------------------------------
*/
/* Reprocess the actual pixel values according to the polygon */
/* merging, and write out this line of image data. */
/* --------------------------------------------------------------------
*/
for (int iX = 0; iX < nXSize; iX++)
{
int iThisPoly = panThisLineId[iX];
if (iThisPoly >= 0)
{
iThisPoly = oFirstEnum.panPolyIdMap[iThisPoly];
if (anBigNeighbour[iThisPoly] != -1)
{
panThisLineWriteVal[iX] =
oFirstEnum.panPolyValue[anBigNeighbour[iThisPoly]];
}
}
}
/* --------------------------------------------------------------------
*/
/* Write the update data out. */
/* --------------------------------------------------------------------
*/
eErr = GDALRasterIO(hDstBand, GF_Write, 0, iY, nXSize, 1,
panThisLineWriteVal, nXSize, 1, GDT_Int64, 0, 0);
/* --------------------------------------------------------------------
*/
/* Swap pixel value, and polygon id lines to be ready for the */
/* next line. */
/* --------------------------------------------------------------------
*/
std::swap(panLastLineVal, panThisLineVal);
std::swap(panLastLineId, panThisLineId);
/* --------------------------------------------------------------------
*/
/* Report progress, and support interrupts. */
/* --------------------------------------------------------------------
*/
if (eErr == CE_None &&
!pfnProgress(0.5 + 0.5 * ((iY + 1) / static_cast<double>(nYSize)),
"", pProgressArg))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
eErr = CE_Failure;
}
}
return eErr;
}
|