由于 STL 文件中的三角面片信息是无序的,可能存在重复的顶点信息。因此,在读取 STL 文件时,需要对顶点信息进行去重处理,以避免在转换为 VTK 文件时出现错误。

以下是实现代码:

import numpy as np

# 读取 STL 文件,去除重复顶点信息,返回顶点坐标和面片索引
def read_stl_file(filename):
    vertices = []
    faces = []
    unique_vertices = {} # 用字典记录已经出现过的顶点
    
    with open(filename, 'r') as f:
        for line in f:
            tokens = line.strip().split()
            if len(tokens) > 0:
                if tokens[0] == 'vertex':
                    # 读取顶点坐标
                    x, y, z = float(tokens[1]), float(tokens[2]), float(tokens[3])
                    # 判断是否已经出现过该顶点
                    key = '{:.6f},{:.6f},{:.6f}'.format(x, y, z) # 保留6位小数
                    if key in unique_vertices:
                        vertex_index = unique_vertices[key]
                    else:
                        vertex_index = len(vertices)
                        unique_vertices[key] = vertex_index
                        vertices.append([x, y, z])
                    # 添加顶点索引
                    if len(faces) > 0 and len(faces[-1]) < 3:
                        faces[-1].append(vertex_index)
                    else:
                        faces.append([vertex_index])
                elif tokens[0] == 'endloop':
                    faces[-1] = tuple(faces[-1]) # 将面片索引转换为元组
    return np.array(vertices), np.array(faces)

# 保存 VTK 文件
def save_vtk_file(filename, vertices, faces):
    with open(filename, 'w') as f:
        # 写入文件头
        f.write('# vtk DataFile Version 3.0\n')
        f.write('vtk output\n')
        f.write('ASCII\n')
        f.write('DATASET POLYDATA\n')
        # 写入顶点信息
        f.write('POINTS {} float\n'.format(len(vertices)))
        for vertex in vertices:
            f.write('{:.6f} {:.6f} {:.6f}\n'.format(vertex[0], vertex[1], vertex[2]))
        # 写入面片信息
        f.write('POLYGONS {} {}\n'.format(len(faces), len(faces)*4))
        for face in faces:
            f.write('3 {} {} {}\n'.format(face[0], face[1], face[2]))

# 读取 STL 文件
vertices, faces = read_stl_file(r'C:\Users\13611\Desktop\人工智能实践4.24\STL-VTK\Bunny_STL.stl')
# 保存 VTK 文件
save_vtk_file('Bunny_VTK.vtk', vertices, faces)

在上述代码中,read_stl_file 函数用于读取 STL 文件并去除重复顶点信息,返回顶点坐标和面片索引。该函数中使用了一个字典 unique_vertices 来记录已经出现过的顶点,保证不会在顶点重复时重复添加顶点信息。

save_vtk_file 函数用于保存 VTK 文件,将顶点坐标和面片索引按照 VTK 文件格式写入到文件中。

最后,调用 read_stl_file 函数读取 STL 文件,再调用 save_vtk_file 函数保存为 VTK 文件,得到转换后的文件 Bunny_VTK.vtk

Python 实现 STL 文件去重顶点并转换为 VTK 文件

原文地址: http://www.cveoy.top/t/topic/nUYj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录