python3dmeshtrimesh

Saving cross section of 3d object by Trimesh - Python


After obtaining the cross section of a 3D object having sphere holes inside it as shown in the picture below, I couldn't find a way to save it as either numpy array or any image format. I used the Trimesh code below to take the section:

slice = tm_build.section(plane_origin=tm_build.centroid, 
                     plane_normal=[0,1,0])
slice_2D, to_3D = slice.to_planar()
slice_2D.show()

enter image description here


Solution

  • The following code snippet allows you to save your section as a png image file.

    import io
    
    import trimesh
    import PIL.Image as Image
    
    mesh_path = r"path\to\mesh"
    
    mesh = trimesh.load_mesh(mesh_path, process=False, maintain_order=True)
    section = mesh.section(plane_origin=[0, 0, 0], plane_normal=[0, 0, 1])
    section_2d, _ = section.to_planar()
    
    scene = section_2d.scene()
    bytes_ = scene.save_image()
    
    image = Image.open(io.BytesIO(bytes_))
    image.save(r"path\image.png")