5

in a QGIS python plugin I get some code that writes a asc file, this is the header of the final file:

NCOLS  20 
NROWS  15 
XLLCORNER  664400.000000 
YLLCORNER  4749500.000000 
CELLSIZE   100.000000  
NODATA_VALUE   -9999.0 
NODATA_VALUE   -9999.0 

as you can see I get the X and Y corners of the file.

I wanted also to load the file in QGIS and obviously it asks me for the CRS.

What I am looking for, is to avoid this message and the related pop-up window while using QgsRasterLayer.

I've found this 2 old questions:

How can I specify the CRS of a raster layer in pyqgis?

and

How to get CRS of a raster layer in pyqgis?

but I cannot use them in order to solve my problem.

Someone has an idea?

3
  • @AndreSilva. The second answer talks about a raster already loaded in the TOC and many answers in the first question talk about iface..
    – matteo
    Commented Feb 22, 2016 at 14:16
  • Do you know which UTM (probable) zone or other CRS it is, and thus the EPSG well-known ID?
    – mkennedy
    Commented Feb 22, 2016 at 17:26
  • @mkennedy. Yes, I can retrieve the CRS (and EPSG code) easily.
    – matteo
    Commented Feb 23, 2016 at 8:09

1 Answer 1

6

For example, if you can retrieve the CRS (and EPSG code) easily then you can assign CRS easily with a few paths at the Python Console of QGIS. For example, I load a raster (xwRcl.tif) where it also asks me for the CRS (see next image).

enter image description here

These commands at the Python Console do the work:

>>>layer = iface.activeLayer()
>>>CRS = QgsCoordinateReferenceSystem()
>>>CRS
<qgis._core.QgsCoordinateReferenceSystem object at 0x9fbc5dac>
>>>CRS.createFromSrid(32612) #EPSG = 32612
True
>>>layer.setCrs(CRS)
>>>layer.crs().postgisSrid()  #to corroborate the assignation
32612L

I saved the raster with another name (test_crs.tif):

provider = layer.dataProvider()

pipe = QgsRasterPipe()

pipe.set(provider.clone())

rasterWriter = QgsRasterFileWriter("/home/zeito/pyqgis_data/test_crs.tif")

xSize = provider.xSize()
ySize = provider.ySize()

rasterWriter.writeRaster(pipe, xSize, ySize, provider.extent(), CRS)

and after reloaded it, in this opportunity, it was avoided the message of asking me for the CRS.

1
  • Just a note that on QGIS 2.14 and 2.18, the line in your second code block that saves the raster- pipe.set(provider.clone()) appears to crash QGIS. Saving of the raster, however, seems to work without that line so that's not a problem.
    – 15Step
    Commented Mar 6, 2018 at 15:09

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.