Computational Geometry: Convex Hulls
The convex hull of a set of points is the smallest convex polygon that contains them all: imagine a rubber band snapped around nails in a board. Computing it is the "hello world" of computational geometry, the field that turns geometry into algorithms. This lesson builds it from one primitive, the orientation test, and implements Andrew's monotone chain algorithm in about fifteen lines.
The one primitive: orientation
Every decision in the algorithm is "do these three points turn left or right?", answered by the 2D cross product (introduced in collision geometry):
No angles, no square roots, no division: with integer coordinates the answer is exact. Good geometric algorithms are written so that this sign is the only thing they need to know.
Andrew's monotone chain
The idea: walk across the points from left to right and keep only the ones where the boundary turns the right way.
- Sort the points by (and by to break ties).
- Build the lower hull: go through the sorted points; before adding a point , pop the last point while the last two points and do not make a left turn (). A right turn means the middle point is inside the hull.
- Build the upper hull the same way, going through the points in reverse order.
- Join the two chains, dropping the duplicated end points.
sorted: (0,0) (1,1) (2,0) (2,2) (3,1) (4,0) …
lower: keep turning left along the bottom edge
upper: keep turning left along the top edge, walking back
result: counter-clockwise hull, starting at the leftmost pointEach point is pushed once and popped at most once per chain, so after sorting the work is linear. The total cost is , dominated by the sort (time complexity).
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def convex_hull(points):
pts = sorted(set(points))
if len(pts) <= 2:
return pts
lower = []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
pts = [(0, 0), (2, 0), (4, 0), (1, 1), (3, 1), (2, 2), (4, 3), (0, 4), (2, 5), (1, 3)]
print("hull:", convex_hull(pts))
print("orientation (0,0),(4,0),(4,3):", cross((0, 0), (4, 0), (4, 3)))
print("collinear (0,0),(2,0),(4,0):", cross((0, 0), (2, 0), (4, 0)))
print("square + centre:", convex_hull([(0, 0), (1, 0), (1, 1), (0, 1), (0.5, 0.5)]))hull: [(0, 0), (4, 0), (4, 3), (2, 5), (0, 4)]
orientation (0,0),(4,0),(4,3): 12
collinear (0,0),(2,0),(4,0): 0
square + centre: [(0, 0), (1, 0), (1, 1), (0, 1)]
The point lies on the bottom edge between and . Because the test pops on , collinear points are dropped and only true corners remain. Change <= 0 to < 0 to keep them (some applications want every point on the boundary).
Area and perimeter of the hull
Since the hull comes out in counter-clockwise order, the shoelace formula gives its area directly (positive for counter-clockwise vertices):
import math
import numpy as np
import matplotlib.pyplot as plt
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def convex_hull(points):
pts = sorted(set(points))
lower, upper = [], []
for chain, seq in ((lower, pts), (upper, reversed(pts))):
for p in seq:
while len(chain) >= 2 and cross(chain[-2], chain[-1], p) <= 0:
chain.pop()
chain.append(p)
return lower[:-1] + upper[:-1]
def shoelace(poly):
return sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(poly, poly[1:] + poly[:1])) / 2
rng = np.random.default_rng(7)
pts = [tuple(int(v) for v in p) for p in rng.integers(0, 50, size=(40, 2))]
hull = convex_hull(pts)
perimeter = sum(math.dist(a, b) for a, b in zip(hull, hull[1:] + hull[:1]))
print(len(set(pts)), "points,", len(hull), "on the hull")
print("hull area:", shoelace(hull), " perimeter:", round(perimeter, 3))
from scipy.spatial import ConvexHull
sp_hull = ConvexHull(np.array(pts))
print("SciPy: area", float(sp_hull.volume), " vertices", len(sp_hull.vertices))
fig, ax = plt.subplots(figsize=(5, 5))
xs, ys = zip(*pts); ax.plot(xs, ys, ".", color="gray")
hx, hy = zip(*(hull + hull[:1])); ax.plot(hx, hy, "-o", color="tab:blue")
ax.set_aspect("equal"); ax.set_title("convex hull (monotone chain)")40 points, 10 on the hull
hull area: 1988.5 perimeter: 167.811
SciPy: area 1988.5000000000002 vertices 10
SciPy agrees on the area (for 2D hulls SciPy calls the area volume; its area attribute is the perimeter). SciPy uses the Qhull library, which also does 3D and higher dimensions.
Tip: The integer coordinates make every
crossexact, and the area is a multiple of (Pick's theorem explains why). With float coordinates, near-collinear triples can get the wrong sign; production libraries use adaptive exact predicates for that.
In software
- Physics engines approximate a complex mesh by its convex hull, because collision tests between convex shapes are fast (SAT, GJK).
- Maps and GIS: the outline of a cluster of GPS points, "the area covered by our delivery drivers".
- Image processing: the hull of a shape's pixels measures how "solid" it is ().
- Algorithms: many problems (farthest pair of points, smallest enclosing rectangle) start by computing the hull, since the answer must lie on it.
Exercises
Exercise 1: Left or right?
Compute for , , . Does the path turn left or right?
Answer
: it turns left (counter-clockwise).
Solution
Positive means counter-clockwise. The triangle has area .
Exercise 2: Hull by hand
Find the convex hull of , , , , , , , listed counter-clockwise from the leftmost-lowest point.
Answer
, , , . The points and are inside, and lies on the right edge, so it is dropped as collinear.
Solution
The four corners of the square contain everything. For : , collinear, so the monotone chain pops it.
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def convex_hull(points):
pts = sorted(set(points))
lower, upper = [], []
for chain, seq in ((lower, pts), (upper, reversed(pts))):
for p in seq:
while len(chain) >= 2 and cross(chain[-2], chain[-1], p) <= 0:
chain.pop()
chain.append(p)
return lower[:-1] + upper[:-1]
print(convex_hull([(0, 0), (3, 0), (3, 3), (0, 3), (1, 2), (2, 1), (3, 1.5)]))[(0, 0), (3, 0), (3, 3), (0, 3)]
Exercise 3: Inside a convex polygon (code)
For a convex polygon in counter-clockwise order, a point is inside (or on the boundary) when for every edge. Write inside_convex(poly, p) and test it on the square , , , with the points , and .
Answer
True, False, True ( is on the right edge).
Solution
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def inside_convex(poly, p):
return all(cross(a, b, p) >= 0 for a, b in zip(poly, poly[1:] + poly[:1]))
square = [(0, 0), (4, 0), (4, 4), (0, 4)]
print([inside_convex(square, p) for p in [(2, 2), (5, 1), (4, 3)]])[True, False, True]
For the edge gives : the point is to the right of that edge, outside.
Exercise 4: Worst-case hull size
All points lie on a circle. How many of them are on the convex hull, and what is the running time of the monotone chain then?
Answer
All are on the hull; the running time is still (the sort), because no point is ever popped.
Solution
Every point on a circle is a corner of the convex polygon they form, so the hull has vertices. The chain loops are no matter how many points survive, since each point is pushed and popped at most once per chain. The sort dominates.
Test yourself
What does Andrew's algorithm do when the last two hull points and the new point make a right turn?
- It adds the new point and keeps going
- It pops the last hull point, because it lies inside
- It restarts the scan
- It reverses the chain
What is the time complexity of the monotone chain algorithm for points?
Why is the orientation test exact for integer coordinates?
- It uses only multiplication and subtraction of integers
- Python rounds the result
- It uses atan2
- Integers cannot be collinear