flotzilla
flotzilla

Reputation: 1262

python: turn polygon into mask array

I have a polygon which I want to turn into a mask array, such that all points that fall inside/outside the polygon are True/False. I thought I found the perfect solution (SciPy Create 2D Polygon Mask), but for some reason this doesn't work!

What am I doing wrong?

#!/usr/bin/env python3

import numpy as np
import scipy as sp
from PIL import Image, ImageDraw

nx, ny = 10, 10

poly = np.array([(1, 1), (6, 2), (9, 9), (3, 7)])

img = Image.new("L", [nx, ny], 0)
ImageDraw.Draw(img).polygon(poly, outline=1, fill=1)
mask = np.array(img)

print(mask)
# [[1 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0]]

Broader context: I'm working with features of arbitrary shape on a rectangular grid. I have the indices of all boundary points on the grid, and I want the indices of a convex hull around this feature. scipy.spatial.ConvexHull(boundary_points) gives me the edge points of the convex hull, and it is this hull polygon that I now want to turn into a mask.

Upvotes: 4

Views: 7616

Answers (1)

user7138814
user7138814

Reputation: 2041

poly has to be a list of tuples or a flattened list. For some reason numpy arrays are handled badly. You can convert a polygon in a numpy array with poly.ravel().tolist() or with list(map(tuple, poly)).

Upvotes: 6

Related Questions