1

I've a raster GeoTIFF file (1000x1000x1) with one binary band (it's a mask taking either 0 or 255 as a value for each pixel). I' using rasterio to read it:

import rasterio
from rasterio.features import shapes

with rasterio.Env():
    with rasterio.open('file_geo.tif') as src:
        image = src.read_masks(1)
        results = ({
            'properties': {'raster_value': v}, 'geometry': s}
            for i, (s,v) in enumerate(
                shapes(
                    image,
                    mask=None,
                    transform=src.transform)
                 )
        )

I extracted the coordinates of each pixel center into a (1'000'000x2) array using np.meshgrid and the right Affine elements of src.meta, namely the translation and the pixel steps in both X and Y direction, which leads to e.g. :

points
array([[2238000.25, 1781999.75],
       [2238000.25, 1781999.25],
       [2238000.25, 1781998.75],
       ...

From that, how could I remove all "non-masked" pixels center coordinates in that list of points? Namely the points which are the center coordinates of any pixels with a value of 255 of the original raster?

I felt I'm on the wrong track for the moment.

1 Answer 1

1

You don't show how you're creating points, but you'll want that array to be the same shape as the raster's array so values in the same position will correspond to each other. Then you can create a boolean array from the raster mask and apply it to the points.

points = points.reshape((1000, 1000, 2))
mask = (image == 255)  # broadcasting, creates a boolean array
points_masked = points[mask]  # boolean indexing

https://numpy.org/doc/stable/user/basics.broadcasting.html https://numpy.org/doc/stable/user/basics.indexing.html#boolean-or-mask-index-arrays

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.