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?
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)