Topics

Rasterizing polygon from numpy arrays


alexisshakas@...
 

Hello,
I've been struggling with this for quite some time now, so its time to ask for help.

My problem is set up as follows:
I want to create a binary mask for an image that is quite large (~10k rows and 360 columns). I have several polygons, all closed, and I want to assign all values that fall in the polygons as True.
The polygons are in the form of a numpy array, with (x,y) coordinates. Each polygon has roughly 1000 values. I have about 200 such polygons for a given image.
Ideally, since the polygons are quite small, I should not query all points of the image (as suggested for example here https://stackoverflow.com/questions/36399381/whats-the-fastest-way-of-checking-if-a-point-is-inside-a-polygon-in-python)



I found documentation about how to rasterize shapefiles here https://rasterio.readthedocs.io/en/latest/api/rasterio.features.html
using for example
rasterio.features.geometry_mask(geometries, out_shape, transform, all_touched=False, invert=False)
but I could not figure out how to do this with a simple numpy array.

Is it possible?

I should also mention that my image axes are mixed. The vertical axis is a float (depths, from 0m to ~100m at 1 mm spacing) while the horizontal axis contains integers (angles, from 0 to 360 in 1 degree increments).

But I could also change these to be simply indices (both integers).

Thank you for any feedback!



Brendan Ward
 

You need to convert each polygon in your numpy array of coordinates into a GeoJSON-like polygon.

You could use Shapely to do so.

You should then be able to use those as input to rasterize or geometry_mask.  Note that your polygons must be in the coordinate system of your images in order for this to work.  Since it sounds like your x,y dimensions of your images are in integer degrees, this means your x,y coordinates must also be in degrees (vertical axis shouldn't matter for rasterize / geometry_mask).

Hope that helps!


alexisshakas@...
 

Hi Brendan and thnk you for the quick response!

The coordinates should not be an issue, since the polygon coordinates are in the same frame as the image.

Can i directly input a Shapely polygon to the geometry_mask class? I was a bit lost on whether this needs to be in some other format, like a sort of iterable dictionary.


Brendan Ward
 

Yes, you should be able to pass a list / tuple (these are iterables) of Shapely geometries as input to geometry_mask.


alexisshakas@...
 

Works like a charm, thank you!