forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolygonize.cpp
1064 lines (931 loc) · 41.2 KB
/
polygonize.cpp
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Project: GDAL
* Purpose: Raster to Polygon Converter
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 2008, Frank Warmerdam
* Copyright (c) 2009-2020, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "gdal_alg.h"
#include <stddef.h>
#include <stdio.h>
#include <cstdlib>
#include <string.h>
#include <algorithm>
#include <limits>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "gdal_alg_priv.h"
#include "gdal.h"
#include "ogr_api.h"
#include "ogr_core.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
CPL_CVSID("$Id$")
/************************************************************************/
/* ==================================================================== */
/* RPolygon */
/* */
/* This is a helper class to hold polygons while they are being */
/* formed in memory, and to provide services to coalesce a much */
/* of edge sections into complete rings. */
/* ==================================================================== */
/************************************************************************/
class RPolygon
{
public:
double dfPolyValue = 0.0;
int nLastLineUpdated = -1;
struct XY
{
int x;
int y;
bool operator<(const XY &other) const
{
if (x < other.x)
return true;
if (x > other.x)
return false;
return y < other.y;
}
bool operator==(const XY &other) const
{
return x == other.x && y == other.y;
}
};
typedef int StringId;
typedef std::map<XY, std::pair<StringId, StringId>> MapExtremity;
std::map<StringId, std::vector<XY>> oMapStrings{};
MapExtremity oMapStartStrings{};
MapExtremity oMapEndStrings{};
StringId iNextStringId = 0;
static StringId findExtremityNot(const MapExtremity &oMap, const XY &xy,
StringId excludedId);
static void removeExtremity(MapExtremity &oMap, const XY &xy, StringId id);
static void insertExtremity(MapExtremity &oMap, const XY &xy, StringId id);
explicit RPolygon(double dfValue) : dfPolyValue(dfValue)
{
}
void AddSegment(int x1, int y1, int x2, int y2, int direction);
void Dump() const;
void Coalesce();
void Merge(StringId iBaseString, StringId iSrcString, int iDirection);
};
/************************************************************************/
/* Dump() */
/************************************************************************/
void RPolygon::Dump() const
{
/*ok*/ printf("RPolygon: Value=%g, LastLineUpdated=%d\n", dfPolyValue,
nLastLineUpdated);
for (const auto &oStringIter : oMapStrings)
{
/*ok*/ printf(" String " CPL_FRMT_GIB ":\n",
static_cast<GIntBig>(oStringIter.first));
for (const auto &xy : oStringIter.second)
{
/*ok*/ printf(" (%d,%d)\n", xy.x, xy.y);
}
}
}
/************************************************************************/
/* findExtremityNot() */
/************************************************************************/
RPolygon::StringId RPolygon::findExtremityNot(const MapExtremity &oMap,
const XY &xy, StringId excludedId)
{
auto oIter = oMap.find(xy);
if (oIter == oMap.end())
return -1;
if (oIter->second.first != excludedId)
return oIter->second.first;
if (oIter->second.second != excludedId)
return oIter->second.second;
return -1;
}
/************************************************************************/
/* Coalesce() */
/************************************************************************/
void RPolygon::Coalesce()
{
/* -------------------------------------------------------------------- */
/* Iterate over loops starting from the first, trying to merge */
/* other segments into them. */
/* -------------------------------------------------------------------- */
for (auto &oStringIter : oMapStrings)
{
const auto thisId = oStringIter.first;
auto &oString = oStringIter.second;
/* --------------------------------------------------------------------
*/
/* Keep trying to merge others strings into our target "base" */
/* string while there are matches. */
/* --------------------------------------------------------------------
*/
while (true)
{
auto nOtherId =
findExtremityNot(oMapStartStrings, oString.back(), thisId);
if (nOtherId != -1)
{
Merge(thisId, nOtherId, 1);
continue;
}
else
{
nOtherId =
findExtremityNot(oMapEndStrings, oString.back(), thisId);
if (nOtherId != -1)
{
Merge(thisId, nOtherId, -1);
continue;
}
}
break;
}
// At this point our loop *should* be closed!
CPLAssert(oString.front() == oString.back());
}
}
/************************************************************************/
/* removeExtremity() */
/************************************************************************/
void RPolygon::removeExtremity(MapExtremity &oMap, const XY &xy, StringId id)
{
auto oIter = oMap.find(xy);
CPLAssert(oIter != oMap.end());
if (oIter->second.first == id)
{
oIter->second.first = oIter->second.second;
oIter->second.second = -1;
if (oIter->second.first < 0)
oMap.erase(oIter);
}
else if (oIter->second.second == id)
{
oIter->second.second = -1;
CPLAssert(oIter->second.first >= 0);
}
else
{
CPLAssert(false);
}
}
/************************************************************************/
/* insertExtremity() */
/************************************************************************/
void RPolygon::insertExtremity(MapExtremity &oMap, const XY &xy, StringId id)
{
auto oIter = oMap.find(xy);
if (oIter != oMap.end())
{
CPLAssert(oIter->second.second == -1);
oIter->second.second = id;
}
else
{
oMap[xy] = std::pair<StringId, StringId>(id, -1);
}
}
/************************************************************************/
/* Merge() */
/************************************************************************/
void RPolygon::Merge(StringId iBaseString, StringId iSrcString, int iDirection)
{
auto &anBase = oMapStrings.find(iBaseString)->second;
auto anStringIter = oMapStrings.find(iSrcString);
auto &anString = anStringIter->second;
int iStart = 1;
int iEnd = -1;
if (iDirection == 1)
{
iEnd = static_cast<int>(anString.size());
}
else
{
iStart = static_cast<int>(anString.size()) - 2;
}
removeExtremity(oMapEndStrings, anBase.back(), iBaseString);
anBase.reserve(anBase.size() + anString.size() - 1);
for (int i = iStart; i != iEnd; i += iDirection)
{
anBase.push_back(anString[i]);
}
removeExtremity(oMapStartStrings, anString.front(), iSrcString);
removeExtremity(oMapEndStrings, anString.back(), iSrcString);
oMapStrings.erase(anStringIter);
insertExtremity(oMapEndStrings, anBase.back(), iBaseString);
}
/************************************************************************/
/* AddSegment() */
/************************************************************************/
void RPolygon::AddSegment(int x1, int y1, int x2, int y2, int direction)
{
nLastLineUpdated = std::max(y1, y2);
/* -------------------------------------------------------------------- */
/* Is there an existing string ending with this? */
/* -------------------------------------------------------------------- */
XY xy1 = {x1, y1};
XY xy2 = {x2, y2};
StringId iExistingString = findExtremityNot(oMapEndStrings, xy1, -1);
if (iExistingString >= 0)
{
StringId iExistingString2 =
findExtremityNot(oMapEndStrings, xy1, iExistingString);
if (iExistingString2 >= 0)
{
// If there are two strings that ending with this segment
// choose the string which is in the same pixel with this segment
auto &anString2 = oMapStrings[iExistingString2];
const size_t nSSize2 = anString2.size();
if (x1 == x2)
{
// vertical segment input, choose the horizontal string
if (anString2[nSSize2 - 2].y == anString2[nSSize2 - 1].y)
{
iExistingString = iExistingString2;
}
}
else
{
// horizontal segment input, choose the vertical string
if (anString2[nSSize2 - 2].x == anString2[nSSize2 - 1].x)
{
iExistingString = iExistingString2;
}
}
}
auto &anString = oMapStrings[iExistingString];
const size_t nSSize = anString.size();
// We are going to add a segment, but should we just extend
// an existing segment already going in the right direction?
const int nLastLen =
std::max(std::abs(anString[nSSize - 2].x - anString[nSSize - 1].x),
std::abs(anString[nSSize - 2].y - anString[nSSize - 1].y));
removeExtremity(oMapEndStrings, anString.back(), iExistingString);
if ((anString[nSSize - 2].x - anString[nSSize - 1].x ==
(anString[nSSize - 1].x - xy2.x) * nLastLen) &&
(anString[nSSize - 2].y - anString[nSSize - 1].y ==
(anString[nSSize - 1].y - xy2.y) * nLastLen))
{
anString[nSSize - 1] = xy2;
}
else
{
anString.push_back(xy2);
}
insertExtremity(oMapEndStrings, anString.back(), iExistingString);
}
else
{
oMapStrings[iNextStringId] = std::vector<XY>{xy1, xy2};
insertExtremity(oMapStartStrings, xy1, iNextStringId);
insertExtremity(oMapEndStrings, xy2, iNextStringId);
iExistingString = iNextStringId;
iNextStringId++;
}
// merge rings if possible
if (direction == 1)
{
StringId iExistingString2 =
findExtremityNot(oMapEndStrings, xy2, iExistingString);
if (iExistingString2 >= 0)
{
this->Merge(iExistingString, iExistingString2, -1);
}
}
}
/************************************************************************/
/* ==================================================================== */
/* End of RPolygon */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* AddEdges() */
/* */
/* Examine one pixel and compare to its neighbour above */
/* (previous) and right. If they are different polygon ids */
/* then add the pixel edge to this polygon and the one on the */
/* other side of the edge. */
/************************************************************************/
template <class DataType>
static void AddEdges(GInt32 *panThisLineId, GInt32 *panLastLineId,
GInt32 *panPolyIdMap, DataType *panPolyValue,
RPolygon **papoPoly, int iX, int iY)
{
// TODO(schwehr): Simplify these three vars.
int nThisId = panThisLineId[iX];
if (nThisId != -1)
nThisId = panPolyIdMap[nThisId];
int nRightId = panThisLineId[iX + 1];
if (nRightId != -1)
nRightId = panPolyIdMap[nRightId];
int nPreviousId = panLastLineId[iX];
if (nPreviousId != -1)
nPreviousId = panPolyIdMap[nPreviousId];
const int iXReal = iX - 1;
if (nThisId != nPreviousId)
{
if (nThisId != -1)
{
if (papoPoly[nThisId] == nullptr)
// FIXME loss of precision for [U]Int64
papoPoly[nThisId] =
new RPolygon(static_cast<double>(panPolyValue[nThisId]));
papoPoly[nThisId]->AddSegment(iXReal, iY, iXReal + 1, iY, 1);
}
if (nPreviousId != -1)
{
if (papoPoly[nPreviousId] == nullptr)
// FIXME loss of precision for [U]Int64
papoPoly[nPreviousId] = new RPolygon(
static_cast<double>(panPolyValue[nPreviousId]));
papoPoly[nPreviousId]->AddSegment(iXReal, iY, iXReal + 1, iY, 0);
}
}
if (nThisId != nRightId)
{
if (nThisId != -1)
{
if (papoPoly[nThisId] == nullptr)
// FIXME loss of precision for [U]Int64
papoPoly[nThisId] =
new RPolygon(static_cast<double>(panPolyValue[nThisId]));
papoPoly[nThisId]->AddSegment(iXReal + 1, iY, iXReal + 1, iY + 1,
1);
}
if (nRightId != -1)
{
if (papoPoly[nRightId] == nullptr)
// FIXME loss of precision for [U]Int64
papoPoly[nRightId] =
new RPolygon(static_cast<double>(panPolyValue[nRightId]));
papoPoly[nRightId]->AddSegment(iXReal + 1, iY, iXReal + 1, iY + 1,
0);
}
}
}
/************************************************************************/
/* EmitPolygonToLayer() */
/************************************************************************/
static CPLErr EmitPolygonToLayer(OGRLayerH hOutLayer, int iPixValField,
RPolygon *poRPoly, double *padfGeoTransform)
{
/* -------------------------------------------------------------------- */
/* Turn bits of lines into coherent rings. */
/* -------------------------------------------------------------------- */
poRPoly->Coalesce();
/* -------------------------------------------------------------------- */
/* Create the polygon geometry. */
/* -------------------------------------------------------------------- */
OGRGeometryH hPolygon = OGR_G_CreateGeometry(wkbPolygon);
for (const auto &oIter : poRPoly->oMapStrings)
{
const auto &anString = oIter.second;
OGRGeometryH hRing = OGR_G_CreateGeometry(wkbLinearRing);
// We go last to first to ensure the linestring is allocated to
// the proper size on the first try.
for (int iVert = static_cast<int>(anString.size()) - 1; iVert >= 0;
iVert--)
{
const int nPixelX = anString[iVert].x;
const int nPixelY = anString[iVert].y;
const double dfX = padfGeoTransform[0] +
nPixelX * padfGeoTransform[1] +
nPixelY * padfGeoTransform[2];
const double dfY = padfGeoTransform[3] +
nPixelX * padfGeoTransform[4] +
nPixelY * padfGeoTransform[5];
OGR_G_SetPoint_2D(hRing, iVert, dfX, dfY);
}
OGR_G_AddGeometryDirectly(hPolygon, hRing);
}
/* -------------------------------------------------------------------- */
/* Create the feature object. */
/* -------------------------------------------------------------------- */
OGRFeatureH hFeat = OGR_F_Create(OGR_L_GetLayerDefn(hOutLayer));
OGR_F_SetGeometryDirectly(hFeat, hPolygon);
if (iPixValField >= 0)
OGR_F_SetFieldDouble(hFeat, iPixValField, poRPoly->dfPolyValue);
/* -------------------------------------------------------------------- */
/* Write the to the layer. */
/* -------------------------------------------------------------------- */
CPLErr eErr = CE_None;
if (OGR_L_CreateFeature(hOutLayer, hFeat) != OGRERR_NONE)
eErr = CE_Failure;
OGR_F_Destroy(hFeat);
return eErr;
}
/************************************************************************/
/* GPMaskImageData() */
/* */
/* Mask out image pixels to a special nodata value if the mask */
/* band is zero. */
/************************************************************************/
template <class DataType>
static CPLErr GPMaskImageData(GDALRasterBandH hMaskBand, GByte *pabyMaskLine,
int iY, int nXSize, DataType *panImageLine)
{
const CPLErr eErr = GDALRasterIO(hMaskBand, GF_Read, 0, iY, nXSize, 1,
pabyMaskLine, nXSize, 1, GDT_Byte, 0, 0);
if (eErr != CE_None)
return eErr;
for (int i = 0; i < nXSize; i++)
{
if (pabyMaskLine[i] == 0)
panImageLine[i] = GP_NODATA_MARKER;
}
return CE_None;
}
/************************************************************************/
/* GDALPolygonizeT() */
/************************************************************************/
template <class DataType, class EqualityTest>
static CPLErr GDALPolygonizeT(GDALRasterBandH hSrcBand,
GDALRasterBandH hMaskBand, OGRLayerH hOutLayer,
int iPixValField, char **papszOptions,
GDALProgressFunc pfnProgress, void *pProgressArg,
GDALDataType eDT)
{
VALIDATE_POINTER1(hSrcBand, "GDALPolygonize", CE_Failure);
VALIDATE_POINTER1(hOutLayer, "GDALPolygonize", CE_Failure);
if (pfnProgress == nullptr)
pfnProgress = GDALDummyProgress;
const int nConnectedness =
CSLFetchNameValue(papszOptions, "8CONNECTED") ? 8 : 4;
/* -------------------------------------------------------------------- */
/* Confirm our output layer will support feature creation. */
/* -------------------------------------------------------------------- */
if (!OGR_L_TestCapability(hOutLayer, OLCSequentialWrite))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Output feature layer does not appear to support creation "
"of features in GDALPolygonize().");
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* Allocate working buffers. */
/* -------------------------------------------------------------------- */
const int nXSize = GDALGetRasterBandXSize(hSrcBand);
const int nYSize = GDALGetRasterBandYSize(hSrcBand);
if (nXSize > std::numeric_limits<int>::max() - 2)
{
CPLError(CE_Failure, CPLE_AppDefined, "Too wide raster");
return CE_Failure;
}
DataType *panLastLineVal = static_cast<DataType *>(
VSI_MALLOC2_VERBOSE(sizeof(DataType), nXSize + 2));
DataType *panThisLineVal = static_cast<DataType *>(
VSI_MALLOC2_VERBOSE(sizeof(DataType), nXSize + 2));
GInt32 *panLastLineId =
static_cast<GInt32 *>(VSI_MALLOC2_VERBOSE(sizeof(GInt32), nXSize + 2));
GInt32 *panThisLineId =
static_cast<GInt32 *>(VSI_MALLOC2_VERBOSE(sizeof(GInt32), nXSize + 2));
GByte *pabyMaskLine = hMaskBand != nullptr
? static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize))
: nullptr;
if (panLastLineVal == nullptr || panThisLineVal == nullptr ||
panLastLineId == nullptr || panThisLineId == nullptr ||
(hMaskBand != nullptr && pabyMaskLine == nullptr))
{
CPLFree(panThisLineId);
CPLFree(panLastLineId);
CPLFree(panThisLineVal);
CPLFree(panLastLineVal);
CPLFree(pabyMaskLine);
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* Get the geotransform, if there is one, so we can convert the */
/* vectors into georeferenced coordinates. */
/* -------------------------------------------------------------------- */
double adfGeoTransform[6] = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
bool bGotGeoTransform = false;
const char *pszDatasetForGeoRef =
CSLFetchNameValue(papszOptions, "DATASET_FOR_GEOREF");
if (pszDatasetForGeoRef)
{
GDALDatasetH hSrcDS = GDALOpen(pszDatasetForGeoRef, GA_ReadOnly);
if (hSrcDS)
{
bGotGeoTransform =
GDALGetGeoTransform(hSrcDS, adfGeoTransform) == CE_None;
GDALClose(hSrcDS);
}
}
else
{
GDALDatasetH hSrcDS = GDALGetBandDataset(hSrcBand);
if (hSrcDS)
bGotGeoTransform =
GDALGetGeoTransform(hSrcDS, adfGeoTransform) == CE_None;
}
if (!bGotGeoTransform)
{
adfGeoTransform[0] = 0;
adfGeoTransform[1] = 1;
adfGeoTransform[2] = 0;
adfGeoTransform[3] = 0;
adfGeoTransform[4] = 0;
adfGeoTransform[5] = 1;
}
/* -------------------------------------------------------------------- */
/* 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. */
/* -------------------------------------------------------------------- */
GDALRasterPolygonEnumeratorT<DataType, EqualityTest> oFirstEnum(
nConnectedness);
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, eDT, 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;
// Swap lines.
std::swap(panLastLineVal, panThisLineVal);
std::swap(panLastLineId, panThisLineId);
/* --------------------------------------------------------------------
*/
/* Report progress, and support interrupts. */
/* --------------------------------------------------------------------
*/
if (!pfnProgress(0.10 * ((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();
/* -------------------------------------------------------------------- */
/* Initialize ids to -1 to serve as a nodata value for the */
/* previous line, and past the beginning and end of the */
/* scanlines. */
/* -------------------------------------------------------------------- */
panThisLineId[0] = -1;
panThisLineId[nXSize + 1] = -1;
for (int iX = 0; iX < nXSize + 2; iX++)
panLastLineId[iX] = -1;
/* -------------------------------------------------------------------- */
/* We will use a new enumerator for the second pass primarily */
/* so we can preserve the first pass map. */
/* -------------------------------------------------------------------- */
GDALRasterPolygonEnumeratorT<DataType, EqualityTest> oSecondEnum(
nConnectedness);
RPolygon **papoPoly = static_cast<RPolygon **>(
VSI_CALLOC_VERBOSE(sizeof(RPolygon *), oFirstEnum.nNextPolygonId));
if (oFirstEnum.nNextPolygonId && papoPoly == nullptr)
eErr = CE_Failure;
/* ==================================================================== */
/* Second pass during which we will actually collect polygon */
/* edges as geometries. */
/* ==================================================================== */
for (int iY = 0; eErr == CE_None && iY < nYSize + 1; iY++)
{
/* --------------------------------------------------------------------
*/
/* Read the image data. */
/* --------------------------------------------------------------------
*/
if (iY < nYSize)
{
eErr = GDALRasterIO(hSrcBand, GF_Read, 0, iY, nXSize, 1,
panThisLineVal, nXSize, 1, eDT, 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 == nYSize)
{
for (int iX = 0; iX < nXSize + 2; iX++)
panThisLineId[iX] = -1;
}
else if (iY == 0)
{
eErr = oSecondEnum.ProcessLine(nullptr, panThisLineVal, nullptr,
panThisLineId + 1, nXSize)
? CE_None
: CE_Failure;
}
else
{
eErr = oSecondEnum.ProcessLine(panLastLineVal, panThisLineVal,
panLastLineId + 1, panThisLineId + 1,
nXSize)
? CE_None
: CE_Failure;
}
if (eErr != CE_None)
continue;
/* --------------------------------------------------------------------
*/
/* Add polygon edges to our polygon list for the pixel */
/* boundaries within and above this line. */
/* --------------------------------------------------------------------
*/
for (int iX = 0; iX < nXSize + 1; iX++)
{
AddEdges(panThisLineId, panLastLineId, oFirstEnum.panPolyIdMap,
oFirstEnum.panPolyValue, papoPoly, iX, iY);
}
/* --------------------------------------------------------------------
*/
/* Periodically we scan out polygons and write out those that */
/* haven't been added to on the last line as we can be sure */
/* they are complete. */
/* --------------------------------------------------------------------
*/
if (iY % 8 == 7)
{
for (int iX = 0; eErr == CE_None && iX < oSecondEnum.nNextPolygonId;
iX++)
{
if (papoPoly[iX] && papoPoly[iX]->nLastLineUpdated < iY - 1)
{
eErr = EmitPolygonToLayer(hOutLayer, iPixValField,
papoPoly[iX], adfGeoTransform);
delete papoPoly[iX];
papoPoly[iX] = nullptr;
}
}
}
/* --------------------------------------------------------------------
*/
/* 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.10 + 0.90 * ((iY + 1) / static_cast<double>(nYSize)),
"", pProgressArg))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
eErr = CE_Failure;
}
}
/* -------------------------------------------------------------------- */
/* Make a cleanup pass for all unflushed polygons. */
/* -------------------------------------------------------------------- */
for (int iX = 0; eErr == CE_None && iX < oSecondEnum.nNextPolygonId; iX++)
{
if (papoPoly[iX])
{
eErr = EmitPolygonToLayer(hOutLayer, iPixValField, papoPoly[iX],
adfGeoTransform);
delete papoPoly[iX];
papoPoly[iX] = nullptr;
}
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
CPLFree(panThisLineId);
CPLFree(panLastLineId);
CPLFree(panThisLineVal);
CPLFree(panLastLineVal);
CPLFree(pabyMaskLine);
CPLFree(papoPoly);
return eErr;
}
/******************************************************************************/
/* GDALFloatEquals() */
/* Code from: */
/* http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm */
/******************************************************************************/
GBool GDALFloatEquals(float A, float B)
{
// This function will allow maxUlps-1 floats between A and B.
const int maxUlps = MAX_ULPS;
// Make sure maxUlps is non-negative and small enough that the default NAN
// won't compare as equal to anything.
#if MAX_ULPS <= 0 || MAX_ULPS >= 4 * 1024 * 1024
#error "Invalid MAX_ULPS"
#endif
// This assignation could violate strict aliasing. It causes a warning with
// gcc -O2. Use of memcpy preferred. Credits for Even Rouault. Further info
// at http://trac.osgeo.org/gdal/ticket/4005#comment:6
int aInt = 0;
memcpy(&aInt, &A, 4);
// Make aInt lexicographically ordered as a twos-complement int.
if (aInt < 0)
aInt = INT_MIN - aInt;
// Make bInt lexicographically ordered as a twos-complement int.
int bInt = 0;
memcpy(&bInt, &B, 4);
if (bInt < 0)
bInt = INT_MIN - bInt;
#ifdef COMPAT_WITH_ICC_CONVERSION_CHECK
const int intDiff =
abs(static_cast<int>(static_cast<GUIntBig>(static_cast<GIntBig>(aInt) -
static_cast<GIntBig>(bInt)) &
0xFFFFFFFFU));
#else
// To make -ftrapv happy we compute the diff on larger type and
// cast down later.
const int intDiff = abs(static_cast<int>(static_cast<GIntBig>(aInt) -
static_cast<GIntBig>(bInt)));
#endif
if (intDiff <= maxUlps)
return true;
return false;
}
/************************************************************************/
/* GDALPolygonize() */
/************************************************************************/
/**
* Create polygon coverage from raster data.
*
* This function creates vector polygons for all connected regions of pixels in
* the raster sharing a common pixel value. Optionally each polygon may be
* labeled with the pixel value in an attribute. Optionally a mask band
* can be provided to determine which pixels are eligible for processing.
*
* Note that currently the source pixel band values are read into a
* signed 64bit integer buffer (Int64), so floating point or complex
* bands will be implicitly truncated before processing. If you want to use a
* version using 32bit float buffers, see GDALFPolygonize().
*
* Polygon features will be created on the output layer, with polygon
* geometries representing the polygons. The polygon geometries will be
* in the georeferenced coordinate system of the image (based on the
* geotransform of the source dataset). It is acceptable for the output
* layer to already have features. Note that GDALPolygonize() does not
* set the coordinate system on the output layer. Application code should
* do this when the layer is created, presumably matching the raster
* coordinate system.
*
* The algorithm used attempts to minimize memory use so that very large
* rasters can be processed. However, if the raster has many polygons
* or very large/complex polygons, the memory use for holding polygon
* enumerations and active polygon geometries may grow to be quite large.
*
* The algorithm will generally produce very dense polygon geometries, with
* edges that follow exactly on pixel boundaries for all non-interior pixels.
* For non-thematic raster data (such as satellite images) the result will
* essentially be one small polygon per pixel, and memory and output layer
* sizes will be substantial. The algorithm is primarily intended for
* relatively simple thematic imagery, masks, and classification results.
*
* @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 collection as
* polygons.
* @param hOutLayer the vector feature layer to which the polygons should
* be written.
* @param iPixValField the attribute field index indicating the feature
* attribute into which the pixel value of the polygon should be written. Or
* -1 to indicate that the pixel value must not be written.
* @param papszOptions a name/value list of additional options
* <ul>
* <li>8CONNECTED=8: May be set to "8" to use 8 connectedness.
* Otherwise 4 connectedness will be applied to the algorithm</li>
* </ul>
* @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 on a failure.
*/
CPLErr CPL_STDCALL GDALPolygonize(GDALRasterBandH hSrcBand,
GDALRasterBandH hMaskBand,
OGRLayerH hOutLayer, int iPixValField,
char **papszOptions,
GDALProgressFunc pfnProgress,
void *pProgressArg)
{
return GDALPolygonizeT<std::int64_t, IntEqualityTest>(
hSrcBand, hMaskBand, hOutLayer, iPixValField, papszOptions, pfnProgress,
pProgressArg, GDT_Int64);
}
/************************************************************************/
/* GDALFPolygonize() */
/************************************************************************/
/**
* Create polygon coverage from raster data.
*
* This function creates vector polygons for all connected regions of pixels in