Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SciPy Create 2D Polygon Mask

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?

like image 450
Isaac Sutherland Avatar asked Sep 06 '10 21:09

Isaac Sutherland


1 Answers

The answer turns out to be quite simple:

import numpy
from PIL import Image, ImageDraw

# polygon = [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]
# width = ?
# height = ?

img = Image.new('L', (width, height), 0)
ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1)
mask = numpy.array(img)
like image 108
Isaac Sutherland Avatar answered Oct 02 '22 07:10

Isaac Sutherland