Skip to content

Instantly share code, notes, and snippets.

@antiface
Forked from adusak/polygon.py
Created August 6, 2016 13:59
Show Gist options
  • Select an option

  • Save antiface/6fba25e98b292e7e45b565114149bcc8 to your computer and use it in GitHub Desktop.

Select an option

Save antiface/6fba25e98b292e7e45b565114149bcc8 to your computer and use it in GitHub Desktop.
Generates bitmap polygon from points
from PIL import Image
from python.common import line as ln
def polygon(points):
# first lets convert the points to lines
lines = []
xmax = 0
ymax = 0
points.append(points[0])
for p in range(1, len(points)):
lines.append(ln.Line(points[p - 1][0], points[p - 1][1], points[p][0], points[p][1]))
x = points[p - 1][0]
y = points[p - 1][1]
xmax = max(x, xmax)
ymax = max(y, ymax)
im = Image.new("RGB", (xmax + 1, ymax + 1), (255, 255, 255))
for x in range(xmax):
for y in range(ymax):
ypoint = y
leftline = ln.Line(0, ypoint, x, ypoint)
intersectioncount = 0
for line in lines:
if ln.line_intersect(leftline, line) is not None:
intersectioncount += 1
if intersectioncount % 2 != 0:
im.putpixel((x, ypoint), (0, 0, 0))
im = im.rotate(180)
im = im.transpose(Image.FLIP_LEFT_RIGHT)
# im.save("polygon"+str(points)+".png")
im.show()
polygon([(10, 10), (180, 20), (160, 150), (100, 50), (20, 180)]) # Obr. 1
polygon([(10, 10), (180, 80), (160, 150), (130, 50), (20, 180)]) # Obr. 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment