1

I have numerous multiband rasters (36 band) in which preserving the band order is important for future processing. One of the bands often contains erroneous data and I'd like to be able to change all the values in within that band to 0, but keep the band in place. Then ideally overwrite the changes to the existing raster. Is there a way to do this without having to open the band in question, make the change to 0, and then re-stack all the other bands along with the edited band into a new file? Or at the very least save the changes to a new raster without having to call up the other 35 bands individually into the stacking function?

For instance

import rasterio as rio
import numpy as np

inraster = "path_to_a_mutliband_raster"
rast = rio.open(inraster)
badband = rast.read(7)
badbad[badband != 0] = 0

From there I'm not sure how to save those changes back into the mutliband raster.

  • I am not certain at all, but I would be surprised if it would be possible to edit only a single band without re-writing the full file. One somewhat messy workaround I can think of would be to write your 0-band to disk, then make a virtual raster that stacks the good bands before, the 0-band, and the good bands after into a single file. – Jon Apr 8 at 16:30
0

I did not find a solution to overwrite the existing raster, but the time of making a new one was much faster than I expected. In this case it still required calling up the other bands and writing them back to new file. Here is what I used -

import rasterio as rio
import numpy as np

rasterin = "path_to_a_mutliband_raster"
rasterout = 'path_to_output_raster'

rast = rio.open(rasterin)
meta = rast.meta
bands = [x + 1 for x in list(range(rast.count))]
rast.close()
badbands = [7, 16, 25]

with rio.open(rasterout, 'w', **meta) as dst:
    with rio.open(rasterin) as src:
        for ID, b in enumerate(bands,1):
            if b in ndvibands:
                ndvi = src.read(b)
                ndvi[ndvi != 0] = 0
                dst.write(ndvi, ID)
            else:
                data = src.read(b)
                dst.write(data, ID)
dst.close

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.