File: gdal_polygonize.py

package info (click to toggle)
gdal 3.11.3%2Bdfsg-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 89,016 kB
  • sloc: cpp: 1,165,048; ansic: 208,864; python: 26,958; java: 5,972; xml: 4,611; sh: 3,776; cs: 2,508; yacc: 1,306; makefile: 213
file content (346 lines) | stat: -rw-r--r-- 11,526 bytes parent folder | download
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************************************
#
#  Project:  GDAL Python Interface
#  Purpose:  Application for converting raster data to a vector polygon layer.
#  Author:   Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
#  Copyright (c) 2008, Frank Warmerdam
#  Copyright (c) 2009-2013, Even Rouault <even dot rouault at spatialys.com>
#  Copyright (c) 2021, Idan Miara <idan@miara.com>
#
# SPDX-License-Identifier: MIT
# ******************************************************************************

import sys
import textwrap
from typing import Optional, Union

from osgeo import gdal, ogr
from osgeo_utils.auxiliary.gdal_argparse import GDALArgumentParser, GDALScript
from osgeo_utils.auxiliary.util import GetOutputDriverFor, enable_gdal_exceptions


@enable_gdal_exceptions
def gdal_polygonize(
    src_filename: Optional[str] = None,
    band_number: Union[int, str] = 1,
    dst_filename: Optional[str] = None,
    overwrite: bool = False,
    driver_name: Optional[str] = None,
    dst_layername: Optional[str] = None,
    dst_fieldname: Optional[str] = None,
    quiet: bool = False,
    mask: str = "default",
    options: Optional[list] = None,
    layer_creation_options: Optional[list] = None,
    connectedness8: bool = False,
):

    if isinstance(band_number, str) and not band_number.startswith("mask"):
        band_number = int(band_number)

    options = options or []

    if connectedness8:
        options.append("8CONNECTED=8")

    if driver_name is None:
        driver_name = GetOutputDriverFor(dst_filename, is_raster=False)

    if dst_layername is None:
        dst_layername = "out"

    # =============================================================================
    # Open source file
    # =============================================================================

    src_ds = gdal.Open(src_filename)

    if src_ds is None:
        print("Unable to open %s" % src_filename)
        return 1

    if band_number == "mask":
        srcband = src_ds.GetRasterBand(1).GetMaskBand()
        # Workaround the fact that most source bands have no dataset attached
        options.append("DATASET_FOR_GEOREF=" + src_filename)
    elif isinstance(band_number, str) and band_number.startswith("mask,"):
        srcband = src_ds.GetRasterBand(int(band_number[len("mask,") :])).GetMaskBand()
        # Workaround the fact that most source bands have no dataset attached
        options.append("DATASET_FOR_GEOREF=" + src_filename)
    else:
        srcband = src_ds.GetRasterBand(band_number)

    if mask == "default":
        maskband = srcband.GetMaskBand()
    elif mask == "none":
        maskband = None
    else:
        mask_ds = gdal.Open(mask)
        maskband = mask_ds.GetRasterBand(1)

    # =============================================================================
    #       Try opening the destination file as an existing file.
    # =============================================================================

    try:
        gdal.PushErrorHandler("CPLQuietErrorHandler")
        dst_ds = ogr.Open(dst_filename, update=1)
        gdal.PopErrorHandler()
    except Exception:
        try:
            dst_ds = ogr.Open(dst_filename)
        except Exception:
            dst_ds = None
        if dst_ds and not overwrite:
            raise Exception(
                f"{dst_filename} exists, but cannot be updated. You may need to remove it before or use -overwrite"
            )

    if dst_ds is not None and overwrite:
        cnt = dst_ds.GetLayerCount()
        iLayer = None  # initialize in case there are no loop iterations
        for iLayer in range(cnt):
            poLayer = dst_ds.GetLayer(iLayer)
            if poLayer is not None and poLayer.GetName() == dst_layername:
                break

        delete_ok = False
        if iLayer != cnt:
            if dst_ds.TestCapability(ogr.ODsCDeleteLayer) == 1:
                try:
                    delete_ok = dst_ds.DeleteLayer(iLayer) == ogr.OGRERR_NONE
                except Exception:
                    delete_ok = False

        if not delete_ok:
            if cnt == 1:
                dst_ds = None
                if gdal.VSIStatL(dst_filename):
                    gdal.Unlink(dst_filename)

    # =============================================================================
    # 	Create output file.
    # =============================================================================
    if dst_ds is None:
        drv = ogr.GetDriverByName(driver_name)
        if not quiet:
            print("Creating output %s of format %s." % (dst_filename, driver_name))
        dst_ds = drv.CreateDataSource(dst_filename)
        if dst_ds is None:
            print('Cannot create datasource "%s"' % dst_filename)
            return 1

    # =============================================================================
    #       Find or create destination layer.
    # =============================================================================
    try:
        dst_layer = dst_ds.GetLayerByName(dst_layername)
    except Exception:
        dst_layer = None

    dst_field: int = -1
    if dst_layer is None:

        srs = src_ds.GetSpatialRef()
        dst_layer = dst_ds.CreateLayer(
            dst_layername,
            geom_type=ogr.wkbPolygon,
            srs=srs,
            options=layer_creation_options if layer_creation_options else [],
        )

        if dst_fieldname is None:
            dst_fieldname = "DN"

        data_type = ogr.OFTInteger
        if srcband.DataType == gdal.GDT_Int64 or srcband.DataType == gdal.GDT_UInt64:
            data_type = ogr.OFTInteger64

        fd = ogr.FieldDefn(dst_fieldname, data_type)
        dst_layer.CreateField(fd)
        dst_field = 0
    else:
        if layer_creation_options:
            print(
                "Warning: layer_creation_options will be ignored as the layer already exists"
            )

        if dst_fieldname is not None:
            dst_field = dst_layer.GetLayerDefn().GetFieldIndex(dst_fieldname)
            if dst_field < 0:
                print(
                    "Warning: cannot find field '%s' in layer '%s'"
                    % (dst_fieldname, dst_layername)
                )

    # =============================================================================
    # Invoke algorithm.
    # =============================================================================

    if quiet:
        prog_func = None
    else:
        prog_func = gdal.TermProgress_nocb

    dst_layer.StartTransaction()
    result = gdal.Polygonize(
        srcband, maskband, dst_layer, dst_field, options, callback=prog_func
    )
    if result == gdal.CE_None:
        dst_layer.CommitTransaction()
    else:
        dst_layer.RollbackTransaction()

    srcband = None
    src_ds = None
    dst_ds = None
    mask_ds = None

    return result


