Computational geometry-convex hull algorithm python implementation and MATLAB animation demo

Source: Internet
Author: User

Convex hull algorithm is one of the most classical problems in computational geometry. Given a set of points, compute its convex hull. What is a convex bag, no more wordy.

This paper presents the Python implementation and MATLAB implementation of the convex hull algorithm in computational geometry-algorithm and application , and gives a matlab animation demonstration program.

Ah, realize who will come true ╮ ( ╯▽╰ ) ╭

Algorithm Convexhull (p) Input: Planar point set P output: A list of 1 of all vertices in CH (p) along a clockwise direction.   According to x-coordinate, all points are sorted to get sequence P1, ..., pn2. Add P1 and P2 (P1 in front) 3 in Lupper.   for (I←3 ton) 4.   Do add pi5 to the Lupper.   While (there are at least three points in the Lupper, and the three points at the very end are not a right turn) 6.   Do delete the second-to-last vertex from the Lupper 7. PN and Pn-1 (PN in front) 8 are added to the llower.   for (I←n-2 downto1) 9.    Do add pi10 to the Llower.    While (there are at least three points in the Llower, and the three points at the very end are not a right turn) 11.  Do delete the second-to-last vertex from the Llower 12.  Delete the first and last points from the llower (to prevent duplicate vertices from appearing after the upper and lower convex packets are joined) 13.  Join Llower to Lupper (the resulting list is recorded as L) 14. Return (L)

Look, not a lot of it.
There is only one point that needs to be explained, and that is the problem of direction determination.

There are three point p,q,r, now demand R is located on the left side of the vector PQ or on the right side (or R on the PQ).

Calculates the cross product of PR and PQ, which is the outer product.

If the vector PR is rotated with P as the center of rotation only the direction of the vector PQ passes through a positive angle (counterclockwise), meaning that r is on the right side of the PQ, and the outer product is positive at this point.

It is also important to note that if there is a three-point collinear on the convex hull, in this case three points are in the convex hull boundary point set. If you want to avoid this, you can solve this problem by using micro-jitter data.

Needless to say, Python implements the following:

1 #!/usr/bin/env python2 #CODING:GBK3  4 ########################################################################5 #Author:feng Ruohang6 #create:2014/10/02 13:397 #digest:computate The convex hull of a given point list8 ########################################################################9  Ten   OneDirection =LambdaM: (M[2][0]-m[0][0]) * (M[1][1]-m[0][1])-(m[1][0]-m[0][0]) * (M[2][1]-m[0][1]) A " " - A Quick side_check version Using LAMBDA expression - Input:given A list of three point:m should like [(P_x,p_y), (q_x,q_y), (r_x,r_y)] the Output:return A number to indicate whether R in the right side of vector (PQ). - Positive means R is on the right side of vector (PQ). - This is negative of the cross product of the PQ and pr:defined by: (QX-PX) (ry-py)-(RX-PX) (qy-py) - which ' negative ' indicate PR is clockwise to PQ, equivalent to R are on the right side of PQ + " " -   +   A defConvex_hull (point_list): at     " " - Input:given a point list:a List of Truple (x, y) - Output:return a point list:a list of truple (x, y) which is convex HULL of input - for the sake of effeciency, there are no error check mechanism here. Please catch outside -     " " -n = Len (point_list)#Total Length in Point_list.sort () -   to     #Valid Check: +     ifN < 3: -         returnpoint_list the   *     #Building Upper hull:initialized with first $Upper_hull = Point_list[0:1]Panax Notoginseng      forIinchRange (2, N): - upper_hull.append (Point_list[i]) the          whileLen (upper_hull) >= 3 and notDirection (upper_hull[-3:]): +             delUpper_hull[-2] A   the     #Building Lower hull:initialized with last +Lower_hull = [Point_list[-1], point_list[-2]] -      forIinchRange (n-3,-1,-1):#From the i-3th to the first point $ lower_hull.append (Point_list[i]) $          whileLen (lower_hull) >= 3 and notDirection (lower_hull[-3:]): -             delLower_hull[-2] -Upper_hull.extend (lower_hull[1:-1]) the     returnUpper_hull -  Wuyi   the #========unit Test: - if__name__=='__main__': WuTest_data = [(I, I * * 2) forIinchRange (1, 100)] -result =convex_hull (test_data) About     Printresult $  -January 23, 2015

The use is very simple, see docstring on the line.

The following gives the implementation of MATLAB, as well as the visualization of the algorithm demo:

The effect is a small animation, like this.

the convex hull algorithm for Matlab has three files:

Side_check2: Check the direction of the bending of three points

Convex_hull: convex packet Algorithm Matlab implementation

Convex_hull_demo: Presentation of the convex hull algorithm.

Copy it in a directory.

Run Convex_hull_demo (RANDN (200,2) *100); you'll see a visual presentation.

This is an auxiliary function.

%filename:side_check2.m%input:     Matrix of Three point: (2x3 or 3x2)%           P (p_x,p_y), Q (q_x,q_y), R (r_x,r_y)%output:    if P Q r three points make a right turn, returning true%           right means that point R is on the right side of the PQ vector. function result = Side_check2 (d) If all (size (d) ~= [3,2])    if all (Size (D) ==[2,3])        D = d ';    else        error (' Error dimension ')    Endendresult = (Det ([[1;1;1], D]) < 0);

This is a pure algorithm implementation.

%filename:     convex_hull.m%convex_hull%input: Point     Set: (n x 2)%ouput:     Hull point List: (x x 2) function l=t (P  [Num,dimension] = size (P), if dimension ~= 2    error (' Dimension error ') ENDP = Sortrows (p,[1,2]);%if there is only one or Remain,return itif num < 3     L = P;     return end%step One:upper hull:l_upper = P ([up],:);%take First and pointsfor i = 3:num    l_upper = [L_upper; P (i,:)]; %add the point to list     while size (l_upper,1) >= 3        l_size = size (l_upper,1);        If Det ([Ones (3,1), L_upper (L_size-2:l_size,:)]) = 3        l_size = size (l_lower,1);       If Det ([Ones (3,1), L_lower (L_size-2:l_size,:)])

This is a demo:

%convex_hull%input:point Set: (n x 2)%ouput:hull point List: (x x 2)%samples:convex_hull_demo (Randn (200,2) *10 0) function L=convex_hull_demo (P)%test data%data_size = data_size%p = Randi ([ -50,50],[data_size,2]); [Num,dimension] = size (P), if dimension ~= 2 error (' Dimension error ') ENDP = Sortrows (p,[1,2]);%====visual Lizationboard_ left = Min (P (:, 1)), board_right = Max (P (:, 1)), Board_bottom = Min (P (:, 2)), board_up = Max (P (:, 2)); x_padding = (board_right- Board_left) *0.1;y_padding = (board_up-board_bottom) *0.1;plot_range= [Board_left-x_padding,board_right + x_padding, Board_bottom-y_padding,board_up+y_padding];clf;scatter (P (:, 1), P (:, 2), ' B. '); axis (plot_range); hold on%==== Visuallization%if there is only one or both point Remain,return itif num < 3 L = P;end%step One:upper hull:l_upper = P ([up],:);%take First pointshull_handle = Plot (L_upper (:, 1), L_upper (:, 2), ' ob-'); for i = 3:num L_upper = [L_uppe R P (i,:)]; %add the point to list while size (l_upper,1) >=3 l_size = size (l_upper,1);  If Side_check2 (L_upper (l_size-2:l_size,:))%check If it is a valid break;        %quit if Valid else L_upper (l_size-1,:) = [];%remove the inner point and continue if not end            Set (Hull_handle, ' XData ', L_upper (:, 1), ' Ydata ', L_upper (:, 2));d Rawnow; End Set (Hull_handle, ' XData ', L_upper (:, 1), ' Ydata ', L_upper (:, 2));d rawnow;end%visualization plot (L_upper (:, 1), L_ Upper (:, 2), ' bo-'); %visualization%step Two:build the lower hulll_lower = [P ([num,num-1],:)];% Add P (n) and P (n-1) set (Hull_handle, ' XData ', L_lower (:, 1), ' Ydata ', L_lower (:, 2));d rawnow;for i = num-2:-1:1 l_lower = [L_lower;    P (i,:)];       While size (l_lower,1) >= 3 l_size = size (l_lower,1);  If Side_check2 (L_lower (l_size-2:l_size,:))%check If it is a valid break;           %quit if Valid else L_lower (l_size-1,:) = [];%remove the inner point and continue if not end Set (Hull_handle, ' XData ', L_lower (:, 1), ' Ydata ', L_lower (:, 2));d Rawnow; End Set (Hull_handle, ' XData ', L_lower (:, 1), ' Ydata ', L_lower (:, 2));d rawnow;endl_lower ([1,size (l_lower,1)],:) = [];if IsEmpty (l_lower) L = l_upper;else L = [L_upper; L_lower (2:size (l_lower,1)-1,:)];endhold Off;return

Computational geometry-convex hull algorithm python implementation and MATLAB animation demo

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.