SciPy Create 2D Polygon Mask

0 votes
I want 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)

 I also want to get the distance transform of this polygon using scipy.ndimage.morphology.distance_transform_edt.

Can anyone tell me how to accomplish this?
Apr 22 in Python by ana1504.k
• 7,870 points
381 views

1 answer to this question.

0 votes
You can try the following code:

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)
answered Apr 22 by SDeb
• 13,160 points

Related Questions In Python

+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
93 views
+2 votes
4 answers

python 2d array

You should make a list of lists, ...READ MORE

answered Oct 18, 2018 in Python by ritu
98 views
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 56,520 points
133 views
0 votes
1 answer

Create time lag in Python

import time time.sleep(10) READ MORE

answered May 2, 2018 in Python by Nietzsche's daemon
• 4,260 points
177 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 232 views
0 votes
1 answer

Create a nested directory in Python

Try os.path.exists, and consider os.makedirs for the ...READ MORE

answered Oct 16, 2018 in Python by SDeb
• 13,160 points
127 views
0 votes
1 answer

Create a GUID/UUID in Python

The uuid module, in Python 2.5 and ...READ MORE

answered Nov 22, 2018 in Python by SDeb
• 13,160 points
60 views