The following code should surround points with a smooth (splined) convex hull. However,…
- User
The following code should surround points with a smooth (splined) convex hull. However, sometimes the convex hull is smaller than the points and leaves points outside it. Fix to ensure the path surrounds all points and a bit more.def create_smooth_scaled_hull(points, scale_factor=1.2, smoothing=0.5, num_points=100, color=None): """ Create a smooth, scaled hull around a set of points. Parameters: points: array-like, shape (n, 2) The input points to create a hull around scale_factor: float How much to scale the hull (1.0 = original size) smoothing: float Controls the smoothness (0 = no smoothing, 1 = max smoothing) num_points: int Number of points to use for the smooth interpolation Returns: PathPatch: A matplotlib patch that can be added to an axis """ # Compute the convex hull hull = ConvexHull(points) hull_points = points[hull.vertices] # Close the hull by repeating the first point hull_points = np.vstack((hull_points, hull_points[0])) # Compute centroid for scaling centroid = np.mean(hull_points, axis=0) # Create a periodic interpolation of the hull points tck, u = splprep([hull_points[:, 0], hull_points[:, 1]], s=smoothing, per=True) # Generate more points along the smooth curve new_points = np.linspace(0, 1, num_points) smooth_points = np.array(splev(new_points, tck)).T # Scale the points around the centroid scaled_points = centroid + (smooth_points - centroid) * scale_factor # Create a matplotlib path for the smooth hull vertices = np.vstack((scaled_points, scaled_points[0])) # Close the path codes = [Path.MOVETO] + [Path.LINETO] *
(len(vertices) - 2) + [Path.CLOSEPOLY] path = Path(vertices, codes) return PathPatch(path, fill=True, alpha=0.5, color=color) Assistant
I'll help fix the code to ensure the convex hull properly surrounds all points with some margin. The main issue is that the smoothing process can sometimes cause the hull to shrink inward. Here's the corrected version: Fixed Smooth Scaled Hull FunctionCódigo Key improvements in this fixed version:
Pre-scaling before smoothing: The hull points are scaled before the smoothing operation to prevent the smoothing process from shrinking the hull too much. Adaptive scaling verification: The code now checks if all original points are inside the hull and adaptively increases the scale factor if needed. Better error handling: Added try-except block for the splprep operation with a fallback to simpler smoothing if the initial attempt fails. Input validation: Added check for minimum number of points needed for hull creation. More robust k parameter: The spline degree (k) is now limited based on the number of hull points.
To use this function: pythonimport matplotlib.pyplot as plt
Your points as numpy array of shape (n, 2)
points = np.array([[x1, y1], [x2, y2], ...])
Create figure and axis
fig, ax = plt.subplots()
- User
Isn't that an endless while loop? # Verify that all original points are inside the hull # If not, increase scale factor adaptively path = Path(smooth_points) while not all(path.contains_points(points)): # Increase scale factor by 5% scale_factor *= 1.05 # Rescale smooth points around centroid smooth_points = centroid + (smooth_points - centroid) * 1.05
Assistant
Ah yes, good catch! You're right - the current implementation creates a new Path on each iteration but doesn't update it inside the loop. Here's the corrected version: Fixed Smooth Scaled Hull FunctionCódigo The key changes are:
Added a maximum iteration limit to prevent infinite loops The Path is now recreated inside the loop with the updated smooth_points Added a warning if the maximum iterations are reached Removed the redundant scale_factor variable since we're directly scaling the smooth_points Close the path properly inside the loop for accurate point containment testing
This should now properly expand the hull until it contains all points, while ensuring the loop can't run forever. The 100-iteration limit should be more than enough since each iteration increases the scale by 5%, but you can adjust this value if needed.