Advertisement
WarPie90

Simple ConvexityDefects using concavehull

Oct 4th, 2023 (edited)
2,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 2.09 KB | None | 0 0
  1. type
  2.   EConvexityDefects = (cdNone, cdAll, cdMinimal);
  3.  
  4. (*
  5.   Finds the defects in relation to a convex hull of the given concave hull.
  6.   cdAll     -> Keeps all convex points as well.
  7.   cdMinimal -> keeps the convex points that was linked to a defect
  8.   cdNone    -> Only defects
  9. *)
  10. function ConvexityDefects(ConcavePoly: TPointArray; Epsilon: Single; Mode:EConvexityDefects=cdNone): TPointArray;
  11. var
  12.   x,y,i,j,k: Int32;
  13.   dist, best: Single;
  14.   pt: TPoint;
  15.   convex: TPointArray;
  16. begin
  17.   convex  := ConcavePoly.ConvexHull();
  18.  
  19.   for x:=0 to High(ConcavePoly) do
  20.   begin
  21.     i := convex.IndexOf(ConcavePoly[x]);
  22.  
  23.     if i <> -1 then
  24.     begin
  25.       j := (i+1) mod Length(convex);
  26.       y := ConcavePoly.IndexOf(convex[j]);
  27.  
  28.       best := 0;
  29.       for k:=y to x do
  30.       begin
  31.         dist := DistToLine(ConcavePoly[k], convex[i], convex[j]);
  32.         if (dist > best) then
  33.         begin
  34.           best := dist;
  35.           pt := ConcavePoly[k];
  36.         end;
  37.       end;
  38.  
  39.       if best >= Epsilon then
  40.       begin
  41.         if (Mode = cdMinimal) and ((Length(Result) = 0) or (Result[High(Result)] <> convex[j])) then Result += convex[j];
  42.         Result += pt;
  43.         if Mode = cdMinimal then Result += convex[i];
  44.       end;
  45.  
  46.       if Mode = cdAll then
  47.         Result += convex[i];
  48.     end;
  49.   end;
  50. end;
  51.  
  52.  
  53. // original simpler function returns only defects
  54. function ConvexityDefects(ConcavePoly: TPointArray; Epsilon: Single): TPointArray;
  55. var
  56.   x,y,i,j,k: Int32;
  57.   dist, best: Single;
  58.   pt: TPoint;
  59.   convex: TPointArray;
  60. begin
  61.   convex  := ConcavePoly.ConvexHull();
  62.  
  63.   for x:=0 to High(ConcavePoly) do
  64.   begin
  65.     i := convex.IndexOf(ConcavePoly[x]);
  66.  
  67.     if i <> -1 then
  68.     begin
  69.       j := (i+1) mod Length(convex);
  70.       y := ConcavePoly.IndexOf(convex[j]);
  71.  
  72.       best := 0;
  73.       for k:=y to x do
  74.       begin
  75.         dist := DistToLine(ConcavePoly[k], convex[i], convex[j]);
  76.         if (dist > best) then
  77.         begin
  78.           best := dist;
  79.           pt := ConcavePoly[k];
  80.         end;
  81.       end;
  82.  
  83.       if best >= Epsilon then Result += pt;
  84.     end;
  85.   end;
  86. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement