0

I am trying to visualize slices of a stl file using matplotlib in python but receiving empty plots.

Here is the code.

z_min = np.min(your_mesh.vectors[:, :, 2])
z_max = np.max(your_mesh.vectors[:, :, 2])
num_slices = 10  # Number of slices

# Create an array of z-values for slicing
z_values = np.linspace(z_min, z_max, num_slices)

# Create a folder to store the sliced images
sliced_images_folder = "sliced_images"
if not os.path.exists(sliced_images_folder):
    os.mkdir(sliced_images_folder)

# Iterate through each slice
for i, z_value in enumerate(z_values):
    # Extract triangles that intersect with the current z-value
    triangles = your_mesh.vectors[(your_mesh.vectors[:, :, 2] >= z_value) &
                                  (your_mesh.vectors[:, :, 2] <= z_value + 0.01)]
    
    # Reshape the triangles array to (N, 3, 3)
    num_triangles = len(triangles)
    triangles = triangles.reshape(num_triangles, -1, 3)
    
    # Create a 3D plot for the current slice
    fig = plt.figure(figsize=(10, 6))
    ax = fig.add_subplot(111, projection='3d')

    # Set plot limits and labels
    ax.set_xlim(your_mesh.min_[0], your_mesh.max_[0])
    ax.set_ylim(your_mesh.min_[1], your_mesh.max_[1])
    ax.set_zlim(z_min, z_max)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    # Add the triangles to the plot
    ax.add_collection3d(mplot3d.art3d.Poly3DCollection(triangles))

    # Set title for the current slice
    ax.set_title(f"Slice at z = {z_value:.2f}")

    # Save the plot as an image
    image_file_name = f"sliced_images/{i:03d}.png"
    plt.savefig(image_file_name)
    plt.close(fig)

Here your_mesh contains the mesh read from the stl file. Slicing is done along z-axis. enter image description here Image contains the saved plot.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • Please try to create a minimal self-contained example. Replicate what an stl file may contain using raw numpy arrays. – Jody Klymak Sep 02 '23 at 17:31
  • Please review #3 of [Creating Effective Stack Overflow Questions](https://trenton3983.github.io/files/Creating_Effective_StackOverflow_Questions.html). If we can't copy, paste, and run, the code, then it is not a complete [mre]. – Trenton McKinney Sep 02 '23 at 17:48

0 Answers0