3

I would like to reclass raster image with PyQGIS command from the Python Console. It runs without error but nothing is created. I have tried a lot of codes from here, but nothing is working.

from PyQt4.QtCore import QFileInfo 
import processing

# Define input and output paths
filePath = "/home/lukas/Desktop/Sentinel/flood.tif"
output = "/home/lukas/Desktop/Sentinel/flood_reclass.tif"
rules = "/home/lukas/Desktop/pyqgis/reclass.txt"

# Get raster data
fileInfo = QFileInfo(filePath)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(filePath, baseName)

# Define the minimum extent of the region
extent = rlayer.extent()
xmin = extent.xMinimum()
xmax = extent.xMaximum()
ymin = extent.yMinimum()
ymax = extent.yMaximum()

import processing
processing.runalg("grass7:r.reclass", rlayer,None, rules, 
"%f,%f,%f,%f"% (xmin, xmax, ymin, ymax), 0.0, output)

Console show no error but there is no result. I have tried to run this in tool, with these layers and rules file and it was working. When I copy command from processing tools history - which worked in tool - it is not working in console.

1 Answer 1

6

There are some syntax errors.

If you run this code from the Python Console:

import processing
processing.alghelp("grass7:r.reclass")

you will get:

ALGORITHM: r.reclass - Creates a new map layer whose category values are based upon a reclassification of the categories in an existing raster map layer.
    input <ParameterRaster>
    rules <ParameterFile>
    txtrules <ParameterString>
    GRASS_REGION_PARAMETER <ParameterExtent>
    GRASS_REGION_CELLSIZE_PARAMETER <ParameterNumber>
    output <OutputRaster>

This means that you need to define the rules before the txtrules (this is the first syntax error).

Finally, since you have already defined a reclassification file with rules, try to replace None with "".

The following code should work (it worked for me):

from PyQt4.QtCore import QFileInfo 
import processing

# Define input and output paths
filePath = "/home/lukas/Desktop/Sentinel/flood.tif"
output = "/home/lukas/Desktop/Sentinel/flood_reclass.tif"
rules = "/home/lukas/Desktop/pyqgis/reclass.txt"

# Get raster data
fileInfo = QFileInfo(filePath)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(filePath, baseName)

# Define the minimum extent of the region
extent = rlayer.extent()
xmin = extent.xMinimum()
xmax = extent.xMaximum()
ymin = extent.yMinimum()
ymax = extent.yMaximum()

import processing
processing.runalg("grass7:r.reclass", rlayer,rules, "", 
"%f,%f,%f,%f"% (xmin, xmax, ymin, ymax), 0.0, output)
1
  • 1
    Thank you very much mgri :) You have solved my problem ! :)
    – zubro
    Commented Aug 30, 2017 at 11:48

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.