finding no data values inside the extent of a shapefile and discarding the values outside the extent

Viewed 13

I have Randolph Glacier Inventory boundary shapefiles of glaciers in Himachal Pradesh. I clipped three different rasters with these shapefiles, and then stacked them together . these clipped rasters contain no data values and I have to find the no data values and the pixel values inside these rasters . But when I am extracting the raster , the values am getting are more than that they should be . for example , the area of a glacier / shapefile is 8.719 km. sq and the resolution of raster is 10 sq.m so accordingly number of pixel in the raster should be 87190, but I am getting approx. 333233(that may be because of the bounding box). So, I decided to create a binary mask so that I can get the values inside the boundary of the raster but still I am getting a lot more values than 87190 . the stacked raster all have the same resolution and the same extent but still when I extract them and multiply the extracted array with the mask given below, the number of pixels extracted are different for two bands. the code i used for making the binary mask is given below . I want to write a code so that I can extract pixel values inside(only inside the boundary of the shapefile) the raster with the no data values present within them.

this is the mask I created this is the shapefile of the same glacier

from rasterio.plot import reshape_as_image
import rasterio.mask
from rasterio.features import rasterize
from shapely.geometry import mapping, Point, Polygon
from shapely.ops import cascaded_union
shape_path=  "E:\semester_4\glaciers of lahaul spiti clipped\RGIId_RGI60-14.11841/11841.shp"
glacier_df = gpd.read_file(shape_path)
raster_path =('E:/semester_4/glaciers of lahaul spiti clipped/RGIId_RGI60-14.11841/stack9/raster_stack_sv_srtm.tif')
with rasterio.open(raster_path , "r") as src:
raster_img = src.read()
raster_meta = src.meta
print("CRS Raster :{} , CRS Vector{}". format (glacier_df.crs , src.crs))
def poly_from_utm (polygon,transform):
poly_pts = []

poly = cascaded_union(polygon)
for i in np.array(poly.exterior.coords):
    
    poly_pts.append(~transform* tuple(i))
    
new_poly = Polygon(poly_pts)
return new_poly    
poly_shp  = []
im_size = (src.meta['height'] , src.meta['width'])
for num , row in glacier_df.iterrows():
   if row['geometry'].geom_type == 'Polygon':
      poly = poly_from_utm(row['geometry'] , src.meta['transform'])
      poly_shp.append(poly)
    
    else:
       for p in row['geometry']:
          poly= poly_from_utm (p , src.meta['transform'])
          poly_shp.append(poly)
        
 mask_stack_sv_srtm = rasterize(shapes = poly_shp , 
             out_shape = im_size)
 plt.figure(figsize = (5, 5))
 plt.imshow(mask_stack_sv_srtm)
0 Answers
Related