因为工作原因需要使用OCC库解析模型文件,分享下过程中遇到的知识点。
但是python OCC的资料比较少,所以一般只能参考下官方或者其他人的案例,然后浏览一些相关书籍。关于里面的API其实都可以查找OCC的C++网站查找,懂C++的很好看懂,不懂的也不会说特别难看懂,下面是API网站
OCC C++ API
好,直接进入正题,在上面那个网站搜索brep,stl,step都可以查找到对应的api。读取step的代码如下,执行函数后回直接返回一个TopoDS_Shape类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | def read_STEP_file(filename): """ read the STEP file and returns a compound """ # 生成一个step模型类 reader = STEPControl_Reader() # 加载一个文件并且返回一个状态枚举值 status = reader.ReadFile(filename) # 如果正常执行且有模型 if status == IFSelect_RetDone: # check status failsonly = False # 如果存在无效或者不完整步骤实体,会显示错误信息 reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) # 执行步骤文件转换 ok = reader.TransferRoot(1) # 返回生成形状的数量 _nbs = reader.NbShapes() # 返回转换后的形状 aResShape = reader.Shape(1) else: print("Error: can't read file.") sys.exit(0) return aResShape |
顺便说下C++头文件在python中怎么查找到对应的包,比如下面这个头文件
规则一般是 from OCC.Core.工具或图形类 import C++头文件
转换后就是下面这样,当然有些不是在Core里的,可以在上面那个网站总分类里查找到。
1 | from OCC.Core.TopoDS import TopoDS_Shape |
上面step其实可以直接用read_step_file返回shape的,不过上面的函数可验证性要好一点,我下面用比较简单的方法读取stl文件
1 2 3 4 5 6 | def read_STL_file(filename): shape = read_stl_file(filename); if not shape: print("Error:can't read file"); sys.exit(0); return shape; |
最后就是显示模型,可以直接用官方的简单版窗口
1 2 3 4 | display, start_display, add_menu, add_function_to_menu = init_display() shp = read_STL_file(filepath); #显示模型到界面上 display.DisplayShape(shp, update=True) |
最后再自己添加些功能就可以读取并显示模型了