I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages.
- input: polygon vertices, image dimensions
- output: binary mask of polygon (numpy 2D array)
(Larger context: I want to get the distance transform of this polygon using scipy.ndimage.morphology.distance_transform_edt.)
Can anyone show me how to do this?
An update on Joe's comment. Matplotlib API has changed since the comment was posted, and now you need to use a method provided by a submodule
matplotlib.path
.Working code is below.
As a slightly more direct alternative to @Anil's answer, matplotlib has
matplotlib.nxutils.points_inside_poly
that can be used to quickly rasterize an arbitrary polygon. E.g.Which yields (a boolean numpy array):
You should be able to pass
grid
to any of the scipy.ndimage.morphology functions quite nicely.You could try to use python's Image Library, PIL. First you initialize the canvas. Then you create a drawing object, and you start making lines. This is assuming that the polygon resides in R^2 and that the vertex list for the input are in the correct order.
Input = [(x1, y1), (x2, y2), ..., (xn, yn)] , (width, height)
Is this what you were looking for, or were you asking something different?
As a slightly alternative to @Yusuke N. answer by using
matplotlib.path
, just as efficient as the one byfrom PIL import Image, ImageDraw
(no need to installPillow
, ,no need to considerinteger
orfloat
. useful me, Ha?)working code is below:
And the result image is below, where dark area is
False
, bright area isTrue
.The answer turns out to be quite simple: