Open In App

Convex Hull in Python

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling.

What is Convex Hull?

The convex hull of a set of points in a Euclidean space is the smallest convex polygon that encloses all of the points. In two dimensions (2D), the convex hull is a convex polygon, and in three dimensions (3D), it is a convex polyhedron.

Convex Hull using Divide and Conquer Algorithm:

Algorithm: Given the set of points for which we have to find the convex hull. Suppose we know the convex hull of the left half points and the right half points, then the problem now is to merge these two convex hulls and determine the convex hull for the complete set.

  • This can be done by finding the upper and lower tangent to the right and left convex hulls. This is illustrated here Tangents between two convex polygons Let the left convex hull be a and the right convex hull be b.
  • Then the lower and upper tangents are named as 1 and 2 respectively, as shown in the figure. Then the red outline shows the final convex hull.
  • Now the problem remains, how to find the convex hull for the left and right half. Now recursion comes into the picture, we divide the set of points until the number of points in the set is very small, say 5, and we can find the convex hull for these points by the brute algorithm.
  • The merging of these halves would result in the convex hull for the complete set of points. Note: We have used the brute algorithm to find the convex hull for a small number of points and it has a time complexity of O(N^3).
  • But some people suggest the following, the convex hull for 3 or fewer points is the complete set of points. This is correct but the problem comes when we try to merge a left convex hull of 2 points and right convex hull of 3 points, then the program gets trapped in an infinite loop in some special cases.
  • So, to get rid of this problem I directly found the convex hull for 5 or fewer points by O(N^3) algorithm, which is somewhat greater but does not affect the overall complexity of the algorithm.

Below is the implementation of the above approach:

Python3
# A divide and conquer program to find convex
# hull of a given set of points.
from functools import cmp_to_key
# stores the centre of polygon (It is made
# global because it is used in the bcompare function)
mid = [0, 0]
# determines the quadrant of the point
# (used in compare())
def quad(p):
    if p[0] >= 0 and p[1] >= 0:
        return 1
    if p[0] <= 0 and p[1] >= 0:
        return 2
    if p[0] <= 0 and p[1] <= 0:
        return 3
    return 4
# Checks whether the line is crossing the polygon
def orientation(a, b, c):
    res = (b[1]-a[1]) * (c[0]-b[0]) - (c[1]-b[1]) * (b[0]-a[0])
    if res == 0:
        return 0
    if res > 0:
        return 1
    return -1
# compare function for sorting
def compare(p1, q1):
    p = [p1[0]-mid[0], p1[1]-mid[1]]
    q = [q1[0]-mid[0], q1[1]-mid[1]]
    one = quad(p)
    two = quad(q)
    if one != two:
        if one < two:
            return -1
        return 1
    if p[1]*q[0] < q[1]*p[0]:
        return -1
    return 1
# Finds upper tangent of two polygons 'a' and 'b'
# represented as two vectors.
def merger(a, b):
    # n1 -> number of points in polygon a
    # n2 -> number of points in polygon b
    n1, n2 = len(a), len(b)
    ia, ib = 0, 0
    # ia -> rightmost point of a
    for i in range(1, n1):
        if a[i][0] > a[ia][0]:
            ia = i
    # ib -> leftmost point of b
    for i in range(1, n2):
        if b[i][0] < b[ib][0]:
            ib = i
    # finding the upper tangent
    inda, indb = ia, ib
    done = 0
    while not done:
        done = 1
        while orientation(b[indb], a[inda], a[(inda+1) % n1]) >= 0:
            inda = (inda + 1) % n1
        while orientation(a[inda], b[indb], b[(n2+indb-1) % n2]) <= 0:
            indb = (indb - 1) % n2
            done = 0
    uppera, upperb = inda, indb
    inda, indb = ia, ib
    done = 0
    g = 0
    while not done:  # finding the lower tangent
        done = 1
        while orientation(a[inda], b[indb], b[(indb+1) % n2]) >= 0:
            indb = (indb + 1) % n2
        while orientation(b[indb], a[inda], a[(n1+inda-1) % n1]) <= 0:
            inda = (inda - 1) % n1
            done = 0
    ret = []
    lowera, lowerb = inda, indb
    # ret contains the convex hull after merging the two convex hulls
    # with the points sorted in anti-clockwise order
    ind = uppera
    ret.append(a[uppera])
    while ind != lowera:
        ind = (ind+1) % n1
        ret.append(a[ind])
    ind = lowerb
    ret.append(b[lowerb])
    while ind != upperb:
        ind = (ind+1) % n2
        ret.append(b[ind])
    return ret
# Brute force algorithm to find convex hull for a set
# of less than 6 points
def bruteHull(a):
    # Take any pair of points from the set and check
    # whether it is the edge of the convex hull or not.
    # if all the remaining points are on the same side
    # of the line then the line is the edge of convex
    # hull otherwise not
    global mid
    s = set()
    for i in range(len(a)):
        for j in range(i+1, len(a)):
            x1, x2 = a[i][0], a[j][0]
            y1, y2 = a[i][1], a[j][1]
            a1, b1, c1 = y1-y2, x2-x1, x1*y2-y1*x2
            pos, neg = 0, 0
            for k in range(len(a)):
                if (k == i) or (k == j) or (a1*a[k][0]+b1*a[k][1]+c1 <= 0):
                    neg += 1
                if (k == i) or (k == j) or (a1*a[k][0]+b1*a[k][1]+c1 >= 0):
                    pos += 1
            if pos == len(a) or neg == len(a):
                s.add(tuple(a[i]))
                s.add(tuple(a[j]))
    ret = []
    for x in s:
        ret.append(list(x))
    # Sorting the points in the anti-clockwise order
    mid = [0, 0]
    n = len(ret)
    for i in range(n):
        mid[0] += ret[i][0]
        mid[1] += ret[i][1]
        ret[i][0] *= n
        ret[i][1] *= n
    ret = sorted(ret, key=cmp_to_key(compare))
    for i in range(n):
        ret[i] = [ret[i][0]/n, ret[i][1]/n]
    return ret
# Returns the convex hull for the given set of points
def divide(a):
    # If the number of points is less than 6 then the
    # function uses the brute algorithm to find the
    # convex hull
    if len(a) <= 5:
        return bruteHull(a)
    # left contains the left half points
    # right contains the right half points
    left, right = [], []
    start = int(len(a)/2)
    for i in range(start):
        left.append(a[i])
    for i in range(start, len(a)):
        right.append(a[i])
    # convex hull for the left and right sets
    left_hull = divide(left)
    right_hull = divide(right)
    # merging the convex hulls
    return merger(left_hull, right_hull)
# Driver Code
if __name__ == '__main__':
    a = []
    a.append([0, 0])
    a.append([1, -4])
    a.append([-1, -5])
    a.append([-5, -3])
    a.append([-3, -1])
    a.append([-1, -3])
    a.append([-2, -2])
    a.append([-1, -1])
    a.append([-2, -1])
    a.append([-1, 1])
    n = len(a)
    # sorting the set of the points according
    # to x-coordinate
    a.sort()
    ans = divide(a)
    print('Convex Hull:')
    for x in ans:
        print(int(x[0]), int(x[1]))

Output
Convex Hull:
-5 -3
-1 -5
1 -4
0 0
-1 1

Time Complexity: O(n * log n). 
Auxiliary Space: O(n)

Convex Hull using Jarvis’ Algorithm or Wrapping:

The idea of Jarvis’s Algorithm is simple, we start from the leftmost point (or point with minimum x coordinate value) and we keep wrapping points in counterclockwise direction.

The big question is, given a point p as current point, how to find the next point in output?

The idea is to use orientation() here. Next point is selected as the point that beats all other points at counterclockwise orientation, i.e., next point is q if for any other point r, we have “orientation(p, q, r) = counterclockwise”.

Algorithm:

  • Initialize p as leftmost point.
  • Do following while we don’t come back to the first (or leftmost) point.
    • The next point q is the point, such that the triplet (p, q, r) is counter clockwise for any other point r. To find this, we simply initialize q as next point, then we traverse through all points. For any point i, if i is more counter clockwise, i.e., orientation(p, i, q) is counter clockwise, then we update q as i. Our final value of q is going to be the most counter clockwise point.
    • next[p] = q (Store q as next of p in the output convex hull).
    • p = q (Set p as q for next iteration).

Below is the implementation of the above approach:

Python3
# code
print("GFG")
# Python3 program to find convex hull of a set of points. Refer 
# https://www.geeksforgeeks.org/orientation-3-ordered-points/
# for explanation of orientation()

# point class with x, y as point 
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def Left_index(points):
    
    '''
    Finding the left most point
    '''
    minn = 0
    for i in range(1,len(points)):
        if points[i].x < points[minn].x:
            minn = i
        elif points[i].x == points[minn].x:
            if points[i].y > points[minn].y:
                minn = i
    return minn

def orientation(p, q, r):
    '''
    To find orientation of ordered triplet (p, q, r). 
    The function returns following values 
    0 --> p, q and r are collinear 
    1 --> Clockwise 
    2 --> Counterclockwise 
    '''
    val = (q.y - p.y) * (r.x - q.x) - \
        (q.x - p.x) * (r.y - q.y)

    if val == 0:
        return 0
    elif val > 0:
        return 1
    else:
        return 2

def convexHull(points, n):
    
    # There must be at least 3 points 
    if n < 3:
        return

    # Find the leftmost point
    l = Left_index(points)

    hull = []
    
    '''
    Start from leftmost point, keep moving counterclockwise 
    until reach the start point again. This loop runs O(h) 
    times where h is number of points in result or output. 
    '''
    p = l
    q = 0
    while(True):
        
        # Add current point to result 
        hull.append(p)

        '''
        Search for a point 'q' such that orientation(p, q, 
        x) is counterclockwise for all points 'x'. The idea 
        is to keep track of last visited most counterclock- 
        wise point in q. If any point 'i' is more counterclock- 
        wise than q, then update q. 
        '''
        q = (p + 1) % n

        for i in range(n):
            
            # If i is more counterclockwise 
            # than current q, then update q 
            if(orientation(points[p], 
                        points[i], points[q]) == 2):
                q = i

        '''
        Now q is the most counterclockwise with respect to p 
        Set p as q for next iteration, so that q is added to 
        result 'hull' 
        '''
        p = q

        # While we don't come to first point
        if(p == l):
            break

    # Print Result 
    for each in hull:
        print(points[each].x, points[each].y)

# Driver Code
points = []
points.append(Point(0, 3))
points.append(Point(2, 2))
points.append(Point(1, 1))
points.append(Point(2, 1))
points.append(Point(3, 0))
points.append(Point(0, 0))
points.append(Point(3, 3))

convexHull(points, len(points))

# This code is contributed by 
# Akarsh Somani, IIIT Kalyani

Output
GFG
0 3
0 0
3 0
3 3

Time Complexity:  O(m * n), where n is number of input points and m is number of output or hull points (m <= n).  For every point on the hull we examine all the other points to determine the next point.
Auxiliary Space: O(n)

Convex Hull using Graham Scan:

Algorithm: Let points[0..n-1] be the input array. Then the algorithm can be divided into two phases:

Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process points be sorting them with respect to the bottom-most point. Once the points are sorted, they form a simple closed path (See the following diagram).

What should be the sorting criteria? computation of actual angles would be inefficient since trigonometric functions are not simple to evaluate. The idea is to use the orientation to compare angles without actually computing them (See the compare() function below)

Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to traverse the path and remove concave points on this path. How to decide which point to remove and which to keep? Again, orientation helps here. The first two points in sorted array are always part of Convex Hull. For remaining points, we keep track of recent three points, and find the angle formed by them. Let the three points be prev(p), curr(c) and next(n). If orientation of these points (considering them in same order) is not counterclockwise, we discard c, otherwise we keep it. Following diagram shows step by step process of this phase.

Below is the implementation of the above approach:

Python3
# A Python3 program to find convex hull of a set of points. Refer 
# https://www.geeksforgeeks.org/orientation-3-ordered-points/
# for explanation of orientation()

from functools import cmp_to_key

# A class used to store the x and y coordinates of points
class Point:
    def __init__(self, x = None, y = None):
        self.x = x
        self.y = y

# A global point needed for sorting points with reference
# to the first point
p0 = Point(0, 0)

# A utility function to find next to top in a stack
def nextToTop(S):
    return S[-2]

# A utility function to return square of distance
# between p1 and p2
def distSq(p1, p2):
    return ((p1.x - p2.x) * (p1.x - p2.x) +
            (p1.y - p2.y) * (p1.y - p2.y))

# To find orientation of ordered triplet (p, q, r).
# The function returns following values
# 0 --> p, q and r are collinear
# 1 --> Clockwise
# 2 --> Counterclockwise
def orientation(p, q, r):
    val = ((q.y - p.y) * (r.x - q.x) -
        (q.x - p.x) * (r.y - q.y))
    if val == 0:
        return 0 # collinear
    elif val > 0:
        return 1 # clock wise
    else:
        return 2 # counterclock wise

# A function used by cmp_to_key function to sort an array of
# points with respect to the first point
def compare(p1, p2):

    # Find orientation
    o = orientation(p0, p1, p2)
    if o == 0:
        if distSq(p0, p2) >= distSq(p0, p1):
            return -1
        else:
            return 1
    else:
        if o == 2:
            return -1
        else:
            return 1

# Prints convex hull of a set of n points.
def convexHull(points, n):

    # Find the bottommost point
    ymin = points[0].y
    min = 0
    for i in range(1, n):
        y = points[i].y

        # Pick the bottom-most or choose the left
        # most point in case of tie
        if ((y < ymin) or
            (ymin == y and points[i].x < points[min].x)):
            ymin = points[i].y
            min = i

    # Place the bottom-most point at first position
    points[0], points[min] = points[min], points[0]

    # Sort n-1 points with respect to the first point.
    # A point p1 comes before p2 in sorted output if p2
    # has larger polar angle (in counterclockwise
    # direction) than p1
    p0 = points[0]
    points = sorted(points, key=cmp_to_key(compare))

    # If two or more points make same angle with p0,
    # Remove all but the one that is farthest from p0
    # Remember that, in above sorting, our criteria was
    # to keep the farthest point at the end when more than
    # one points have same angle.
    m = 1 # Initialize size of modified array
    for i in range(1, n):
    
        # Keep removing i while angle of i and i+1 is same
        # with respect to p0
        while ((i < n - 1) and
        (orientation(p0, points[i], points[i + 1]) == 0)):
            i += 1

        points[m] = points[i]
        m += 1 # Update size of modified array

    # If modified array of points has less than 3 points,
    # convex hull is not possible
    if m < 3:
        return

    # Create an empty stack and push first three points
    # to it.
    S = []
    S.append(points[0])
    S.append(points[1])
    S.append(points[2])

    # Process remaining n-3 points
    for i in range(3, m):
    
        # Keep removing top while the angle formed by
        # points next-to-top, top, and points[i] makes
        # a non-left turn
        while ((len(S) > 1) and
        (orientation(nextToTop(S), S[-1], points[i]) != 2)):
            S.pop()
        S.append(points[i])

    # Now stack has the output points,
    # print contents of stack
    while S:
        p = S[-1]
        print("(" + str(p.x) + ", " + str(p.y) + ")")
        S.pop()

# Driver Code
input_points = [(0, 3), (1, 1), (2, 2), (4, 4),
                (0, 0), (1, 2), (3, 1), (3, 3)]
points = []
for point in input_points:
    points.append(Point(point[0], point[1]))
n = len(points)
convexHull(points, n)

# This code is contributed by Kevin Joshi

Output
(0, 3)
(4, 4)
(3, 1)
(0, 0)

Time Complexity: O(nLogn), where n be the number of input points.
Auxiliary Space: O(n)

Convex Hull | Monotone Chain Algorithm:

Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the clockwise direction and find the lower hull.

Below is the implementation of the above approach:

Python3
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

# A utility function to find next
# to top in a stack


def nextToTop(S):
    a = S.pop()
    b = S.pop()
    S.append(a)
    return b

# A utility function to swap two
# points


def swap(p1, p2):
    return p2, p1

# A utility function to return
# square of distance between
# two points


def distSq(p1, p2):
    return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)

# Prints convex hull of a set of n
# points.


def convexHull(points, n):

    # There must be at least 3 points
    if (n < 3):
        return

    # Initialize Result
    hull = []

    # Find the leftmost point
    l = 0
    for i in range(1, n):
        if (points[i].x < points[l].x):
            l = i

    # Start from leftmost point, keep
    # moving counterclockwise until
    # reach the start point again
    # This loop runs O(h) times where h is
    # number of points in result or output.
    p = l
    q = 0
    while (True):

        # Add current point to result
        hull.append(points[p])

        # Search for a point 'q' such that
        # orientation(p, x, q) is counterclockwise
        # for all points 'x'. The idea is to keep
        # track of last visited most counterclock-
        # wise point in q. If any point 'i' is more
        # counterclock-wise than q, then update q.
        q = (p + 1) % n

        for i in range(0, n):

            # If i is more counterclockwise than
            # current q, then update q
            if (orientation(points[p], points[i], points[q]) == 2):
                q = i

        # Now q is the most counterclockwise with
        # respect to p. Set p as q for next iteration,
        # so that q is added to result 'hull'
        p = q

        # While we don't come to first point
        if (p == l):
            break

    # Print Result
    printHull(hull)

# A utility function to return square
# of distance between p1 and p2


def distSq(p1, p2):
    return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)

# To find orientation of ordered triplet (p, q, r).
# The function returns following values
# 0 --> p, q and r are collinear
# 1 --> Clockwise
# 2 --> Counterclockwise


def orientation(p, q, r):
    val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)

    if (val == 0):
        return 0 # collinear
    elif (val > 0):
        return 1 # clock or wise
    else:
        return 2 # counterclock or wise

# Prints convex hull of a set of n points.


def printHull(hull):

    print("The points in Convex Hull are:")
    for i in range(len(hull)):
        print("(", hull[i].x, ", ", hull[i].y, ")")


# Driver Code
if __name__ == "__main__":

    points = []
    points.append(Point(0, 3))
    points.append(Point(2, 2))
    points.append(Point(1, 1))
    points.append(Point(2, 1))
    points.append(Point(3, 0))
    points.append(Point(0, 0))
    points.append(Point(3, 3))

    n = len(points)
    convexHull(points, n)

    # This code is contributed by ishankhandelwals.

Output
The points in Convex Hull are:
( 0 ,  3 )
( 0 ,  0 )
( 3 ,  0 )
( 3 ,  3 )

Time Complexity: O(n⋅h), where ℎh is typically proportional to 𝑛n in the worst case.
Auxiliary Space :O(n) 

Quickhull Algorithm for Convex Hull:

The QuickHull algorithm is a Divide and Conquer algorithm similar to QuickSort. Let a[0…n-1] be the input array of points. Following are the steps for finding the convex hull of these points.

Algorithm:

  • Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x.
  • Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further.
  • For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull.
  • The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull.

Below is the implementation of the above approach:

Python3
# python program to implement Quick Hull algorithm
# to find convex hull.

# Stores the result (points of convex hull)
hull = set()

# Returns the side of point p with respect to line
# joining points p1 and p2.
def findSide(p1, p2, p):
    val = (p[1] - p1[1]) * (p2[0] - p1[0]) - (p2[1] - p1[1]) * (p[0] - p1[0])

    if val > 0:
        return 1
    if val < 0:
        return -1
    return 0

# returns a value proportional to the distance
# between the point p and the line joining the
# points p1 and p2
def lineDist(p1, p2, p):
    return abs((p[1] - p1[1]) * (p2[0] - p1[0]) -
            (p2[1] - p1[1]) * (p[0] - p1[0]))

# End points of line L are p1 and p2. side can have value
# 1 or -1 specifying each of the parts made by the line L
def quickHull(a, n, p1, p2, side):

    ind = -1
    max_dist = 0

    # finding the point with maximum distance
    # from L and also on the specified side of L.
    for i in range(n):
        temp = lineDist(p1, p2, a[i])
        
        if (findSide(p1, p2, a[i]) == side) and (temp > max_dist):
            ind = i
            max_dist = temp

    # If no point is found, add the end points
    # of L to the convex hull.
    if ind == -1:
        hull.add("$".join(map(str, p1)))
        hull.add("$".join(map(str, p2)))
        return

    # Recur for the two parts divided by a[ind]
    quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2))
    quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1))

def printHull(a, n):
    # a[i].second -> y-coordinate of the ith point
    if (n < 3):
        print("Convex hull not possible")
        return

    # Finding the point with minimum and
    # maximum x-coordinate
    min_x = 0
    max_x = 0
    for i in range(1, n):
        if a[i][0] < a[min_x][0]:
            min_x = i
        if a[i][0] > a[max_x][0]:
            max_x = i

    # Recursively find convex hull points on
    # one side of line joining a[min_x] and
    # a[max_x]
    quickHull(a, n, a[min_x], a[max_x], 1)

    # Recursively find convex hull points on
    # other side of line joining a[min_x] and
    # a[max_x]
    quickHull(a, n, a[min_x], a[max_x], -1)

    print("The points in Convex Hull are:")
    
    for element in hull:
        x = element.split("$")
        print("(", x[0], ",", x[1], ") ", end = " ")

# Driver code
a = [[0, 3], [1, 1], [2, 2], [4, 4],
    [0, 0], [1, 2], [3, 1], [3, 3]]
n = len(a)
printHull(a, n)

# The code is contributed by Nidhi goel 

Output
The points in Convex Hull are:
( 4 , 4 )  ( 3 , 1 )  ( 0 , 0 )  ( 0 , 3 )  

Time Complexity: The analysis is similar to Quick Sort. On average, we get time complexity as O(n Log n), but in worst case, it can become O(n2)
Auxiliary Space :O(n) 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads