Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw polygons with Python?

I have input values of x, y coordinates in the following format:

[[1,1], [2,1], [2,2], [1,2], [0.5,1.5]] 

I want to draw polygons, but I don't know how to draw them!

Thanks

like image 233
W.Fan Avatar asked May 15 '17 03:05

W.Fan


People also ask

How do you draw a polygon with an image in Python?

polylines() method is used to draw a polygon on any image. Parameters: image: It is the image on which circle is to be drawn. pts: Array of polygonal curves.

How do I draw a polygon in Matplotlib?

import matplotlib. pyplot as plt coord = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]] coord. append(coord[0]) #repeat the first point to create a 'closed loop' xs, ys = zip(*coord) #create lists of x and y values plt. figure() plt.


2 Answers

Using matplotlib.pyplot

import matplotlib.pyplot as plt  coord = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]] coord.append(coord[0]) #repeat the first point to create a 'closed loop'  xs, ys = zip(*coord) #create lists of x and y values  plt.figure() plt.plot(xs,ys)  plt.show() # if you need... 
like image 117
Julien Avatar answered Sep 22 '22 01:09

Julien


Another way to draw a polygon is this:

import PIL.ImageDraw as ImageDraw import PIL.Image as Image  image = Image.new("RGB", (640, 480))  draw = ImageDraw.Draw(image)  # points = ((1,1), (2,1), (2,2), (1,2), (0.5,1.5)) points = ((100, 100), (200, 100), (200, 200), (100, 200), (50, 150)) draw.polygon((points), fill=200)  image.show() 

Note that you need to install the pillow library. Also, I scaled up your coordinates by the factor of 100 so that we can see the polygon on the 640 x 480 screen.

Hope this helps.

like image 35
Nurjan Avatar answered Sep 22 '22 01:09

Nurjan