0

My code converts shapefiles to rasters. I had first done this in colour, but now I need greyscale (1 band). The code seems to create this for the first raster file, but the other raster files seem to have no bands (previously they all had 3).

shapefiles = [folder + '/' + file for file in os.listdir(folder) if 'shp' in file]
output = 'output'
if not os.path.exists(output):
    os.mkdir(output)
RefImage = ref_image
gdalformat = 'GTiff'
datatype = gdal.GDT_Byte
burnVal = 1 #value for the output image pixels

# Get projection info from reference image
RasImage = gdal.Open(RefImage, gdal.GA_ReadOnly)

for Shapefile in shapefiles:
    ds = ogr.Open(Shapefile)
    ds_layer = ds.GetLayer()
# convert a shapefile to raster
def convertShpToRaster(inputfile, band, size):
    shp = ogr.Open(inputfile)
    lyr = shp.GetLayer(0)
    lyrname = lyr.GetName()
    #color = plt.gray()

    subprocess.call('gdal_rasterize -ts {0} {1} -l {2} -burn {3} ./{4} ./{5}.tif' \
                .format(size[0], size[1], lyrname, band, inputfile, output + '/' + lyrname))

def inputToShapefile():
    # input color, resolution and shapefile location
    #color = plt.gray()
    band = RasImage.GetRasterBand(1)
    size = RasImage.RasterXSize, RasImage.RasterYSize

    # call the function
    for inputfile in shapefiles:
        convertShpToRaster(inputfile, band, size)   

inputToShapefile()

Can somebody advise? Should I rasterise as before and then drop bands instead?

I am using Python 3.7.

  • 1
    band = RasImage.GetRasterBand(1) is going to set band to an object, but then you're passing that object into the string formatting when building the command. Just pass a "1" as a string or an int instead. Also note that the python bindings have an entry point to the rasterize utility so you could avoid using a subprocess if you feel so inclined – mikewatt Jan 9 at 1:47
  • thanks Vince. I think I have it now - adding .GetBand() to the band object and then removing band from the string part of the command, so: subprocess.call('gdal_rasterize -ts {0} {1} -l {0} -burn 1 ./{2} ./{3}.tif' \ .format(size, lyrname, inputfile, output + '/' + lyrname)) def inputToShapefile(): # input color, resolution and shapefile location #color = plt.gray() band = RasImage.GetRasterBand(1).GetBand() – gall Jan 9 at 10:45

Your Answer

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

Browse other questions tagged or ask your own question.