python实现STL模型文件体积表面积计算

发布时间 2023-11-09 09:43:44作者: Solo李
没有什么特殊的算法,直接用包,开箱即用
from stl import mesh
import numpy as np

# 读取stl文件
filename = './text.stl'
mesh_data = mesh.Mesh.from_file(filename)

xyz = (mesh_data.max_ - mesh_data.min_)
sizel = round(xyz[0] / 10, 2)
sizew = round(xyz[1] / 10, 2)
sizeh = round(xyz[2] / 10, 2)

# 计算体积
volume, _, _ = mesh_data.get_mass_properties()

# 计算表面积
surface_area = 0.0
for triangle in mesh_data.vectors:
    # 获取三角形的三个顶点
    a = triangle[0]
    b = triangle[1]
    c = triangle[2]
    # 计算三角形的面积并累加
    surface_area += 0.5 * np.linalg.norm(np.cross(b - a, c - a))

print("Surface Area:", surface_area)

print("Volume:", volume)