I have a simple box (width: 400, lenght: 400, height: 50):
Here the code to create that box:
import numpy as np
import trimesh
# Vertices
vert = np.array([[-200., -200., 0.],
[-200., -200., 50.],
[-200., 200., 0.],
[-200., 200., 50.],
[ 200., -200., 0.],
[ 200., -200., 50.],
[ 200., 200., 0.],
[ 200., 200., 50.]])
# Faces
fa = np.array([[6, 0, 4],
[0, 6, 2],
[4, 6, 5],
[6, 7, 5],
[6, 2, 7],
[2, 3, 7],
[2, 0, 3],
[0, 1, 3],
[0, 4, 1],
[4, 5, 1],
[7, 1, 5],
[1, 7, 3]])
# MESH
mesh = trimesh.Trimesh(vertices= vert,
faces=fa)
The issue
As you can see, the top surface of the box is at z=0, and the lower surface is at z=50.
Now, I would expect to see this clearly, when I do a cross-section, using x as a normal:
# X - Normal => AXIS WRONG
slice_ = mesh.section(plane_origin=(0,0,0),
plane_normal=[1,0,0])
slice_2D, to_3D = slice_.to_planar()
slice_2D.show()
... but what I get is this:
You can clearly see that the box cross-section is not positioned correctly, as it should begin at z=0, and extend to z=50 (horizontal axis of the plot above).
Interestingly, getting cross-sections with z-normal works perfectly:
# Z - Normal => OK
slice_ = mesh.section(plane_origin=(0,0,0),
plane_normal=[0,0,1])
slice_2D, to_3D = slice_.to_planar()
slice_2D.show()
..if I ask for a cross-section at z=-10, where there should be no box, it rightfully complains.
# Z - Normal => OK
slice_ = mesh.section(plane_origin=(0,0,-10),
plane_normal=[0,0,1])
slice_2D, to_3D = slice_.to_planar()
slice_2D.show()
AttributeError: 'NoneType' object has no attribute 'to_planar'
How can I get the correct cross-section for the x-normal?
Edit
I also posted the question here: https://github.com/mikedh/trimesh/issues/1359
I think you need to specify the matrix explicitly when using to_planar, as if the matrix is unspecified the function has to fit a plane which may not be what you want.
Edit 2
Alternative: maybe one could rotate the mesh by 90 degrees around the x-axis and then do a z-cross, section. I tried that, but somehow it won't work:
from scipy.spatial.transform import Rotation as R
def rotate_vector(vec, rotation_degrees=90, rotation_axis = np.array([1, 0, 0])):
# Function that turns a vector a given angle about a given axis
rotation_radians = np.radians(rotation_degrees)
rotation_vector = rotation_radians * rotation_axis
rotation = R.from_rotvec(rotation_vector)
rotated_vec = rotation.apply(vec)
return rotated_vec
# Turn all vertices by 90deg around the x-axis
new_vert = []
for v in vert:
print(v)
print(rotate_vector(v))
new_vert.append(rotate_vector(v))
new_vert = []
for v in vert:
new_vert.append(rotate_vector(v))
# Create the mesh
mesh_rot = trimesh.Trimesh(vertices= new_vert,
faces=fa)
# Create a slice with a z-axis normal
slice_ = mesh_rot .section(plane_origin=(0,0,0),
plane_normal=[0,0,1.0])
slice_2D, to_3D = slice_.to_planar()
slice_2D.show()




