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

  • 1
    getting NaN is easy just divide them by 0 or Inf
    – Ian Turton
    Jul 29 '20 at 16:20
  • 2
    What is your NoData value set to at the moment? What is the data type? Is it 8 bit 3 band? Was your original 8 bit 3 band or did it have a 4th band? What was the NoData value in the original? BTW NaN is not NoData, NaN is part of the complex floating point specification, it means Not a Number, complex float supports infinity, negative infinity and not a number values, simple floating points do not. NoData is a GIS concept used to make images transparent or to exclude from geoprocessing where cells have not been assigned a legitimate value. Jul 30 '20 at 1:36

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

    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


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

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.