trimesh.voxel package

Submodules

trimesh.voxel.base module

voxel.py

Convert meshes to a simple voxel data structure and back again.

class trimesh.voxel.base.VoxelGrid(encoding, transform=None, metadata=None)

Bases: trimesh.parent.Geometry

Store 3D voxels.

apply_transform(matrix)
as_boxes(colors=None, **kwargs)

A rough Trimesh representation of the voxels with a box for each filled voxel.

Parameters

colors ((3,) or (4,) float or uint8) – (X, Y, Z, 3) or (X, Y, Z, 4) float or uint8 Where matrix.shape == (X, Y, Z)

Returns

mesh – Mesh with one box per filled cell.

Return type

trimesh.Trimesh

property bounds
copy()
crc()
property element_volume
property encoding

Encoding object providing the occupancy grid.

See trimesh.voxel.encoding for implementations.

property extents
fill(method='holes', **kwargs)

Mutates self by filling in the encoding according to morphology.fill.

Parameters
  • method (implementation key, one of) – trimesh.voxel.morphology.fill.fillers keys

  • **kwargs (additional kwargs passed to the keyed implementation) –

Returns

Return type

self after replacing encoding with a filled version.

property filled_count

int, number of occupied voxels in the grid.

hollow(structure=None)

Mutates self by removing internal voxels leaving only surface elements.

Surviving elements are those in encoding that are adjacent to an empty voxel, where adjacency is controlled by structure.

Parameters

structure (adjacency structure. If None, square connectivity is used.) –

Returns

Return type

self after replacing encoding with a surface version.

indices_to_points(indices)
property is_empty
is_filled(point)

Query points to see if the voxel cells they lie in are filled or not.

Parameters

point ((n, 3) float) – Points in space

Returns

is_filled – Is cell occupied or not for each point

Return type

(n,) bool

property marching_cubes

A marching cubes Trimesh representation of the voxels.

No effort was made to clean or smooth the result in any way; it is merely the result of applying the scikit-image measure.marching_cubes function to self.encoding.dense.

Returns

meshed – object, as returned by marching cubes algorithm.

Return type

Trimesh object representing the current voxel

property matrix

Return a DENSE matrix of the current voxel encoding

Returns

dense – Numpy array of dense matrix Shortcut to voxel.encoding.dense

Return type

(a, b, c) bool

md5()
property origin

Deprecated. Use self.translation.

property pitch

Uniform scaling factor representing the side length of each voxel.

Raises a RuntimeError if self.transformation has rotation or shear components of has non-uniform scaling.

property points

The center of each filled cell as a list of points.

Returns

points

Return type

(self.filled, 3) float, list of points

points_to_indices(points)

Convert points to indices in the matrix array.

Parameters

points ((n, 3) float, point in space) –

Returns

indices

Return type

(n, 3) int array of indices into self.encoding

revoxelized(shape)

Create a new VoxelGrid without rotations, reflections or shearing.

Parameters

shape (3-tuple of ints denoting the shape of the returned VoxelGrid.) –

Returns

  • VoxelGrid of the given shape with (possibly non-uniform) scale and

  • translation transformation matrix.

property scale

3-element float representing per-axis scale.

Raises a RuntimeError if self.transform has rotation or shear components.

property shape

3-tuple of ints denoting shape of occupancy grid.

show(*args, **kwargs)

Convert the current set of voxels into a trimesh for visualization and show that via its built- in preview method.

property sparse_indices

(n, 3) int array of sparse indices of occupied voxels.

strip()

Mutate self by stripping leading/trailing planes of zeros.

Returns

Return type

self after mutation occurs in-place

property transform

4x4 homogeneous transformation matrix.

property translation

Location of voxel at [0, 0, 0].

property volume

What is the volume of the filled cells in the current voxel object.

Returns

volume

Return type

float, volume of filled cells

trimesh.voxel.creation module

trimesh.voxel.creation.local_voxelize(mesh, point, pitch, radius, fill=True, **kwargs)

Voxelize a mesh in the region of a cube around a point. When fill=True, uses proximity.contains to fill the resulting voxels so may be meaningless for non-watertight meshes. Useful to reduce memory cost for small values of pitch as opposed to global voxelization.

Parameters
  • mesh (trimesh.Trimesh) – Source geometry

  • point ((3, ) float) – Point in space to voxelize around

  • pitch (float) – Side length of a single voxel cube

  • radius (int) – Number of voxel cubes to return in each direction.

  • kwargs (parameters to pass to voxelize_subdivide) –

Returns

voxels – or None if the volume is empty

Return type

VoxelGrid instance with resolution (m, m, m) where m=2*radius+1

trimesh.voxel.creation.voxelize(mesh, pitch, method='subdivide', **kwargs)

Voxelize the given mesh using the specified implementation.

See voxelizers for available implementations or to add your own, e.g. via voxelizers[‘custom_key’] = custom_fn.

custom_fn should have signature (mesh, pitch, **kwargs) -> VoxelGrid and should not modify encoding.

Parameters
  • mesh (Trimesh object (left unchanged)) –

  • pitch (float, side length of each voxel.) –

  • method (implementation method. Must be in fillers.) –

  • **kwargs (additional kwargs passed to the specified implementation.) –

Returns

Return type

A VoxelGrid instance.

trimesh.voxel.encoding module

OO interfaces to encodings for ND arrays which caching.

class trimesh.voxel.encoding.BinaryRunLengthEncoding(data)

Bases: trimesh.voxel.encoding.RunLengthEncoding

1D binary run length encoding.

See trimesh.voxel.runlength documentation for implementation details.

binary_run_length_data(dtype=<class 'numpy.int64'>)
copy()
property dense
static from_brle(brle_data, dtype=None)
static from_dense(dense_data, encoding_dtype=<class 'numpy.int64'>)
static from_rle(rle_data, dtype=None)
gather(indices)
gather_nd(indices)
property is_empty
mask(mask)
run_length_data(dtype=<class 'numpy.int64'>)
property size
sorted_gather(ordered_indices)
property sparse_components
property sparse_indices
property sparse_values
property stripped

Get encoding with all zeros stripped from the start and end of each axis.

Returns

  • encoding (?)

  • padding ((n, 2) int) – Padding at the start and end that was stripped

property sum
class trimesh.voxel.encoding.DenseEncoding(data)

Bases: trimesh.voxel.encoding.Encoding

Simple Encoding implementation based on a numpy ndarray.

copy()
property dense
property dtype
property flat
gather(indices)
gather_nd(indices)
get_value(index)
property is_empty
mask(mask)
reshape(shape)
property shape
property size
property sparse_components
property sparse_indices
property sparse_values
property sum
class trimesh.voxel.encoding.Encoding(data)

Bases: abc.ABC

Base class for objects that implement a specific subset of of ndarray ops.

This presents a unified interface for various different ways of encoding conceptually dense arrays and to interoperate between them.

Example implementations are ND sparse arrays, run length encoded arrays and dense encodings (wrappers around np.ndarrays).

binary_run_length_data(dtype=<class 'numpy.int64'>)
abstract copy()
crc()
property data
abstract property dense
abstract property dtype
property flat
flip(axis=0)
abstract gather_nd(indices)
abstract get_value(index)
property is_empty
abstract mask(mask)
md5()
property mutable
property ndims
reshape(shape)
run_length_data(dtype=<class 'numpy.int64'>)
abstract property shape
abstract property size
property sparse_components
abstract property sparse_indices
abstract property sparse_values
property stripped

Get encoding with all zeros stripped from the start and end of each axis.

Returns

  • encoding (?)

  • padding ((n, 2) int) – Padding at the start and end that was stripped

abstract property sum
transpose(perm)
class trimesh.voxel.encoding.FlattenedEncoding(data)

Bases: trimesh.voxel.encoding.LazyIndexMap

Lazily flattened encoding.

Dense equivalent is np.reshape(data, (-1,)) (np.flatten creates a copy).

copy()
property dense
property flat
mask(mask)
property shape
class trimesh.voxel.encoding.FlippedEncoding(encoding, axes)

Bases: trimesh.voxel.encoding.LazyIndexMap

Encoding with entries flipped along one or more axes.

Dense equivalent is np.flip

copy()
property dense
flip(axis=0)
mask(mask)
property shape
class trimesh.voxel.encoding.LazyIndexMap(data)

Bases: trimesh.voxel.encoding.Encoding

Abstract class for implementing lazy index mapping operations.

Implementations include transpose, flatten/reshaping and flipping

Derived classes must implement:
  • _to_base_indices(indices)

  • _from_base_indices(base_indices)

  • shape

  • dense

  • mask(mask)

property dtype
gather_nd(indices)
get_value(index)
property is_empty
property size
property sparse_indices
property sparse_values
property sum
class trimesh.voxel.encoding.RunLengthEncoding(data, dtype=None)

Bases: trimesh.voxel.encoding.Encoding

1D run length encoding.

See trimesh.voxel.runlength documentation for implementation details.

binary_run_length_data(dtype=<class 'numpy.int64'>)
copy()
crc()
property dense
property dtype
static from_brle(brle_data, dtype=None)
static from_dense(dense_data, dtype=<class 'numpy.int64'>, encoding_dtype=<class 'numpy.int64'>)
static from_rle(rle_data, dtype=None)
gather(indices)
gather_nd(indices)
get_value(index)
property is_empty
mask(mask)
md5()
property ndims
run_length_data(dtype=<class 'numpy.int64'>)
property shape
property size
sorted_gather(ordered_indices)
property sparse_components
property sparse_indices
property sparse_values
property stripped

Get encoding with all zeros stripped from the start and end of each axis.

Returns

  • encoding (?)

  • padding ((n, 2) int) – Padding at the start and end that was stripped

property sum
class trimesh.voxel.encoding.ShapedEncoding(encoding, shape)

Bases: trimesh.voxel.encoding.LazyIndexMap

Lazily reshaped encoding.

Numpy equivalent is np.reshape

copy()
property dense
property flat
mask(mask)
property shape
trimesh.voxel.encoding.SparseBinaryEncoding(indices, shape=None)

Convenient factory constructor for SparseEncodings with values all ones.

Parameters
  • indices ((m, n) sparse indices into conceptual rank-n array) –

  • shape (length n iterable or None. If None, maximum of indices along first) – axis + 1 is used

Returns

Return type

rank n bool SparseEncoding with True values at each index.

class trimesh.voxel.encoding.SparseEncoding(indices, values, shape=None)

Bases: trimesh.voxel.encoding.Encoding

Encoding implementation based on an ND sparse implementation.

Since the scipy.sparse implementations are for 2D arrays only, this implementation uses a single-column CSC matrix with index raveling/unraveling.

copy()
property dense
property dtype
static from_dense(dense_data)
gather_nd(indices)
get_value(index)
mask(mask)
property ndims
property shape
property size
property sparse_components
property sparse_indices
property sparse_values
property stripped

Get encoding with all zeros stripped from the start/end of each axis.

Returns

SparseEncoding with same values but indices shifted down

by padding[:, 0]

padding: (n, 2) array of ints denoting padding at the start/end

that was stripped

Return type

encoding

property sum
class trimesh.voxel.encoding.TransposedEncoding(base_encoding, perm)

Bases: trimesh.voxel.encoding.LazyIndexMap

Lazily transposed encoding

Dense equivalent is np.transpose

copy()
property data
property dense
gather(indices)
get_value(index)
mask(mask)
property perm
property shape
transpose(perm)

trimesh.voxel.morphology module

Basic morphology operations that create new encodings.

trimesh.voxel.morphology.binary_closing(encoding, **kwargs)

Encoding wrapper around scipy.ndimage.morphology.binary_closing.

https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.morphology.binary_closing.html#scipy.ndimage.morphology.binary_closing

trimesh.voxel.morphology.binary_dilation(encoding, **kwargs)

Encoding wrapper around scipy.ndimage.morphology.binary_dilation.

https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.morphology.binary_dilation.html#scipy.ndimage.morphology.binary_dilation

trimesh.voxel.morphology.fill(encoding, method='base', **kwargs)

Fill the given encoding using the specified implementation.

See fillers for available implementations or to add your own, e.g. via fillers[‘custom_key’] = custom_fn.

custom_fn should have signature (encoding, **kwargs) -> filled_encoding and should not modify encoding.

Parameters
  • encoding (Encoding object (left unchanged)) –

  • method (method present in fillers.) –

  • **kwargs (additional kwargs passed to the specified implementation.) –

Returns

Return type

A new filled Encoding object.

trimesh.voxel.morphology.surface(encoding, structure=None)

Get elements on the surface of encoding.

A surface element is any one in encoding that is adjacent to an empty voxel.

Parameters
  • encoding (Encoding or dense rank-3 array) –

  • structure (adjacency structure. If None, square connectivity is used.) –

Returns

Return type

new surface Encoding.

trimesh.voxel.ops module

trimesh.voxel.ops.boolean_sparse(a, b, operation=<ufunc 'logical_and'>)

Find common rows between two arrays very quickly using 3D boolean sparse matrices.

Parameters
  • a ((n, d) int, coordinates in space) –

  • b ((m, d) int, coordinates in space) –

  • operation (numpy operation function, ie:) – np.logical_and np.logical_or

Returns

coords

Return type

(q, d) int, coordinates in space

trimesh.voxel.ops.fill_base(sparse_indices)

Given a sparse surface voxelization, fill in between columns.

Parameters

sparse_indices ((n, 3) int, location of filled cells) –

Returns

filled

Return type

(m, 3) int, location of filled cells

trimesh.voxel.ops.fill_orthographic(dense)
trimesh.voxel.ops.fill_voxelization(sparse_indices)

Given a sparse surface voxelization, fill in between columns.

Parameters

sparse_indices ((n, 3) int, location of filled cells) –

Returns

filled

Return type

(m, 3) int, location of filled cells

trimesh.voxel.ops.indices_to_points(indices, pitch=None, origin=None)

Convert indices of an (n,m,p) matrix into a set of voxel center points.

Parameters
  • indices ((q, 3) int, index of voxel matrix (n,m,p)) –

  • pitch (float, what pitch was the voxel matrix computed with) –

  • origin ((3,) float, what is the origin of the voxel matrix) –

Returns

points

Return type

(q, 3) float, list of points

trimesh.voxel.ops.matrix_to_marching_cubes(matrix, pitch=1.0)

Convert an (n,m,p) matrix into a mesh, using marching_cubes.

Parameters

matrix ((n, m, p) bool) – Occupancy array

Returns

mesh – Mesh generated by meshing voxels using the marching cubes algorithm in skimage

Return type

trimesh.Trimesh

trimesh.voxel.ops.matrix_to_points(matrix, pitch=None, origin=None)

Convert an (n,m,p) matrix into a set of points for each voxel center.

Parameters
  • matrix ((n,m,p) bool, voxel matrix) –

  • pitch (float, what pitch was the voxel matrix computed with) –

  • origin ((3,) float, what is the origin of the voxel matrix) –

Returns

points

Return type

(q, 3) list of points

trimesh.voxel.ops.multibox(centers, colors=None)

Return a Trimesh object with a box at every center.

Doesn’t do anything nice or fancy.

Parameters
  • centers ((n,3) float, center of boxes that are occupied) –

  • pitch (float, the edge length of a voxel) –

  • colors ((3,) or (4,) or (n,3) or (n, 4) float, color of boxes) –

Returns

rough

Return type

Trimesh object representing inputs

trimesh.voxel.ops.points_to_indices(points, pitch=None, origin=None)

Convert center points of an (n,m,p) matrix into its indices.

Parameters
  • points ((q, 3) float) – Center points of voxel matrix (n,m,p)

  • pitch (float) – What pitch was the voxel matrix computed with

  • origin ((3,) float) – What is the origin of the voxel matrix

Returns

indices – List of indices

Return type

(q, 3) int

trimesh.voxel.ops.points_to_marching_cubes(points, pitch=1.0)

Mesh points by assuming they fill a voxel box, and then running marching cubes on them

Parameters

points ((n, 3) float) – Points in 3D space

Returns

mesh – Points meshed using marching cubes

Return type

trimesh.Trimesh

trimesh.voxel.ops.sparse_to_matrix(sparse)

Take a sparse (n,3) list of integer indexes of filled cells, turn it into a dense (m,o,p) matrix.

Parameters

sparse ((n, 3) int) – Index of filled cells

Returns

dense – Matrix of filled cells

Return type

(m, o, p) bool

trimesh.voxel.ops.strip_array(data)

trimesh.voxel.runlength module

Numpy encode/decode/utility implementations for run length encodings.

# Run Length Encoded Features

Encoding/decoding functions for run length encoded data.

We include code for two variations:

  • run length encoding (RLE)

  • binary run length encdoing (BRLE)

RLE stores sequences of repeated values as the value followed by its count, e.g.

`python dense_to_rle([5, 5, 3, 2, 2, 2, 2, 6]) == [5, 2, 3, 1, 2, 4, 6, 1] `

i.e. the value 5 is repeated 2 times, then 3 is repeated 1 time, 2 is repeated 4 times and 6 is repeated 1 time.

BRLE is an optimized form for when the stored values can only be 0 or 1. This means we only need to save the counts, and assume the values alternate (starting at 0).

`python dense_to_brle([1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) ==               [0, 2, 4, 7, 2] `

i.e. the value zero occurs 0 times, followed by 2 ones, 4 zeros, 7 ones and 2 zeros.

Sequences with counts exceeding the data type’s maximum value have to be handled carefully. For example, the uint8 encoding of 300 zeros (uint8 has a max value of 255) is:

  • RLE: [0, 255, 0, 45] (0 repeated 255 times + 0 repeated 45 times)

  • BRLE: [255, 0, 45, 0] (255 zeros + 0 ones + 45 zeros + 0 ones)

This module contains implementations of various RLE/BRLE operations.

trimesh.voxel.runlength.brle_gather_1d(brle_data, indices)

Gather BRLE data values at the provided dense indices.

This is equivalent to rle_to_dense(rle_data)[indices] but the implementation does not require the construction of the dense array.

If indices is known to be in order, use sorted_brle_gather_1d.

Parameters
  • rle_data (run length encoded data) –

  • indices (dense indices) –

Returns

  • numpy array, dense data at indices, same length as indices and dtype as

  • rle_data

trimesh.voxel.runlength.brle_gatherer_1d(indices)

Get a gather function at the given indices.

Because gathering on BRLE data requires sorting, for instances where gathering at the same indices on different RLE data this can save the sorting process.

If only gathering on a single RLE iterable, use brle_gather_1d.

Parameters

indices (iterable of integers) –

Returns

  • gather function, mapping (rle_data, dtype=None) -> values.

  • values will have the same length as indices and dtype provided,

  • or rle_data.dtype if no dtype is provided.

trimesh.voxel.runlength.brle_length(brle)

Optimized implementation of len(brle_to_dense(brle))

trimesh.voxel.runlength.brle_logical_not(brle)

Get the BRLE encoding of the logical_not`ed dense form of `brle.

Equivalent to dense_to_brle(np.logical_not(brle_to_dense(brle))) but highly optimized - just pads brle with a 0 on each end (or strips is existing endpoints are both zero).

Parameters

brle (rank 1 int array of binary run length encoded data) –

Returns

  • rank 1 int array of binary run length encoded data corresponding to

  • element-wise not of the input.

trimesh.voxel.runlength.brle_mask(rle_data, mask)

Perform masking of the input binary run-length data.

Parameters
  • brle_data (iterable of binary run length encoded data) –

  • mask (iterable of bools corresponding to the dense mask.) –

Returns

Return type

iterable dense values of brle_data wherever mask is True.

trimesh.voxel.runlength.brle_reverse(brle_data)

Equivalent to dense_to_brle(brle_to_dense(brle_data)[-1::-1]).

trimesh.voxel.runlength.brle_strip(brle_data)

Remove leading and trailing zeros.

Parameters

brle_data (binary run length encoded data.) –

Returns

  • (stripped_brle_data, padding)

  • stripped_brle_data (rle data without any leading or trailing zeros)

  • padding (2-element dense padding)

trimesh.voxel.runlength.brle_to_brle(brle, dtype=<class 'numpy.int64'>)

Almost the identity function.

Checks for possible merges and required splits.

trimesh.voxel.runlength.brle_to_dense(brle_data, vals=None)

Decode binary run length encoded data to dense.

Parameters
  • brle_data (BRLE counts of False/True values) –

  • vals (if not None, a length 2 array/list/tuple with False/True substitute) – values, e.g. brle_to_dense([2, 3, 1, 0], [7, 9]) == [7, 7, 9, 9, 9, 7]

Returns

Return type

rank 1 dense data of dtype bool if vals is None else vals.dtype

Raises

ValueError if vals it not None and shape is not (2,)

trimesh.voxel.runlength.brle_to_rle(brle, dtype=<class 'numpy.int64'>)
trimesh.voxel.runlength.brle_to_sparse(brle_data, dtype=<class 'numpy.int64'>)
trimesh.voxel.runlength.dense_to_brle(dense_data, dtype=<class 'numpy.int64'>)

Get the binary run length encoding of dense_data.

Parameters
  • dense_data (rank 1 bool array of data to encode.) –

  • dtype (numpy int type.) –

Returns

Return type

Binary run length encoded rank 1 array of dtype dtype.

Raises

ValuError if dense_data is not a rank 1 bool array.

trimesh.voxel.runlength.dense_to_rle(dense_data, dtype=<class 'numpy.int64'>)

Get run length encoding of the provided dense data.

trimesh.voxel.runlength.merge_brle_lengths(lengths)

Inverse of split_long_brle_lengths.

trimesh.voxel.runlength.merge_rle_lengths(values, lengths)

Inverse of split_long_rle_lengths except returns normal python lists.

trimesh.voxel.runlength.rle_gather_1d(rle_data, indices, dtype=None)

Gather RLE data values at the provided dense indices.

This is equivalent to rle_to_dense(rle_data)[indices] but the implementation does not require the construction of the dense array.

If indices is known to be in order, use sorted_gather_1d.

Parameters
  • rle_data (run length encoded data) –

  • indices (dense indices) –

  • dtype (numpy dtype. If not provided, uses rle_data.dtype) –

Returns

  • numpy array, dense data at indices, same length as indices and dtype as

  • rle_data

trimesh.voxel.runlength.rle_gatherer_1d(indices)

Get a gather function at the given indices.

Because gathering on RLE data requires sorting, for instances where gathering at the same indices on different RLE data this can save the sorting process.

If only gathering on a single RLE iterable, use rle_gather_1d.

Parameters

indices (iterable of integers) –

Returns

  • gather function, mapping (rle_data, dtype=None) -> values.

  • values will have the same length as indices and dtype provided,

  • or rle_data.dtype if no dtype is provided.

trimesh.voxel.runlength.rle_length(rle)

Optimized implementation of len(rle_to_dense(rle_to_brle(rle)))

trimesh.voxel.runlength.rle_mask(rle_data, mask)

Perform masking of the input run-length data.

Parameters
  • rle_data (iterable of run length encoded data) –

  • mask (iterable of bools corresponding to the dense mask.) –

Returns

Return type

iterable of dense values of rle_data wherever mask is True.

trimesh.voxel.runlength.rle_reverse(rle_data)

Get the rle encoding of the reversed dense array.

trimesh.voxel.runlength.rle_strip(rle_data)

Remove leading and trailing zeros.

Parameters

rle_data (run length encoded data) –

Returns

stripped_rle_data: rle data without any leading or trailing zeros padding: 2-element dense padding

Return type

(stripped_rle_data, padding)

trimesh.voxel.runlength.rle_to_brle(rle, dtype=None)

