我有以下函数以PLOT3D格式保存点云:
def write(filename, mesh):
"""
Write the mesh to filename in PLOT3D format.
filename: is the name of the output file.
mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point.
"""
points = mesh.points
imax = np.unique(points[:, 0]).size
jmax = np.unique(points[:, 1]).size
_2d = False
if points.shape[1] == 2:
_2d = True
elif np.unique(points[:, 2]).size == 1:
_2d = True
with open(filename, "w") as p3dfile:
if not _2d:
kmax = np.unique(points[:, 2]).size
print(imax, jmax, kmax, file=p3dfile)
for value in points.flatten(order="F"):
print(value, file=p3dfile)
else:
print(imax, jmax, file=p3dfile)
for value in points[:, 0:2].flatten(order="F"):
print(value, file=p3dfile)对于大量的点,这个函数非常慢。
我很感激任何关于改进上述代码的建议。
发布于 2019-11-19 21:33:17
表名
write太泛型了。更好的名字之一是write_points_2d。即使变量被标记为“受保护的”_...,以数字开头的名称也是错误的命名模式。因为它是布尔标志,所以有意义的名称应该是is_2dim (是二维空间)由于mesh参数只用于访问其内部属性points,所以最好直接传递目标点数据结构(称为参数替换查询)。
在当前的方法中,当到达条件if not _2d:时,将重复计算表达式np.unique(points[:, 2]).size,而不是:
由于points数组应该是带有2或3列的2d数组,所以我们可以一次收集所有列的唯一计数(而不是声明imax,jmax):
col_counts = [np.unique(row).size for row in points.T]整个条件:
_2d = False
if points.shape[1] == 2:
_2d = True
elif np.unique(points[:, 2]).size == 1:
_2d = True现在替换为一条语句:
is_2dim = points.shape[1] == 2 or col_counts[2] == 1在每次迭代时调用print函数将数据写入文件:
for value in points.flatten(order="F"):
print(value, file=p3dfile)与立即调用生成器表达式上的书面()相比,它的效率和性能肯定更低。
最后优化的函数:
def write_points(filename, points):
"""
Write the mesh points to filename in PLOT3D format.
filename: is the name of the output file.
mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point.
"""
col_counts = [np.unique(row).size for row in points.T]
is_2dim = points.shape[1] == 2 or col_counts[2] == 1
with open(filename, "w") as p3dfile:
pd3file.write(' '.join(map(str, col_counts)))
pd3file.writelines(f'{num}\n' for num in points.flatten(order="F"))https://codereview.stackexchange.com/questions/232648
复制相似问题