1# -*- coding: utf-8 -*-
2
3"""
4***************************************************************************
5    polygonize.py
6    ---------------------
7    Date                 : August 2012
8    Copyright            : (C) 2012 by Victor Olaya
9    Email                : volayaf at gmail dot com
10***************************************************************************
11*                                                                         *
12*   This program is free software; you can redistribute it and/or modify  *
13*   it under the terms of the GNU General Public License as published by  *
14*   the Free Software Foundation; either version 2 of the License, or     *
15*   (at your option) any later version.                                   *
16*                                                                         *
17***************************************************************************
18"""
19
20__author__ = 'Victor Olaya'
21__date__ = 'August 2012'
22__copyright__ = '(C) 2012, Victor Olaya'
23
24import os
25
26from qgis.PyQt.QtGui import QIcon
27
28from qgis.core import (QgsProcessing,
29                       QgsProcessingException,
30                       QgsProcessingParameterDefinition,
31                       QgsProcessingParameterRasterLayer,
32                       QgsProcessingParameterBand,
33                       QgsProcessingParameterString,
34                       QgsProcessingParameterBoolean,
35                       QgsProcessingParameterVectorDestination)
36from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
37from processing.tools.system import isWindows
38from processing.algs.gdal.GdalUtils import GdalUtils
39
40pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
41
42
43class polygonize(GdalAlgorithm):
44    INPUT = 'INPUT'
45    BAND = 'BAND'
46    FIELD = 'FIELD'
47    EIGHT_CONNECTEDNESS = 'EIGHT_CONNECTEDNESS'
48    EXTRA = 'EXTRA'
49    OUTPUT = 'OUTPUT'
50
51    def __init__(self):
52        super().__init__()
53
54    def initAlgorithm(self, config=None):
55        self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT, self.tr('Input layer')))
56        self.addParameter(QgsProcessingParameterBand(self.BAND,
57                                                     self.tr('Band number'),
58                                                     1,
59                                                     parentLayerParameterName=self.INPUT))
60        self.addParameter(QgsProcessingParameterString(self.FIELD,
61                                                       self.tr('Name of the field to create'),
62                                                       defaultValue='DN'))
63        self.addParameter(QgsProcessingParameterBoolean(self.EIGHT_CONNECTEDNESS,
64                                                        self.tr('Use 8-connectedness'),
65                                                        defaultValue=False))
66
67        extra_param = QgsProcessingParameterString(self.EXTRA,
68                                                   self.tr('Additional command-line parameters'),
69                                                   defaultValue=None,
70                                                   optional=True)
71        extra_param.setFlags(extra_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
72        self.addParameter(extra_param)
73
74        self.addParameter(QgsProcessingParameterVectorDestination(self.OUTPUT,
75                                                                  self.tr('Vectorized'),
76                                                                  QgsProcessing.TypeVectorPolygon))
77
78    def name(self):
79        return 'polygonize'
80
81    def displayName(self):
82        return self.tr('Polygonize (raster to vector)')
83
84    def group(self):
85        return self.tr('Raster conversion')
86
87    def groupId(self):
88        return 'rasterconversion'
89
90    def icon(self):
91        return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'polygonize.png'))
92
93    def commandName(self):
94        return 'gdal_polygonize'
95
96    def getConsoleCommands(self, parameters, context, feedback, executing=True):
97        arguments = []
98
99        if self.parameterAsBoolean(parameters, self.EIGHT_CONNECTEDNESS, context):
100            arguments.append('-8')
101
102        if self.EXTRA in parameters and parameters[self.EXTRA] not in (None, ''):
103            extra = self.parameterAsString(parameters, self.EXTRA, context)
104            arguments.append(extra)
105
106        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
107        if inLayer is None:
108            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT))
109
110        arguments.append(inLayer.source())
111
112        arguments.append('-b')
113        arguments.append(str(self.parameterAsInt(parameters, self.BAND, context)))
114
115        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
116        self.setOutputValue(self.OUTPUT, outFile)
117        output, outFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
118
119        if outFormat:
120            arguments.append('-f {}'.format(outFormat))
121
122        arguments.append(output)
123
124        layerName = GdalUtils.ogrOutputLayerName(output)
125        if layerName:
126            arguments.append(layerName)
127        arguments.append(self.parameterAsString(parameters, self.FIELD, context))
128
129        return [self.commandName() + ('.bat' if isWindows() else '.py'), GdalUtils.escapeAndJoin(arguments)]
130