在使用 Python 中的 CGAL(Computational Geometry Algorithms Library)库计算 alpha shape 时,遇到了问题。虽然遵循了相关示例和教程,但计算结果却与预期不符。
2. 解决方案
经过仔细排查,发现问题出在使用了错误的库版本上。具体来说,在代码中使用了 CGAL 的 5.1 版本,而示例中使用的是 4.12 版本。这两个版本的库在接口和功能上存在一些差异,导致了错误的结果。
为了解决这个问题,将 CGAL 库版本更新到 4.12,然后再次运行代码。这次,计算结果与预期的一致,成功获得了正确的 alpha shape。
以下是代码中需要修改的部分:
from CGAL.Alpha_shapes_2 import *
from CGAL.Triangulations_2 import Delaunay_triangulation_2
from CGAL.Kernel import *
将上述代码替换为:
from CGAL import Alpha_shapes_2, Delaunay_triangulation_2, Kernel
修改后,代码可以正常运行并获得正确的结果。
以下是完整的代码:
from CGAL import Alpha_shapes_2, Delaunay_triangulation_2, Kernel
from random import *
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import constants
def Point_2_str(self):
return "Point_2" + str((self.x(), self.y()))
# now we turn it into a member function
Point_2.__str__ = Point_2_str
def show_alpha_values(AS):
print("Alpha spectrum")
for alpha_value in AS.alpha:
print(alpha_value)
def read_points(file):
result = []
dataFile = open(file, 'r')
for i, line in enumerate(dataFile):
coordinateList = [float(x) for x in line.strip().split()]
for j in range(0, len(coordinateList), 2):
result.append(Kernel.Point_2(coordinateList[j], coordinateList[j + 1]))
dataFile.close()
return result
def getAlphaShape():
L = []
verbose = True
list_of_points = read_points(constants.PROJECT_PATH + '\\data\\clusters.txt')
a = Alpha_shapes_2.Alpha_shape_2()
a.make_alpha_shape(list_of_points)
a.set_mode(Alpha_shapes_2.Alpha_shape_2.Mode.REGULARIZED)
a.set_alpha(1000)
alpha_shape_edges = []
alpha_shape_vertices = []
for it in a.alpha_shape_edges:
alpha_shape_edges.append(a.segment(it))
for it in a.alpha_shape_vertices:
alpha_shape_vertices.append(it)
_showAlphaShape(list_of_points, alpha_shape_vertices)
print("alpha_shape_edges")
print(len(alpha_shape_edges))
print("alpha_shape_vertices")
print(len(alpha_shape_vertices))
print("Optimal alpha: ")
print(a.find_optimal_alpha(2).next())
def _showAlphaShape(points, vertices):
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.axis('equal')
axes.set_xlabel(r'$x (m)$')
axes.set_ylabel(r'$y (m)$')
axes.set_title(r'$\alpha$-shape of clusters')
# draw cluster points
x = [pt.x() for pt in points]
y = [pt.y() for pt in points]
axes.scatter(x, y, s=1)
# draw alpha shape
for i in range(len(vertices) - 1):
x1 = vertices[i].point()[0]
x2 = vertices[i + 1].point()[0]
y1 = vertices[i].point()[1]
y2 = vertices[i + 1].point()[1]
axes.plot([[x1, x2], [y1, y2]], color='b')
fontP = FontProperties()
fontP.set_size('7')
axes.legend(loc=3, prop=fontP)
fig.savefig(constants.PROJECT_PATH + '\\data\\1.svg')
希望以上的解答对您有所帮助。如果您还有其他问题,请随时提出。