Convert run length encoded (RLE) value/counts to BRLE.

RLE data is stored in a rank 1 array with each pair giving: (value, count)

e.g. the RLE encoding of [4, 4, 4, 1, 1, 6] is [4, 3, 1, 2, 6, 1].

Parameters

rle ((n,) int) – Run length encoded data

Returns

otherwise brle_to_brle is called on that list before returning.

Return type

equivalent binary run length encoding. a list if dtype is None,

Raises

ValueError – If any of the even counts of rle are not zero or 1.

trimesh.voxel.runlength.rle_to_dense(rle_data, dtype=<class 'numpy.int64'>)

Get the dense decoding of the associated run length encoded data.

trimesh.voxel.runlength.rle_to_rle(rle, dtype=<class 'numpy.int64'>)

Almost the identity function.

Checks for possible merges and required splits.

trimesh.voxel.runlength.rle_to_sparse(rle_data)

Get dense indices associated with non-zeros.

trimesh.voxel.runlength.sorted_brle_gather_1d(brle_data, ordered_indices)

Gather brle_data at ordered_indices.

This is equivalent to brle_to_dense(brle_data)[ordered_indices] but avoids the decoding.

Parameters
  • raw_data (iterable of run-length-encoded data.) –

  • ordered_indices (iterable of ints in ascending order.) –

Returns

  • raw_data iterable of values at the dense indices, same length as

  • ordered indices.

trimesh.voxel.runlength.sorted_rle_gather_1d(rle_data, ordered_indices)

Gather brle_data at ordered_indices.

This is equivalent to rle_to_dense(brle_data)[ordered_indices] but avoids the decoding.

Parameters
  • brle_data (iterable of run-length-encoded data.) –

  • ordered_indices (iterable of ints in ascending order.) –

Returns

  • brle_data iterable of values at the dense indices, same length as

  • ordered indices.

trimesh.voxel.runlength.split_long_brle_lengths(lengths, dtype=<class 'numpy.int64'>)

Split lengths that exceed max dtype value.

Lengths l are converted into [max_val, 0] * l // max_val + [l % max_val]

e.g. for dtype=np.uint8 (max_value == 255) ` split_long_brle_lengths([600, 300, 2, 6], np.uint8) ==              [255, 0, 255, 0, 90, 255, 0, 45, 2, 6] `

trimesh.voxel.runlength.split_long_rle_lengths(values, lengths, dtype=<class 'numpy.int64'>)

Split long lengths in the associated run length encoding.

e.g. `python split_long_rle_lengths([5, 300, 2, 12], np.uint8) == [5, 255, 5, 45, 2, 12] `

Parameters
  • values (values column of run length encoding, or rle[::2]) –

  • lengths (counts in run length encoding, or rle[1::2]) –

  • dtype (numpy data type indicating the maximum value.) –

Returns

  • values, lengths associated with the appropriate splits. lengths will be

  • of type dtype, while values will be the same as the value passed in.

trimesh.voxel.transforms module

class trimesh.voxel.transforms.Transform(matrix)

Bases: object

Class for caching metadata associated with 4x4 transformations.

The transformation matrix is used to define relevant properties for the voxels, including pitch and origin.

apply_scale(scale)

Mutate the transform in-place and return self.

apply_transform(matrix)

Mutate the transform in-place and return self.

apply_translation(translation)

Mutate the transform in-place and return self.

copy()
crc()

Get the zlib.adler32 hash of the current transformation matrix.

Returns

crc – Hash of transformation matrix

Return type

str

property inverse_matrix
inverse_transform_points(points)

Apply the inverse transformation to points (not in-place).

property is_identity

Flags this transformation being sufficiently close to eye(4).

property matrix

Get the homogeneous transformation matrix.

Returns

matrix – Transformation matrix

Return type

(4, 4) float

md5()

Get the MD5 hash of the current transformation matrix.

Returns

md5 – Hash of transformation matrix

Return type

str

property pitch
property scale

Get the scale factor of the current transformation.

Returns

scale – Scale factor from the matrix

Return type

(3,) float

