10

I need to load a raster file from the provided file path. I wish to use it further in the Raster Calculator. I wrote a function which converts string (I assume it is a file path) to a raster object.

from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo
def StringToRaster(raster):
 # Check if string is provided
 if isinstance(raster,basestring):
 fileInfo = QFileInfo(raster)
 baseName = fileInfo.baseName()
 path = fileInfo.filePath()
 if (baseName and path):
 raster = QgsRasterLayer(path, baseName)
 if not raster.isValid():
 print "Layer failed to load!"
 return
 else:
 print "Unable to read basename and file path - Your string is probably invalid"
 return
 return raster

I have no idea why, but raster.isValid() always returns False. When I take exactly the same path which I provided to my function, I am able to add this layer to QGIS from the interface (from the menu Layer --> Add layer ---> Add raster layer).

My layer is a Float32 GeoTIFF with one band only.

enter image description here

Germán Carrillo
37.3k5 gold badges127 silver badges182 bronze badges
asked Apr 26, 2015 at 9:29
1
  • Example path: /home/mateusz/many times I tried/data/TTT/TRR___niskorozdzielczy.tif Commented Apr 26, 2015 at 9:33

3 Answers 3

7

If you keep getting non valid layers, even defining them correctly, you're probably missing the QGIS prefix definition in your script (in case that you work out of QGIS).

qgis_prefix="/usr" 
QgsApplication.setPrefixPath(qgis_prefix, True) 
QgsApplication.initQgis()

If you work on Windows, your qgis_prefix should be something like this:

qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis"

Now your raster layer should be valid.

answered May 8, 2015 at 2:12
3
  • Thanks, it seems that you need to import additional modules? Error message: name 'QgsApplication' is not defined. Commented May 12, 2015 at 4:51
  • Right, you would need (at least) this line: from qgis.core import QgsApplication Commented May 12, 2015 at 15:42
  • 1
    Great, now it works perfectly. Commented May 12, 2015 at 18:53
6

This code works in my Python Console:

from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo
def StringToRaster(raster):
 # Check if string is provided
 fileInfo = QFileInfo(raster)
 path = fileInfo.filePath()
 baseName = fileInfo.baseName()
 layer = QgsRasterLayer(path, baseName)
 QgsMapLayerRegistry.instance().addMapLayer(layer)
 if layer.isValid() is True:
 print "Layer was loaded successfully!"
 else:
 print "Unable to read basename and file path - Your string is probably invalid"
raster = '/home/zeito/Desktop/output2.tif'
StringToRaster(raster)

After running the code in the Python Console of QGIS:

result

For those who will work with QGIS 3:

from qgis.core import QgsRasterLayer
from PyQt5.QtCore import QFileInfo
def StringToRaster(raster):
 # Check if string is provided
 fileInfo = QFileInfo(raster)
 path = fileInfo.filePath()
 baseName = fileInfo.baseName()
 layer = QgsRasterLayer(path, baseName)
 QgsProject.instance().addMapLayer(layer)
 if layer.isValid() is True:
 print ("Layer was loaded successfully!")
 else:
 print ("Unable to read basename and file path - Your string is probably invalid")
raster = '/home/zeito/Desktop/output2.tif'
StringToRaster(raster)
Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Apr 26, 2015 at 12:50
2
  • 1
    Thanks, but my code also works in Python console within QGIS. For some reason, when I give exactly the same path, isValid() returns False outside Python QGIS console (for example in iPython) and True in QGIS Python console. Commented Apr 28, 2015 at 4:13
  • I added a picture to my question. Commented Apr 28, 2015 at 4:25
3

The QGIS documentation also proposes a second way, I found very helpful:

[R]aster layers can be loaded using the addRasterLayer function of the QgisInterface:

iface.addRasterLayer("/path/to/raster/file.tif", "layer name you like")

answered Jul 13, 2018 at 14:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.