首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以PLOT3D格式保存点云

以PLOT3D格式保存点云
EN

Code Review用户
提问于 2019-11-19 16:49:15
回答 1查看 114关注 0票数 4

我有以下函数以PLOT3D格式保存点云:

代码语言:javascript
复制
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)

对于大量的点,这个函数非常慢。

我很感激任何关于改进上述代码的建议。

EN

回答 1

Code Review用户

回答已采纳

发布于 2019-11-19 21:33:17

Optimizations/improvements:

表名

  • 对于特定函数来说,write太泛型了。更好的名字之一是write_points
  • _2d。即使变量被标记为“受保护的”_...,以数字开头的名称也是错误的命名模式。因为它是布尔标志,所以有意义的名称应该是is_2dim (是二维空间)

由于mesh参数只用于访问其内部属性points,所以最好直接传递目标点数据结构(称为参数替换查询)。

在当前的方法中,当到达条件if not _2d:时,将重复计算表达式np.unique(points[:, 2]).size,而不是:

由于points数组应该是带有2或3列的2d数组,所以我们可以一次收集所有列的唯一计数(而不是声明imaxjmax):

代码语言:javascript
复制
col_counts = [np.unique(row).size for row in points.T]

整个条件:

代码语言:javascript
复制
_2d = False
if points.shape[1] == 2:
    _2d = True
elif np.unique(points[:, 2]).size == 1:
    _2d = True

现在替换为一条语句:

代码语言:javascript
复制
is_2dim = points.shape[1] == 2 or col_counts[2] == 1

在每次迭代时调用print函数将数据写入文件:

代码语言:javascript
复制
for value in points.flatten(order="F"):
    print(value, file=p3dfile)

与立即调用生成器表达式上的书面()相比,它的效率和性能肯定更低。

最后优化的函数:

代码语言:javascript
复制
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"))
票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/232648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档