stl package

stl.Mesh

class stl.Mesh(*args: Any, **kwargs: Any)[source]

Bases: BaseStl

property areas

Mesh areas

property attr
property centroids

Mesh centroids

check(exact=False)

Check the mesh is valid or not

Parameters:

exact (bool) – Perform exact checks.

classmethod critical(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod debug(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
dtype = dtype([('normals', '<f4', (3,)), ('vectors', '<f4', (3, 3)), ('attr', '<u2', (1,))])
  • normals: numpy.float32(), (3, )

  • vectors: numpy.float32(), (3, 3)

  • attr: numpy.uint16(), (1, )

classmethod error(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod exception(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod from_3mf_file(filename, calculate_normals=True, **kwargs)
classmethod from_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load a mesh from a STL file

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_files(filenames, calculate_normals=True, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load multiple meshes from STL files into a single mesh

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filenames (list(str)) – The files to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_multi_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load multiple meshes from a STL file

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
get_header(name)
get_mass_properties()
Evaluate and return a tuple with the following elements:
  • the volume

  • the position of the center of gravity (COG)

  • the inertia matrix expressed at the COG

Documentation can be found here: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

get_mass_properties_with_density(density)
get_unit_normals()
classmethod info(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
is_closed(exact=False)

Check the mesh is closed or not

Parameters:

exact (bool) – Perform a exact check on edges.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
classmethod load(fh, mode=Mode.AUTOMATIC, speedups=True)

Load Mesh from STL file

Automatically detects binary versus ascii STL files.

Parameters:
  • fh (file) – The file handle to open

  • mode (int) – Automatically detect the filetype or force binary

classmethod log(level: int, msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
logger: logging.Logger = <Logger stl.base.BaseMesh (WARNING)>
property max_

Mesh maximum value

property min_

Mesh minimum value

property normals
property points
classmethod remove_duplicate_polygons(data, value=RemoveDuplicates.SINGLE)
classmethod remove_empty_areas(data)
rotate(axis, theta=0, point=None)

Rotate the matrix over the given axis by the given theta (angle)

Uses the rotation_matrix() in the background.

Note

Note that the point was accidentaly inverted with the old version of the code. To get the old and incorrect behaviour simply pass -point instead of point or -numpy.array(point) if you’re passing along an array.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

  • point (numpy.array) – Rotation point so manual translation is not required

rotate_using_matrix(rotation_matrix, point=None)

Rotate using a given rotation matrix and optional rotation point

Note that this rotation produces clockwise rotations for positive angles which is arguably incorrect but will remain for legacy reasons. For more details, read here: https://github.com/WoLpH/numpy-stl/issues/166

classmethod rotation_matrix(axis, theta)

Generate a rotation matrix to Rotate the matrix over the given axis by the given theta (angle)

Uses the Euler-Rodrigues formula for fast rotations.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

save(filename, fh=None, mode=Mode.AUTOMATIC, update_normals=True)

Save the STL to a (binary) file

If mode is AUTOMATIC an ASCII file will be written if the output is a TTY and a BINARY file otherwise.

Parameters:
  • filename (str) – The file to load

  • fh (file) – The file handle to open

  • mode (int) – The mode to write, default is AUTOMATIC.

  • update_normals (bool) – Whether to update the normals

transform(matrix)

Transform the mesh with a rotation and a translation stored in a single 4x4 matrix

Parameters:

matrix (numpy.array) – Transform matrix with shape (4, 4), where matrix[0:3, 0:3] represents the rotation part of the transformation matrix[0:3, 3] represents the translation part of the transformation

translate(translation)

Translate the mesh in the three directions

Parameters:

translation (numpy.array) – Translation vector (x, y, z)

property units

Mesh unit vectors

update_areas(normals=None)
update_centroids()
update_max()
update_min()
update_normals(update_areas=True, update_centroids=True)

Update the normals, areas, and centroids for all points

update_units()
property v0
property v1
property v2
values() an object providing a view on D's values
property vectors
classmethod warning(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
property x
property y
property z

stl.main module

stl.main.main()[source]
stl.main.to_ascii()[source]
stl.main.to_binary()[source]

stl.base module

stl.base.AREA_SIZE_THRESHOLD = 0

When removing empty areas, remove areas that are smaller than this

class stl.base.BaseMesh(*args: Any, **kwargs: Any)[source]

Bases: Logged, Mapping

Mesh object with easy access to the vectors through v0, v1 and v2. The normals, areas, min, max and units are calculated automatically.

Parameters:
  • data (numpy.array) – The data for this mesh

  • calculate_normals (bool) – Whether to calculate the normals

  • remove_empty_areas (bool) – Whether to remove triangles with 0 area (due to rounding errors for example)

Variables:
  • name (str) – Name of the solid, only exists in ASCII files

  • data (numpy.array) – Data as BaseMesh.dtype()

  • points (numpy.array) – All points (Nx9)

  • normals (numpy.array) – Normals for this mesh, calculated automatically by default (Nx3)

  • vectors (numpy.array) – Vectors in the mesh (Nx3x3)

  • attr (numpy.array) – Attributes per vector (used by binary STL)

  • x (numpy.array) – Points on the X axis by vertex (Nx3)

  • y (numpy.array) – Points on the Y axis by vertex (Nx3)

  • z (numpy.array) – Points on the Z axis by vertex (Nx3)

  • v0 (numpy.array) – Points in vector 0 (Nx3)

  • v1 (numpy.array) – Points in vector 1 (Nx3)

  • v2 (numpy.array) – Points in vector 2 (Nx3)

>>> data = np.zeros(10, dtype=BaseMesh.dtype)
>>> mesh = BaseMesh(data, remove_empty_areas=False)
>>> # Increment vector 0 item 0
>>> mesh.v0[0] += 1
>>> mesh.v1[0] += 2
>>> # Check item 0 (contains v0, v1 and v2)
>>> assert np.array_equal(
...     mesh[0], np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0])
... )
>>> assert np.array_equal(
...     mesh.vectors[0],
...     np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [0.0, 0.0, 0.0]]),
... )
>>> assert np.array_equal(mesh.v0[0], np.array([1.0, 1.0, 1.0]))
>>> assert np.array_equal(
...     mesh.points[0],
...     np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0]),
... )
>>> assert np.array_equal(
...     mesh.data[0],
...     np.array(
...         (
...             [0.0, 0.0, 0.0],
...             [[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [0.0, 0.0, 0.0]],
...             [0],
...         ),
...         dtype=BaseMesh.dtype,
...     ),
... )
>>> assert np.array_equal(mesh.x[0], np.array([1.0, 2.0, 0.0]))
>>> mesh[0] = 3
>>> assert np.array_equal(
...     mesh[0], np.array([3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0])
... )
>>> len(mesh) == len(list(mesh))
True
>>> bool((mesh.min_ < mesh.max_).all())
True
>>> mesh.update_normals()
>>> float(mesh.units.sum())
0.0
>>> mesh.v0[:] = mesh.v1[:] = mesh.v2[:] = 0
>>> float(mesh.points.sum())
0.0
>>> mesh.v0 = mesh.v1 = mesh.v2 = 0
>>> mesh.x = mesh.y = mesh.z = 0
>>> mesh.attr = 1
>>> bool((mesh.attr == 1).all())
True
>>> mesh.normals = 2
>>> bool((mesh.normals == 2).all())
True
>>> mesh.vectors = 3
>>> bool((mesh.vectors == 3).all())
True
>>> mesh.points = 4
>>> bool((mesh.points == 4).all())
True
property areas

Mesh areas

property attr
property centroids

Mesh centroids

check(exact=False)[source]

Check the mesh is valid or not

Parameters:

exact (bool) – Perform exact checks.

classmethod critical(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod debug(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
dtype = dtype([('normals', '<f4', (3,)), ('vectors', '<f4', (3, 3)), ('attr', '<u2', (1,))])
  • normals: numpy.float32(), (3, )

  • vectors: numpy.float32(), (3, 3)

  • attr: numpy.uint16(), (1, )

classmethod error(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod exception(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
get_mass_properties()[source]
Evaluate and return a tuple with the following elements:
  • the volume

  • the position of the center of gravity (COG)

  • the inertia matrix expressed at the COG

Documentation can be found here: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

get_mass_properties_with_density(density)[source]
get_unit_normals()[source]
classmethod info(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
is_closed(exact=False)[source]

Check the mesh is closed or not

Parameters:

exact (bool) – Perform a exact check on edges.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
classmethod log(level: int, msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
logger: Logger = <Logger stl.base.BaseMesh (WARNING)>
property max_

Mesh maximum value

property min_

Mesh minimum value

property normals
property points
classmethod remove_duplicate_polygons(data, value=RemoveDuplicates.SINGLE)[source]
classmethod remove_empty_areas(data)[source]
rotate(axis, theta=0, point=None)[source]

Rotate the matrix over the given axis by the given theta (angle)

Uses the rotation_matrix() in the background.

Note

Note that the point was accidentaly inverted with the old version of the code. To get the old and incorrect behaviour simply pass -point instead of point or -numpy.array(point) if you’re passing along an array.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

  • point (numpy.array) – Rotation point so manual translation is not required

rotate_using_matrix(rotation_matrix, point=None)[source]

Rotate using a given rotation matrix and optional rotation point

Note that this rotation produces clockwise rotations for positive angles which is arguably incorrect but will remain for legacy reasons. For more details, read here: https://github.com/WoLpH/numpy-stl/issues/166

classmethod rotation_matrix(axis, theta)[source]

Generate a rotation matrix to Rotate the matrix over the given axis by the given theta (angle)

Uses the Euler-Rodrigues formula for fast rotations.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

transform(matrix)[source]

Transform the mesh with a rotation and a translation stored in a single 4x4 matrix

Parameters:

matrix (numpy.array) – Transform matrix with shape (4, 4), where matrix[0:3, 0:3] represents the rotation part of the transformation matrix[0:3, 3] represents the translation part of the transformation

translate(translation)[source]

Translate the mesh in the three directions

Parameters:

translation (numpy.array) – Translation vector (x, y, z)

property units

Mesh unit vectors

update_areas(normals=None)[source]
update_centroids()[source]
update_max()[source]
update_min()[source]
update_normals(update_areas=True, update_centroids=True)[source]

Update the normals, areas, and centroids for all points

update_units()[source]
property v0
property v1
property v2
values() an object providing a view on D's values
property vectors
classmethod warning(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
property x
property y
property z
stl.base.DIMENSIONS = 3

Dimensions used in a vector

class stl.base.Dimension(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

X = 0

X index (for example, mesh.v0[0][X])

Y = 1

Y index (for example, mesh.v0[0][Y])

Z = 2

Z index (for example, mesh.v0[0][Z])

as_integer_ratio()

Return a pair of integers, whose ratio is equal to the original int.

The ratio is in lowest terms and has a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

is_integer()

Returns True. Exists for duck type compatibility with float.is_integer.

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class stl.base.RemoveDuplicates(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Choose whether to remove no duplicates, leave only a single of the duplicates or remove all duplicates (leaving holes).

ALL = 2
NONE = 0
SINGLE = 1
classmethod map(value)[source]
stl.base.VECTORS = 3

Vectors in a point

stl.base.logged(class_)[source]

stl.mesh module

class stl.mesh.Mesh(*args: Any, **kwargs: Any)[source]

Bases: BaseStl

property areas

Mesh areas

property attr
property centroids

Mesh centroids

check(exact=False)

Check the mesh is valid or not

Parameters:

exact (bool) – Perform exact checks.

classmethod critical(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod debug(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
dtype = dtype([('normals', '<f4', (3,)), ('vectors', '<f4', (3, 3)), ('attr', '<u2', (1,))])
  • normals: numpy.float32(), (3, )

  • vectors: numpy.float32(), (3, 3)

  • attr: numpy.uint16(), (1, )

classmethod error(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod exception(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod from_3mf_file(filename, calculate_normals=True, **kwargs)
classmethod from_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load a mesh from a STL file

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_files(filenames, calculate_normals=True, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load multiple meshes from STL files into a single mesh

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filenames (list(str)) – The files to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_multi_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load multiple meshes from a STL file

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
get_header(name)
get_mass_properties()
Evaluate and return a tuple with the following elements:
  • the volume

  • the position of the center of gravity (COG)

  • the inertia matrix expressed at the COG

Documentation can be found here: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

get_mass_properties_with_density(density)
get_unit_normals()
classmethod info(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
is_closed(exact=False)

Check the mesh is closed or not

Parameters:

exact (bool) – Perform a exact check on edges.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
classmethod load(fh, mode=Mode.AUTOMATIC, speedups=True)

Load Mesh from STL file

Automatically detects binary versus ascii STL files.

Parameters:
  • fh (file) – The file handle to open

  • mode (int) – Automatically detect the filetype or force binary

classmethod log(level: int, msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
logger: logging.Logger = <Logger stl.base.BaseMesh (WARNING)>
property max_

Mesh maximum value

property min_

Mesh minimum value

property normals
property points
classmethod remove_duplicate_polygons(data, value=RemoveDuplicates.SINGLE)
classmethod remove_empty_areas(data)
rotate(axis, theta=0, point=None)

Rotate the matrix over the given axis by the given theta (angle)

Uses the rotation_matrix() in the background.

Note

Note that the point was accidentaly inverted with the old version of the code. To get the old and incorrect behaviour simply pass -point instead of point or -numpy.array(point) if you’re passing along an array.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

  • point (numpy.array) – Rotation point so manual translation is not required

rotate_using_matrix(rotation_matrix, point=None)

Rotate using a given rotation matrix and optional rotation point

Note that this rotation produces clockwise rotations for positive angles which is arguably incorrect but will remain for legacy reasons. For more details, read here: https://github.com/WoLpH/numpy-stl/issues/166

classmethod rotation_matrix(axis, theta)

Generate a rotation matrix to Rotate the matrix over the given axis by the given theta (angle)

Uses the Euler-Rodrigues formula for fast rotations.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

save(filename, fh=None, mode=Mode.AUTOMATIC, update_normals=True)

Save the STL to a (binary) file

If mode is AUTOMATIC an ASCII file will be written if the output is a TTY and a BINARY file otherwise.

Parameters:
  • filename (str) – The file to load

  • fh (file) – The file handle to open

  • mode (int) – The mode to write, default is AUTOMATIC.

  • update_normals (bool) – Whether to update the normals

transform(matrix)

Transform the mesh with a rotation and a translation stored in a single 4x4 matrix

Parameters:

matrix (numpy.array) – Transform matrix with shape (4, 4), where matrix[0:3, 0:3] represents the rotation part of the transformation matrix[0:3, 3] represents the translation part of the transformation

translate(translation)

Translate the mesh in the three directions

Parameters:

translation (numpy.array) – Translation vector (x, y, z)

property units

Mesh unit vectors

update_areas(normals=None)
update_centroids()
update_max()
update_min()
update_normals(update_areas=True, update_centroids=True)

Update the normals, areas, and centroids for all points

update_units()
property v0
property v1
property v2
values() an object providing a view on D's values
property vectors
classmethod warning(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
property x
property y
property z

stl.stl module

stl.stl.BUFFER_SIZE = 4096

Amount of bytes to read while using buffered reading

class stl.stl.BaseStl(*args: Any, **kwargs: Any)[source]

Bases: BaseMesh

property areas

Mesh areas

property attr
property centroids

Mesh centroids

check(exact=False)

Check the mesh is valid or not

Parameters:

exact (bool) – Perform exact checks.

classmethod critical(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod debug(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
dtype = dtype([('normals', '<f4', (3,)), ('vectors', '<f4', (3, 3)), ('attr', '<u2', (1,))])
  • normals: numpy.float32(), (3, )

  • vectors: numpy.float32(), (3, 3)

  • attr: numpy.uint16(), (1, )

classmethod error(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod exception(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
classmethod from_3mf_file(filename, calculate_normals=True, **kwargs)[source]
classmethod from_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)[source]

Load a mesh from a STL file

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_files(filenames, calculate_normals=True, mode=Mode.AUTOMATIC, speedups=True, **kwargs)[source]

Load multiple meshes from STL files into a single mesh

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filenames (list(str)) – The files to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

classmethod from_multi_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)[source]

Load multiple meshes from a STL file

Note: mode is hardcoded to ascii since binary stl files do not support the multi format

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
get_header(name)[source]
get_mass_properties()
Evaluate and return a tuple with the following elements:
  • the volume

  • the position of the center of gravity (COG)

  • the inertia matrix expressed at the COG

Documentation can be found here: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

get_mass_properties_with_density(density)
get_unit_normals()
classmethod info(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
is_closed(exact=False)

Check the mesh is closed or not

Parameters:

exact (bool) – Perform a exact check on edges.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
classmethod load(fh, mode=Mode.AUTOMATIC, speedups=True)[source]

Load Mesh from STL file

Automatically detects binary versus ascii STL files.

Parameters:
  • fh (file) – The file handle to open

  • mode (int) – Automatically detect the filetype or force binary

classmethod log(level: int, msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
logger: logging.Logger = <Logger stl.base.BaseMesh (WARNING)>
property max_

Mesh maximum value

property min_

Mesh minimum value

property normals
property points
classmethod remove_duplicate_polygons(data, value=RemoveDuplicates.SINGLE)
classmethod remove_empty_areas(data)
rotate(axis, theta=0, point=None)

Rotate the matrix over the given axis by the given theta (angle)

Uses the rotation_matrix() in the background.

Note

Note that the point was accidentaly inverted with the old version of the code. To get the old and incorrect behaviour simply pass -point instead of point or -numpy.array(point) if you’re passing along an array.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

  • point (numpy.array) – Rotation point so manual translation is not required

rotate_using_matrix(rotation_matrix, point=None)

Rotate using a given rotation matrix and optional rotation point

Note that this rotation produces clockwise rotations for positive angles which is arguably incorrect but will remain for legacy reasons. For more details, read here: https://github.com/WoLpH/numpy-stl/issues/166

classmethod rotation_matrix(axis, theta)

Generate a rotation matrix to Rotate the matrix over the given axis by the given theta (angle)

Uses the Euler-Rodrigues formula for fast rotations.

Parameters:
  • axis (numpy.array) – Axis to rotate over (x, y, z)

  • theta (float) – Rotation angle in radians, use math.radians to convert degrees to radians if needed.

save(filename, fh=None, mode=Mode.AUTOMATIC, update_normals=True)[source]

Save the STL to a (binary) file

If mode is AUTOMATIC an ASCII file will be written if the output is a TTY and a BINARY file otherwise.

Parameters:
  • filename (str) – The file to load

  • fh (file) – The file handle to open

  • mode (int) – The mode to write, default is AUTOMATIC.

  • update_normals (bool) – Whether to update the normals

transform(matrix)

Transform the mesh with a rotation and a translation stored in a single 4x4 matrix

Parameters:

matrix (numpy.array) – Transform matrix with shape (4, 4), where matrix[0:3, 0:3] represents the rotation part of the transformation matrix[0:3, 3] represents the translation part of the transformation

translate(translation)

Translate the mesh in the three directions

Parameters:

translation (numpy.array) – Translation vector (x, y, z)

property units

Mesh unit vectors

update_areas(normals=None)
update_centroids()
update_max()
update_min()
update_normals(update_areas=True, update_centroids=True)

Update the normals, areas, and centroids for all points

update_units()
property v0
property v1
property v2
values() an object providing a view on D's values
property vectors
classmethod warning(msg: object, *args: object, exc_info: bool | Tuple[Type[BaseException], BaseException, TracebackType | None] | Tuple[None, None, None] | BaseException | None = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None) None
property x
property y
property z
stl.stl.COUNT_SIZE = 4

The amount of bytes in the count field

stl.stl.HEADER_FORMAT = '{package_name} ({version}) {now} {name}'

The header format, can be safely monkeypatched. Limited to 80 characters

stl.stl.HEADER_SIZE = 80

The amount of bytes in the header field

stl.stl.MAX_COUNT = 100000000.0

The maximum amount of triangles we can read from binary files

class stl.stl.Mode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

ASCII = 1

Force writing ASCII

AUTOMATIC = 0

Automatically detect whether the output is a TTY, if so, write ASCII otherwise write BINARY

BINARY = 2

Force writing BINARY

as_integer_ratio()

Return a pair of integers, whose ratio is equal to the original int.

The ratio is in lowest terms and has a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

is_integer()

Returns True. Exists for duck type compatibility with float.is_integer.

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

stl.stl.StlMesh(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs)

Load a mesh from a STL file

Parameters:
  • filename (str) – The file to load

  • calculate_normals (bool) – Whether to update the normals

  • fh (file) – The file handle to open

  • kwargs (dict) – The same as for stl.mesh.Mesh