0

I am trying to crop a raster but instead of just getting the values of the cropped raster I am trying to get the positions of that values on the matrix. I already did this with this code:

import geopandas
import rasterio
import rasterio.mask
import numpy as np

shp = gpd.read_file('myshapefile.shp')
with rasterio.open('mytif.tif') as src:
    mask_shp = [feature['geometry'] for feature in json.loads(shp.to_json())['features']]
    for index in range(len(mask_shp)):
        out_image, out_transform = rasterio.mask.mask(src, [mask_shp[index]], crop=False, nodata=np.nan)
        z,x,y = np.where(~np.isnan(out_image))
        #Some calculations using the positions of pixels inside the geometry

The problem with the code above is that it is very slow, the part which makes it slow is setting crop=False.

When I set crop=False the output dimension of cropped raster is the same as the original raster so I can calculate the positions of pixels inside polygon with np.where(~np.isnan(out_image))

But the difference of time when setting crop=False instead of crop=True is too high, I wonder if there is a better way to do it.

1 Answer 1

0

I found a way to do this faster. I created a temporal raster of the same size than the original but with different values, the value of each pixel is the position of that pixel. For example for a 10x10 raster:

0  1  2  ... 7  8  9
10 11 12 ... 17 18 19
         ...
80 81 82 ... 87 88 89
90 91 92 ... 97 98 99

Now If I crop this temporal raster even with the parameter crop=True I can get the pixel positions of the raster much faster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.