Is there a processing algorithm in the pyqgis API for assigning a projection to a raster (GeoTIFF)?

I am clipping a GeoTIFF with a selected feature of a vector layer (shapefile). Both are projected in GDA94/MGA Zone 55. The QGIS project is set for the same projection. The result is defaulting to WGS84 for some reason, but not projecting to WGS84. It is holding the GDA94/MGA Zone 55 coordinates. I need to make sure the output is also in GDA94/MGA Zone 55 before progressing to the next step of the program.

I am running this in QGIS 2.14. I ran it two years back in QGIS 2.8 and I got the same projection in the output as I had in the input. I have tried manually running "Raster... Projections... Assign Projections" on the input raster before the clip, to make certain the input is georeferenced in a "QGIS friendly" manner. No luck. Here is the clipping algorithm I am running.

processing.runalg("saga:clipgridwithpolygon", veg_raster_for_clip, selected, outraster)
  • I have solved my problem, but have not answered the question. Originally I used the GDAL "rasterize" tool to create the raster I am clipping. I used defaults and it created a rather large 32 bit float raster. I created a new raster with ArcGIS Pro using the defaults and the result was a much smaller 4 bit raster. When clipped the output is projected in GDA94/MGA Zone 55. Still no answer for an "assign projection/define projection" function I can use with pyqgis. – Mike Apr 27 '18 at 6:59

You have to create a QgsRasterLayer object with the result of your processing and then set the crs.

Useful resurce here and here :

import processing
from qgis.core import QgsRasterLayer, QgsCoordinateReferenceSystem

processing.runalg("saga:clipgridwithpolygon", veg_raster_for_clip, selected, outraster)

layer_raster = QgsRasterLayer( outraster, 'name')

#replace 4326 with the crs that you want
layer_raster.setCrs( QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) )

After this you could do what you want with the object, even save it in another file.

  • 1
    Thanks, Oscar. Works like a charm - after removing the "s" from the end of "layer_rasters" in last line. – Mike Apr 27 '18 at 18:05
  • Oh, sorry. I edited the code ;) – Oscar Campo Apr 27 '18 at 21:16

Your Answer

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

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