class GDALPolygonize(GDALScript):
    def __init__(self):
        super().__init__()
        self.title = "Produces a polygon feature layer from a raster"
        self.description = textwrap.dedent(
            """\
            This utility creates vector polygons for all connected regions of pixels in the raster
            sharing a common pixel value. Each polygon is created with an attribute indicating
            the pixel value of that polygon.
            A raster mask may also be provided to determine which pixels are eligible for processing.
            The utility will create the output vector datasource if it does not already exist,
            otherwise it will try to append to an existing one.
            The utility is based on the GDALPolygonize() function
            which has additional details on the algorithm."""
        )

    def get_parser(self, argv) -> GDALArgumentParser:
        parser = self.parser

        parser.add_argument(
            "-q",
            "-quiet",
            dest="quiet",
            action="store_true",
            help="The script runs in quiet mode. "
            "The progress monitor is suppressed and routine messages are not displayed.",
        )

        parser.add_argument(
            "-8",
            dest="connectedness8",
            action="store_true",
            help="Use 8 connectedness. Default is 4 connectedness.",
        )

        parser.add_argument(
            "-o",
            dest="options",
            type=str,
            action="append",
            metavar="name=value",
            help="Specify a special argument to the algorithm. This may be specified multiple times.",
        )

        parser.add_argument(
            "-mask",
            dest="mask",
            type=str,
            metavar="filename",
            default="default",
            help="Use the first band of the specified file as a validity mask "
            "(zero is invalid, non-zero is valid).",
        )

        parser.add_argument(
            "-nomask",
            dest="mask",
            action="store_const",
            const="none",
            default="default",
            help="Do not use the default validity mask for the input band "
            "(such as nodata, or alpha masks).",
        )

        parser.add_argument(
            "-b",
            "-band",
            dest="band_number",
            metavar="band",
            type=str,
            default="1",
            help="The band on <raster_file> to build the polygons from. "
            'Starting with GDAL 2.2, the value can also be set to "mask", '
            "to indicate that the mask band of the first band must be used "
            '(or "mask,band_number" for the mask of a specified band).',
        )

        parser.add_argument(
            "-of",
            "-f",
            dest="driver_name",
            metavar="ogr_format",
            help="Select the output format. "
            "if not specified, the format is guessed from the extension. "
            "Use the short format name.",
        )

        parser.add_argument(
            "-lco",
            dest="layer_creation_options",
            type=str,
            action="append",
            metavar="name=value",
            help="Specify a layer creation option. This may be specified multiple times.",
        )

        parser.add_argument(
            "-overwrite",
            dest="overwrite",
            action="store_true",
            help="overwrite output file if it already exists",
        )

        parser.add_argument(
            "src_filename",
            type=str,
            help="The source raster file from which polygons are derived.",
        )

        parser.add_argument(
            "dst_filename",
            type=str,
            help="The destination vector file to which the polygons will be written.",
        )

        parser.add_argument(
            "dst_layername",
            type=str,
            nargs="?",
            help="The name of the layer created to hold the polygon features.",
        )

        parser.add_argument(
            "dst_fieldname",
            type=str,
            nargs="?",
            help='The name of the field to create (defaults to "DN").',
        )

        return parser

    def doit(self, **kwargs):
        return gdal_polygonize(**kwargs)


def main(argv=sys.argv):
    return GDALPolygonize().main(argv)


if __name__ == "__main__":
    sys.exit(main(sys.argv))