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, 2019 in Python by ana1504.k
• 7,910 points
5,550 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, 2019 by SDeb
• 13,300 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,440 points
1,339 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
1,314 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
• 58,020 points
1,619 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
1,780 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
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,300 points
1,628 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,300 points
759 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP