I want writing a python script to convert a layer raster to vector. Create a script but I have an error:

import gdal,ogr,os

# open raster file
raster = gdal.Open('C:/Users/beckham/Documents/Tesis 2018/Cortes muestra/SV2.tif')
band = raster.GetRasterBand(1)

#create new shp file
newSHPfn = 'test.shp'
shpDriver = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(newSHPfn):
outDataSource = shpDriver.CreateDataSource(newSHPfn)
outLayer = outDataSource.CreateLayer(newSHPfn, geom_type=ogr.wkbLineString )

# polygonize
processing.run('qgis:polygonize',raster, None, outLayer, 1)

The error is:

Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.0\apps\Python36\lib\code.py", line 91, in runcode exec(code, self.locals) File "", line 1, in File "", line 16, in File "C:/PROGRA~1/QGIS3~1.0/apps/qgis/./python/plugins\processing\tools\general.py", line 84, in run return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context) File "C:/PROGRA~1/QGIS3~1.0/apps/qgis/./python/plugins\processing\core\Processing.py", line 131, in runAlgorithm if param.name() not in parameters: TypeError: argument of type 'Dataset' is not iterable

I want to create a very simple script in python that polygonizes a raster. Based on python cookbook + forums search I wrote the following code

#import des modules
from osgeo import gdal, ogr
from qgis.core import *
from qgis.gui import *
import sys
from PyQt4.QtCore import * 

##Result=output vector

# 1. Open Raster and get band 1
src_ds = gdal.Open(srcRaster)
srcband = src_ds.GetRasterBand(1)

# 2. Create output datasource
Result = QgsVectorLayer("Polygon", "temporary_points", "memory")
Result.dataProvider().addAttributes([QgsField("ClassNo",     QVariant.String)])
gdal.Polygonize( srcband, None, Result, 0, [], callback=None )

Which ends up with the error "in method 'Polygonize', argument 3 of type 'OGRLayerShadow *". The truth is, I don't really understand what should be the syntax of gdal_polygonize in a QGIS python script (command line can be found here).

Could anybody please help ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.