[GIS] How to convert 0 values to NoData values with rasterio

gdalpythonqgis-3rasterioshapefile

I clipped my TIFF image to smaller TIFF via using a shapefile as mask with rasterio Python library. After that my square shaped clip has bigger extent than shapefile and outside the the shapefile area is black and valued as 0. How can I change it to NODATA values?

enter image description here

Best Answer

You need to open the source file to read data values and metadata, then read the band data as numpy array, make the required changes to the numpy array and then save numpay array to a new dataset file:

source_raster_path = "example.tif"
distination_raster_path = "fixed_example.tif"
with rasterio.open(source_raster_path, "r+") as src:
    src.nodata = 0 # set the nodata value
    profile = src.profile
    profile.update(
            dtype=rasterio.uint8,
            compress='lzw'
    )

    with rasterio.open(distination_raster_path, 'w',  **profile) as dst:
        for i in range(1, src.count + 1):
            band = src.read(i)
            # band = np.where(band!=1,0,band) # if value is not equal to 1 assign no data value i.e. 0
            band = np.where(band==0,0,band) # for completeness
            dst.write(band,i)

References:

https://rasterio.groups.io/g/main/topic/change_the_nodata_value_in_a/28801885 https://rasterio.readthedocs.io/en/latest/topics/writing.html

Related Question