From d21870870bbe5f89bfce7bfd4f4b86adab14306d Mon Sep 17 00:00:00 2001 From: Pierre Manchon Date: Thu, 26 Aug 2021 15:10:37 +0200 Subject: [PATCH] Added the new get_value_from_coords() function to avoid duplicated code. --- INPMT/__utils/raster.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/INPMT/__utils/raster.py b/INPMT/__utils/raster.py index c6ca43e..2dc89c1 100644 --- a/INPMT/__utils/raster.py +++ b/INPMT/__utils/raster.py @@ -28,6 +28,8 @@ import rasterio.mask from rasterio.features import shapes +from geopandas import GeoDataFrame + from .utils import __count_values, __gather, format_dataset_output from .vector import __read_shapefile, intersect @@ -83,6 +85,18 @@ def get_pixel_count(dataset_path: AnyStr, band: SupportsInt) -> tuple[Any, Count return __dataset, __ctr +def get_value_from_coord(index: int, dataset: AnyStr, shapefile: GeoDataFrame) -> int: + with rasterio.open(dataset) as src: + x, y = list(shapefile.loc[index, 'geometry'].coords)[0] + # get pixel x+y of the coordinate + py, px = src.index(x, y) + # create 1x1px window of the pixel + window = rasterio.windows.Window(px - 1//2, py - 1//2, 1, 1) + # read rgb values of the window + value = src.read(window=window) + return value[0][0] + + def raster_crop( dataset: AnyStr, shapefile: AnyStr, processing: AnyStr, overwrite: bool = False ) -> AnyStr: @@ -191,7 +205,6 @@ def raster_stats( with rasterio.open(dataset) as ro: x = ro.read() x = x[x != ro.nodata] - # Divide by 10.000 because NDVI is usually between -1 and 1 and these values are between -10000 and 10000 return ( round(x.sum(), 3), round(x.min(), 3),