我有一个追踪非常清晰的几何形状的点样本。我正在努力恢复形状。我可以用简单的形状做到这一点,但我不能用更复杂的形状做到这一点。
这是我的尝试:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
# Define the size of the squares and the number of points
square_size = 3
num_points = 200
# Generate random points inside the first and second squares
square1_points = np.random.uniform(0, square_size, (num_points, 2))
square2_points = np.random.uniform(square_size - 1, 2 * square_size - 1, (num_points, 2))
# Combine the points from both squares
combined_points = np.vstack((square1_points, square2_points))
# Create a DataFrame
df_points = pd.DataFrame(combined_points, columns=['x', 'y'])
fig, ax = plt.subplots(figsize=(7, 7))
ax.grid(False)
ax.scatter(df_points['x'], df_points['y'], color='red')
# Compute and plot the convex hull
hull = ConvexHull(combined_points)
for simplex in hull.simplices:
ax.plot(combined_points[simplex, 0], combined_points[simplex, 1], 'b-', linewidth=4)
plt.show()
显然,蓝色轮廓并不遵循红点生成的轮廓。我该如何解决它?
在您的第一个示例中,蓝线正在按照您的要求进行操作,制作一个凸船体。如果蓝线“向内”移动以消除空白并更好地围绕点形成形状,则需要形状变为非凸面。
在这种情况下,为了实现您所描述的效果,您需要类似 alpha shape 的东西而不是凸包,alphashape 库为此提供了一个实现