2

In the QGIS 3.36.1 Python Console, I'm trying to create an output raster so I can write pixel values sampled from another raster.

output_raster_path = r'D:\Output Raster.tif'
output_raster = QgsRasterFileWriter(output_raster_path)
output_raster.setOutputFormat("GTiff")
output_raster.setCreateOptions([])  # No compression
output_raster.writeRaster(cols, rows, extent, input_raster.crs())

The line output_raster.writeRaster(cols, rows, extent, input_raster.crs()) is throwing an error

Traceback (most recent call last):
  File "C:\OSGeo4W\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 13, in <module>
TypeError: QgsRasterFileWriter.writeRaster(): arguments did not match any overloaded call:
  overload 1: argument 1 has unexpected type 'int'
  overload 2: argument 1 has unexpected type 'int'

rows and cols are definitely int and the extent is QgsRectangle.

It looks like the line is right, according to the documentation:

writeRaster(self, pipe: QgsRasterPipe | None, nCols: int, nRows: int, outputExtent: QgsRectangle, crs: QgsCoordinateReferenceSystem, feedback: QgsRasterBlockFeedback | None = None) → Qgis.RasterFileWriterResult

I've tried naming the arguments, so nCols = cols, nRows = rows etc., but that produced an error too. The error means there's something wrong with the order or type of the arguments, but I can't see what.

This is kind of similar to "QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call" in PyQGIS but there must be a different answer.

1

1 Answer 1

2

I could get the same TypeError:

File "C:\OSGeo4W\apps\Python312\Lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 8, in <module>
TypeError: QgsRasterFileWriter.writeRaster(): arguments did not match any overloaded call:
  overload 1: argument 1 has unexpected type 'int'
  overload 2: argument 1 has unexpected type 'int'

when I proceeded with this script:

from qgis.utils import iface
from qgis.core import QgsRasterFileWriter

layer = iface.activeLayer()
provider = layer.dataProvider()

out_file = provider.dataSourceUri().replace('.tif', '.img')
file_writer = QgsRasterFileWriter(out_file)
result = file_writer.writeRaster(provider.xSize(), provider.ySize(), provider.extent(), provider.crs())

⚠️ As was mentioned in @user30184's comment it is vital to include the pipe-parameter of the QgsRasterPipe class type:

Contains a pipeline of raster interfaces for sequential raster processing.

There are also several suggestions regarding your code:

  • check firstly details about the writeRaster()-method with help(QgsRasterFileWriter.writeRaster):

     Help on built-in function writeRaster:
    
     writeRaster(...)
         writeRaster(self, pipe: Optional[QgsRasterPipe], nCols: int, nRows: int, outputExtent: QgsRectangle, crs: QgsCoordinateReferenceSystem, feedback: Optional[QgsRasterBlockFeedback] = None) -> Qgis.RasterFileWriterResult
         Write raster file
    
         :param pipe: raster pipe
         :param nCols: number of output columns
         :param nRows: number of output rows (or -1 to automatically calculate row number to have square pixels)
         :param outputExtent: extent to output
         :param crs: crs to reproject to
         :param feedback: optional feedback object for progress reports
    
         .. deprecated:: QGIS 3.8
           use version with transformContext instead
    
  • treat file export results properly using the Qgis.RasterFileWriterResult

  • make use of the QgsRasterBlockFeedback class and its errors()-method to get more details about errors while retrieving the raster block

  • apply the Python Try Except blocks to handle errors and exceptions

  • check if your input QgsRasterLayer is solid with the isValid()-method

  • imports can be useful to make your code reusable in the future in standalone applications

  • delete the writer object with del statement

In the end, your code may look as follows:

from qgis.utils import iface
from qgis.core import Qgis, QgsRasterPipe, QgsRasterFileWriter, QgsRasterBlockFeedback

layer = iface.activeLayer()

if layer.isValid():
    provider = layer.dataProvider()

    pipe = QgsRasterPipe()
    pipe.set(provider.clone())

    out_file = provider.dataSourceUri().replace('.tif', '.img')
    file_writer = QgsRasterFileWriter(out_file)

    try:
        feedback = QgsRasterBlockFeedback()
        result = file_writer.writeRaster(pipe, provider.xSize(), provider.xSize(), provider.extent(), provider.crs(), feedback)
        if result != Qgis.RasterFileWriterResult.Success:
            print(feedback.errors())
    except Exception as e:
        print(e)
        
    del file_writer

References:

2
  • How do you add that yellow warning sign?
    – Bera
    Commented Jun 13 at 6:53
  • It is an emoji: ⚠️, I just do not remember where I found it...
    – Taras
    Commented Jun 13 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.