2

I would like to know how to transform the following code in something that only uses PyQGIS. I haven't found an example showing how to create raster files with PyQGIS yet.

I'm making a processing algorithm in QGIS 3. The variable input is a QgsRasterLayer.

#Getting input attributes
band_count = input.bandCount()
rows = input.height()
cols = input.width()
pixelType = input.dataProvider().dataType(1)

#Getting the destination file name and file format
destfile = self.parameterAsOutputLayer(parameters, 'OUTPUT', context)
fileformat = GdalUtils.getFormatShortNameFromFilename(destfile)

The actual raster creation is made below. This is the part I want to change to use only PyQGIS instead of GDAL. The variable classified is a numpy array made with scikit-learn.

driver = gdal.GetDriverByName(fileformat)
#Number of bands should be 1
band_count = 1
outRaster = driver.Create(destfile, cols, rows, band_count, pixelType)
outRaster.SetGeoTransform(dataset.GetGeoTransform())
outRaster.SetProjection(dataset.GetProjectionRef())
outRaster.GetRasterBand(1).WriteArray(classified)

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.