Polygons¶
scikit-geometry
can handle polygons, as well as polygons with holes. Polygons can be created from lists of points.
[1]:
import skgeom as sg
from skgeom.draw import draw
[2]:
poly = sg.Polygon([sg.Point2(0, 0), sg.Point2(0, 3), sg.Point2(3, 3)])
[3]:
draw(poly)
You may also use lists of coordinates or numpy arrays to construct polygons:
[4]:
sg.Polygon([[0, 0], [0, 3], [3, 3]])
Likewise, you can access a Polygon’s vertices as either a list of Point2
s or as a numpy array:
[5]:
list(poly.vertices)
[5]:
[PointC2(0, 0), PointC2(0, 3), PointC2(3, 3)]
[6]:
poly.coords
[6]:
array([[0., 0.],
[0., 3.],
[3., 3.]])
We can check wether a given point is inside the polygon (a negative sign means outside, positive means inside):
[7]:
poly.oriented_side(sg.Point2(1, 2))
[7]:
Sign.NEGATIVE
[8]:
poly.oriented_side(sg.Point2(2, 1))
[8]:
Sign.POSITIVE
Calculate the bounding box
[9]:
poly.bbox()
[9]:
Bbox_2(0, 0, 3, 3)
Compute the area of the polygon. Note: the sign depends on the order of the polygon (clockwise → negative, counter-clockwise → positive).
[10]:
poly.area()
[10]:
-4.5
[11]:
poly.orientation() == sg.Sign.CLOCKWISE
[11]:
True
[12]:
poly.is_convex()
[12]:
True
[13]:
poly.is_simple()
[13]:
True
Polygon with Holes¶
We can cut out an area of a Polygon by adding one or multiple holes.
[14]:
hole = sg.Polygon([
sg.Point2(1.0, 2.0),
sg.Point2(1.0, 2.5),
sg.Point2(0.5, 2.5),
sg.Point2(0.5, 2.0)]
)
poly_with_hole = sg.PolygonWithHoles(poly, [hole])
[15]:
draw(poly_with_hole)
Boolean operations on Polygons¶
scikit-geometry supports boolean operations on polygons, such as computing the union, difference and intersection between two polygons (or polygons with holes).
[16]:
poly1 = sg.Polygon([sg.Point2(3, 0), sg.Point2(3, 3), sg.Point2(0, 3), sg.Point2(0, 0)])
poly2 = sg.Polygon([sg.Point2(5, 2), sg.Point2(5, 5), sg.Point2(2, 5), sg.Point2(2, 2)])
[17]:
draw(poly1, facecolor='red')
draw(poly2, facecolor='blue')
[18]:
from skgeom import boolean_set
[19]:
draw(boolean_set.join(poly1, poly2))
[20]:
draw(boolean_set.difference(poly1, poly2))
[21]:
draw(boolean_set.symmetric_difference(poly1, poly2))
[22]:
draw(boolean_set.intersect(poly1, poly2))
Minkowski Sum of 2 Polygons¶
We can compute the minkowski sum of two polygons easily (i.e. offsetting a polygon with another polygon).
[23]:
from skgeom import minkowski
[24]:
p1 = sg.Polygon([sg.Point2(-1, -1), sg.Point2(1, -1), sg.Point2(0, 1)])
p2 = sg.Polygon([sg.Point2(3, -1), sg.Point2(5, -1), sg.Point2(5, 1), sg.Point2(3, 1)])
[25]:
draw(p1, facecolor='red')
draw(p2, facecolor='blue')
[26]:
result = minkowski.minkowski_sum(p1, p2)
draw(result)