TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Computational Geometry: Convex Hulls

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):

cross⁡(o,a,b)=(ax−ox)(by−oy)−(ay−oy)(bx−ox)>0o→a→b turns left (counter-clockwise)<0turns right (clockwise)=0collinear\begin{aligned} &\operatorname{cross}(o, a, b) = (a_x - o_x)(b_y - o_y) - (a_y - o_y)(b_x - o_x) \\ &\quad > 0 && o \to a \to b \text{ turns left (counter-clockwise)} \\ &\quad < 0 && \text{turns right (clockwise)} \\ &\quad = 0 && \text{collinear} \end{aligned}

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.

  1. Sort the points by xx (and by yy to break ties).
  2. Build the lower hull: go through the sorted points; before adding a point pp, pop the last point while the last two points and pp do not make a left turn (cross⁡≤0\operatorname{cross} \le 0). A right turn means the middle point is inside the hull.
  3. Build the upper hull the same way, going through the points in reverse order.
  4. Join the two chains, dropping the duplicated end points.
text
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 point

Each point is pushed once and popped at most once per chain, so after sorting the work is linear. The total cost is O(nlog⁡n)O(n \log n), dominated by the sort (time complexity).

python · try it yourself
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 (2,0)(2, 0) lies on the bottom edge between (0,0)(0, 0) and (4,0)(4, 0). Because the test pops on cross⁡≤0\operatorname{cross} \le 0, 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):

area=12⋅∑(xi⋅yi+1−xi+1⋅yi)(indices wrap around)\text{area} = \tfrac{1}{2} \cdot \sum (x_i \cdot y_{i+1} - x_{i+1} \cdot y_i) \qquad \text{(indices wrap around)}
python · try it yourself
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 cross exact, and the area is a multiple of 12\frac{1}{2} (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 (area/hull area\text{area} / \text{hull area}).
  • 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 cross⁡(o,a,b)\operatorname{cross}(o, a, b) for o=(1,1)o = (1, 1), a=(4,2)a = (4, 2), b=(2,5)b = (2, 5). Does the path o→a→bo \to a \to b turn left or right?

Answer

cross⁡=11>0\operatorname{cross} = 11 > 0: it turns left (counter-clockwise).

Solution
(ax−ox)(by−oy)−(ay−oy)(bx−ox)=(3)(4)−(1)(1)=12−1=11(a_x - o_x)(b_y - o_y) - (a_y - o_y)(b_x - o_x) = (3)(4) - (1)(1) = 12 - 1 = 11

Positive means counter-clockwise. The triangle o,a,bo, a, b has area 11/211/2.

Exercise 2: Hull by hand

Find the convex hull of (0,0)(0, 0), (3,0)(3, 0), (3,3)(3, 3), (0,3)(0, 3), (1,2)(1, 2), (2,1)(2, 1), (3,1.5)(3, 1.5), listed counter-clockwise from the leftmost-lowest point.

Answer

(0,0)(0, 0), (3,0)(3, 0), (3,3)(3, 3), (0,3)(0, 3). The points (1,2)(1, 2) and (2,1)(2, 1) are inside, and (3,1.5)(3, 1.5) lies on the right edge, so it is dropped as collinear.

Solution

The four corners of the square contain everything. For (3,1.5)(3, 1.5): cross⁡((3,0),(3,1.5),(3,3))=0⋅3−1.5⋅0=0\operatorname{cross}((3, 0), (3, 1.5), (3, 3)) = 0 \cdot 3 - 1.5 \cdot 0 = 0, collinear, so the monotone chain pops it.

python · try it yourself
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 cross⁡(vi,vi+1,p)≥0\operatorname{cross}(v_i, v_{i+1}, p) \ge 0 for every edge. Write inside_convex(poly, p) and test it on the square (0,0)(0, 0), (4,0)(4, 0), (4,4)(4, 4), (0,4)(0, 4) with the points (2,2)(2, 2), (5,1)(5, 1) and (4,3)(4, 3).

Answer

True, False, True ((4,3)(4, 3) is on the right edge).

Solution
python · try it yourself
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 (5,1)(5, 1) the edge (4,0)→(4,4)(4, 0) \to (4, 4) gives cross⁡=0⋅1−4⋅1=−4<0\operatorname{cross} = 0 \cdot 1 - 4 \cdot 1 = -4 < 0: the point is to the right of that edge, outside.

Exercise 4: Worst-case hull size

All nn 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 nn are on the hull; the running time is still O(nlog⁡n)O(n \log n) (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 nn vertices. The chain loops are O(n)O(n) 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?

  1. It adds the new point and keeps going
  2. It pops the last hull point, because it lies inside
  3. It restarts the scan
  4. It reverses the chain

What is the time complexity of the monotone chain algorithm for nn points?

  1. O(n)O(n)
  2. O(n2)O(n^2)
  3. O(nlog⁡n)O(n \log n)
  4. O(2n)O(2^n)

Why is the orientation test exact for integer coordinates?

  1. It uses only multiplication and subtraction of integers
  2. Python rounds the result
  3. It uses atan2
  4. Integers cannot be collinear