I want to calculate a new raster starting from my own raster. I use QGIS Raster Calculator and it works. Then I want to include it in a python script to create it manually. My new raster is created but empty. I am searching where the problem comes from. My formula is correct (when I copy paste it in QGIS Raster Calculator it works fine). So I tried to execute it directly from the console, I got this error and qgis closed :
My code is the following :
l=iface.activeLayer()
a=l.extent()
b=l.width()
c=l.height()
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
rast = QgsRasterCalculatorEntry()
entries=[rast]
calc = QgsRasterCalculator( '("lu_6@1"=210)*200',"D:/ju/Histo_Europe_folder_test/test_map.tif",'GTiff',a,b,c,entries )
My raster layer is called lu_6 and I am using QGIS 2.18.9.
Any idea why I get this error ?
Answer
I got my system dump with your code. Issue is because it's necessary a good reference for your layer by using QgsRasterCalculatorEntry class methods (you cannot use that string for 'expression'). So, with a copy/path of your next modified code at Python Console of QGIS:
l=iface.activeLayer()
a=l.extent()
b=l.width()
c=l.height()
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
rast = QgsRasterCalculatorEntry()
rast.ref = l.name() +'@1'
rast.raster = l
rast.bandNumber = 1
entries=[ rast ]
expression = '( ' + entries[0].ref + ' ) * 200 '
print expression
calc = QgsRasterCalculator( expression,
"/home/zeito/pyqgis_data/z.tif",
'GTiff',
a,
b,
c,
entries )
calc.processCalculation()
I got 0 execution code, pointed out that it ran without problems. I tried it out with raster of next image (with only 3 values to make corroboration easier).
By using Value Tool plugin, it was corroborated that values were obtained as expected in resulting raster.
Editing Note:
Afterward, I see condition for resulting raster. In this case, code is as follows:
l=iface.activeLayer()
a=l.extent()
b=l.width()
c=l.height()
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
rast = QgsRasterCalculatorEntry()
rast.ref = l.name() +'@1'
rast.raster = l
rast.bandNumber = 1
entries=[ rast ]
expression = '( (' + entries[0].ref + ' ) = 1 ) * 200 + ' + '( (' + entries[0].ref + ' ) != 1 ) * ' + entries[0].ref
print expression
calc = QgsRasterCalculator( expression,
"/home/zeito/pyqgis_data/z.tif",
'GTiff',
a,
b,
c,
entries )
calc.processCalculation()
After running it, results were obtained as expected.
No comments:
Post a Comment