This code of mine is written to extract raster using a particular shapefile in PyQGIS:

import subprocess, os, glob, gdal
result_path = "/data/brent/bukidnon_hansen_data/result_path//"
mask_layer = ("/data/brent/bukidnon_hansen_data/shp_files/AD_Kalatunganrange.shp")

for fname in glob.glob("*.tif"):
    input = os.path.join("/data/brent/bukidnon_hansen_data/bukidnon_forest_cover_hansen", fname)
    (pathshp, shpname) = os.path.split(mask_layer)
    (newName, ext) = os.path.splitext(shpname)
    warp = 'gdalwarp -cutline \'%s\' -crop_to_cutline -dstalpha \'%s\' \'%s\'' % (mask_layer, input, result_path+newName+fname)

The output rasters had two bands, what I want are single band rasters. I checked the gdalwarp documentation http://www.gdal.org/gdalwarp.html but I can't find the arguments that should make the output raster as single band.

Perhaps I missed something?

The input tiffs are single band rasters.

  • @Joseph I'd removed the -dst alpha and it worked. Aug 2 '17 at 2:49
  • Nice one! Will post the comment as an answer for the convenience of others :)
    – Joseph
    Aug 2 '17 at 8:56
  • 1
    That's what I would like to comment, so the answer could served as a reference for others. Again, much thanks.:] Aug 3 '17 at 4:34

The output raster has two bands because you are also including the alpha band (indicated by the -dstalpha parameter). If you don't need this band then you can remove the parameter so that it reads:

warp = 'gdalwarp -cutline \'%s\' -crop_to_cutline \'%s\' \'%s\'' % (mask_layer, input, result_path+newName+fname)

This should create an output raster with only one band.

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.