How to view the slices of a 3d stl file separately in Python?

400 Views Asked by At

I am trying to load a stl file and trying to view the slices of the stl file. I have tried this:

import numpy as np
from stl import mesh
import matplotlib.pyplot as plt

Load the STL file

mesh_data = mesh.Mesh.from_file('MyStl.stl')

Define the slicing axis (X, Y, or Z)

slicing_axis = 'Y'  # Replace with the desired axis

Define the number of slices

num_slices = 10  # Adjust the number of slices as needed

Calculate the range along the slicing axis

axis_range = mesh_data.points[:, 2]  # Assuming Z-axis slicing

Create evenly spaced slice positions

slice_positions = np.linspace(min(axis_range), max(axis_range), num_slices)

Iterate through the slices and create 2D images

for i, slice_position in enumerate(slice_positions):
# Define a small tolerance for matching vertices
    tolerance = 1e-6

# Create a mask to extract the slice
    if slicing_axis == 'X':
       mask = np.isclose(mesh_data.points[:, 0], slice_position, atol=tolerance)
    elif slicing_axis == 'Y':
       mask = np.isclose(mesh_data.points[:, 1], slice_position, atol=tolerance)
    elif slicing_axis == 'Z':
       mask = np.isclose(mesh_data.points[:, 2], slice_position, atol=tolerance)

# Extract the vertices for the slice
    sliced_vertices = mesh_data.points[mask]

# Create a 2D plot of the slice (you can use any 2D plotting library)
    plt.figure()
    plt.scatter(sliced_vertices[:, 0], sliced_vertices[:, 1], s=1)
    plt.axis('equal')  # Ensure equal aspect ratio for the plot
    plt.title(f'Slice {i+1}')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()

I am getting the plots but not able to view any thing in the plots meaning I'm just getting empty plots.Help me in viewing the slices .Thanks in advance.

0

There are 0 best solutions below