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.