0

The shape of a shapely polygon can easily be converted to an array of points by using

x,y = polygon.exterior.xy

However, this returns only the actual points.

How can I convert a shapely polygon to an array, with a 0 for each pixel outside of the shape, and a 1 for each pixel inside the shape?

Thus, for an example, a polygon with width=100, height=100 should result in a (100,100) array.

I could do this by getting the exterior points, and then looping through each pixel and seeing if it's inside/on the shape, or outside. But I think there should be an easier method?

Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64
  • Does this answer your question? [SciPy Create 2D Polygon Mask](https://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask). This is not really related to Shapely. But if you have the coordinates of polygon's vertices, you could try the solutions provided by the link. My guess is that some of them will be faster than your solution below. – Georgy Sep 15 '20 at 16:16
  • Why do you need an array with ones and zeroes specifically? – Jann Poppinga Oct 02 '20 at 14:07

2 Answers2

1

I don't know about your exact requirement, but the fastest to get the general result should be this:

width = int(shape.bounds[2] - shape.bounds[0])
height = int(shape.bounds[3] - shape.bounds[1])
points = MultiPoint( [(x,y) for x in range(width) for y in range(height)] )
zeroes = points.difference( shape )
ones = points.intersection( shape )
Jann Poppinga
  • 444
  • 4
  • 18
0

This could answer my question, but I'm wondering if there is a faster way.

data = []

width = int(shape.bounds[2] - shape.bounds[0])
height = int(shape.bounds[3] - shape.bounds[1])

for y in range(0,height):
    row = []
    for x in range(0,width):
        val = 1 if shape.convex_hull.contains(Point(x,y)) else 0
        row.append(val)
    data.append(row)
Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64
  • Why are you using the convex hull? That does not correspond to your question. For speed, you should consider https://shapely.readthedocs.io/en/stable/manual.html#prepared-geometry-operations – Jann Poppinga Oct 02 '20 at 14:14