2

I'm brand new in python.

I'm using QGIS 2.18.3. I wrote this script that should read all the dual band raster layers in the canvas and should save each band in a separate way, but it doesn't work. I presume it will be full of errors.

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

# where to save bands
outputDir = "D:\prova"

import os
lddLrs = qgis.utils.iface.legendInterface().layers()

for lyr in lddLrs:
    if (lyr.type()==QgsMapLayer.RasterLayer): 
    os.system("gdal_translate -b 1 "+ str(lyr.source()) + " " + outputDir + " / " + str(lyr.name()) + " _VV.tif"))
    qgis.utils.iface.addRasterLayer(str(outputDir + "/" + lyr.name() + ".tif"), str(lyr.name() + "_VV.tif"))
    os.system("gdal_translate -b 2 "+ str(lyr.source()) + " " + outputDir + " / " + str(lyr.name()) + " _VH.tif"))
    qgis.utils.iface.addRasterLayer(str(outputDir + "/" + lyr.name() + ".tif"), str(lyr.name() + "_VH.tif"))
  • I fixed all errors and now, code works perfectly. Please, see my answer. – xunilk Mar 10 '17 at 23:48
2

I fixed all errors and now, it works perfectly. Complete code is below:

import sys, os

# where to save bands
outputDir = "/home/zeito/pyqgis_data"

lddLrs = iface.legendInterface().layers()

for lyr in lddLrs:
    if (lyr.type() == QgsMapLayer.RasterLayer): 
        cmd1 = "gdal_translate -b 1 "+ lyr.source() + " " + outputDir + "/" + lyr.name() + "_VV.tif"
        os.system(cmd1)
        cmd2 = outputDir + "/" + lyr.name() + "_VV.tif"
        iface.addRasterLayer(cmd2)
        cmd3 = "gdal_translate -b 2 "+ lyr.source() + " " + outputDir + "/" + lyr.name() + "_VH.tif"
        os.system(cmd3)
        cmd4 = outputDir + "/" + lyr.name() + "_VH.tif"
        iface.addRasterLayer(cmd4)

I tried it out with a RGB raster. After running the code, bands 1 and 2 were loaded automatically; as it can be observed at next image:

enter image description here

With Value Tool plugin of QGIS, I corroborated that the splitting was done as expected.

  • I apologize, I need to be more skilled to participate to stack exchange. Thank you again – ilFonta Mar 11 '17 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.