transform_points(points)

Apply the transformation to points (not in-place).

Parameters

points ((n, 3) float) – Points in cartesian space

Returns

transformed – Points transformed by matrix

Return type

(n, 3) float

property translation

Get the translation component of the matrix

Returns

translation – Cartesian translation

Return type

(3,) float

property unit_volume

Volume of a transformed unit cube.

Module contents

class trimesh.voxel.VoxelGrid(encoding, transform=None, metadata=None)

Bases: trimesh.parent.Geometry

Store 3D voxels.

apply_transform(matrix)
as_boxes(colors=None, **kwargs)

A rough Trimesh representation of the voxels with a box for each filled voxel.

Parameters

colors ((3,) or (4,) float or uint8) – (X, Y, Z, 3) or (X, Y, Z, 4) float or uint8 Where matrix.shape == (X, Y, Z)

Returns

mesh – Mesh with one box per filled cell.

Return type

trimesh.Trimesh

property bounds
copy()
crc()
property element_volume
property encoding

Encoding object providing the occupancy grid.

See trimesh.voxel.encoding for implementations.

property extents
fill(method='holes', **kwargs)

Mutates self by filling in the encoding according to morphology.fill.

Parameters
  • method (implementation key, one of) – trimesh.voxel.morphology.fill.fillers keys

  • **kwargs (additional kwargs passed to the keyed implementation) –

Returns

Return type

self after replacing encoding with a filled version.

property filled_count

int, number of occupied voxels in the grid.

hollow(structure=None)

Mutates self by removing internal voxels leaving only surface elements.

Surviving elements are those in encoding that are adjacent to an empty voxel, where adjacency is controlled by structure.

Parameters

structure (adjacency structure. If None, square connectivity is used.) –

Returns

Return type

self after replacing encoding with a surface version.

indices_to_points(indices)
property is_empty
is_filled(point)

Query points to see if the voxel cells they lie in are filled or not.

Parameters

point ((n, 3) float) – Points in space

Returns

is_filled – Is cell occupied or not for each point

Return type

(n,) bool

property marching_cubes

A marching cubes Trimesh representation of the voxels.

No effort was made to clean or smooth the result in any way; it is merely the result of applying the scikit-image measure.marching_cubes function to self.encoding.dense.

Returns

meshed – object, as returned by marching cubes algorithm.

Return type

Trimesh object representing the current voxel

property matrix

Return a DENSE matrix of the current voxel encoding

Returns

dense – Numpy array of dense matrix Shortcut to voxel.encoding.dense

Return type

(a, b, c) bool

md5()
property origin

Deprecated. Use self.translation.

property pitch

Uniform scaling factor representing the side length of each voxel.

Raises a RuntimeError if self.transformation has rotation or shear components of has non-uniform scaling.

property points

The center of each filled cell as a list of points.

Returns

points

Return type

(self.filled, 3) float, list of points

points_to_indices(points)

Convert points to indices in the matrix array.

Parameters

points ((n, 3) float, point in space) –

Returns

indices

Return type

(n, 3) int array of indices into self.encoding

revoxelized(shape)

Create a new VoxelGrid without rotations, reflections or shearing.

Parameters

shape (3-tuple of ints denoting the shape of the returned VoxelGrid.) –

Returns

  • VoxelGrid of the given shape with (possibly non-uniform) scale and

  • translation transformation matrix.

property scale

3-element float representing per-axis scale.

Raises a RuntimeError if self.transform has rotation or shear components.

property shape

3-tuple of ints denoting shape of occupancy grid.

show(*args, **kwargs)

Convert the current set of voxels into a trimesh for visualization and show that via its built- in preview method.

property sparse_indices

(n, 3) int array of sparse indices of occupied voxels.

strip()

Mutate self by stripping leading/trailing planes of zeros.

Returns

Return type

self after mutation occurs in-place

property transform

4x4 homogeneous transformation matrix.

property translation

Location of voxel at [0, 0, 0].

property volume

What is the volume of the filled cells in the current voxel object.

Returns

volume

Return type

float, volume of filled cells