trimesh.path.path module

path.py

A module designed to work with vector paths such as those stored in a DXF or SVG file.

Classes

Path([entities, vertices, metadata, …])

A Path object consists of vertices and entities.

Path2D([entities, vertices, metadata, …])

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

Path3D([entities, vertices, metadata, …])

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

class trimesh.path.path.Path(entities=None, vertices=None, metadata=None, process=True, colors=None, **kwargs)

Bases: object

A Path object consists of vertices and entities. Vertices are a simple (n, dimension) float array of points in space.

Entities are a list of objects representing geometric primitives, such as Lines, Arcs, BSpline, etc. All entities reference vertices by index, so any transform applied to the simple vertex array is applied to the entity.

Methods

apply_layer(name)

Apply a layer name to every entity in the path.

apply_scale(scale)

Apply a transformation matrix to the current path in- place

apply_transform(transform)

Apply a transformation matrix to the current path in- place

apply_translation(offset)

Apply a transformation matrix to the current path in- place

convert_units(desired[, guess])

Convert the units of the current drawing in place.

copy()

Get a copy of the current mesh

crc()

A CRC of the current vertices and entities.

discretize_path(path)

Given a list of entities, return a list of connected points.

explode()

Turn every multi- segment entity into single segment entities in- place.

export([file_obj, file_type])

Export the path to a file object or return data.

fill_gaps([distance])

Find vertices without degree 2 and try to connect to other vertices.

md5()

An MD5 hash of the current vertices and entities.

merge_vertices([digits])

Merges vertices which are identical and replace references

process()

Apply basic cleaning functions to the Path object in- place.

remove_duplicate_entities()

Remove entities that are duplicated

remove_entities(entity_ids)

Remove entities by index.

remove_invalid()

Remove entities which declare themselves invalid

remove_unreferenced_vertices()

Removes all vertices which aren’t used by an entity.

replace_vertex_references(mask)

Replace the vertex index references in every entity.

rezero()

Translate so that every vertex is positive in the current mesh is positive.

scene()

Get a scene object containing the current Path3D object.

to_dict()

Attributes

bounds

Return the axis aligned bounding box of the current path.

centroid

Return the centroid of axis aligned bounding box enclosing all entities of the path object.

colors

Colors are stored per-entity.

dangling

List of entities that aren’t included in a closed path

discrete

A sequence of connected vertices in space, corresponding to self.paths.

entities

The actual entities making up the path.

extents

The size of the axis aligned bounding box.

is_closed

Are all entities connected to other entities.

is_empty

Are any entities defined for the current path.

kdtree

A KDTree object holding the vertices of the path.

layers

Get a list of the layer for every entity.

length

The total discretized length of every entity.

paths

Sequence of closed paths, encoded by entity index.

referenced_vertices

Which vertices are referenced by an entity.

scale

What is a representitive number that reflects the magnitude of the world holding the paths, for numerical comparisons.

units

If there are units defined in self.metadata return them.

vertex_graph

Return a networkx.Graph object for the entity connectiviy

vertex_nodes

Get a list of which vertex indices are nodes, which are either endpoints or points where the entity makes a direction change.

vertices

apply_layer(name)

Apply a layer name to every entity in the path.

Parameters

name (str) – Apply layer name to every entity

apply_scale(scale)

Apply a transformation matrix to the current path in- place

Parameters

scale (float or (3,) float) – Scale to be applied to mesh

apply_transform(transform)

Apply a transformation matrix to the current path in- place

Parameters

transform ((d+1, d+1) float) – Homogeneous transformations for vertices

apply_translation(offset)

Apply a transformation matrix to the current path in- place

Parameters

offset (float or (3,) float) – Translation to be applied to mesh

property bounds

Return the axis aligned bounding box of the current path.

Returns

bounds – AABB with (min, max) coordinates

Return type

(2, dimension) float

property centroid

Return the centroid of axis aligned bounding box enclosing all entities of the path object.

Returns

centroid – Approximate centroid of the path

Return type

(d,) float

property colors

Colors are stored per-entity.

Returns

colors – RGBA colors for each entity

Return type

(len(entities), 4) uint8

convert_units(desired, guess=False)

Convert the units of the current drawing in place.

Parameters
  • desired (str) – Unit system to convert to

  • guess (bool) – If True will attempt to guess units

copy()

Get a copy of the current mesh

Returns

copied – Copy of self

Return type

Path object

crc()

A CRC of the current vertices and entities.

Returns

crc – CRC of entity points and vertices

Return type

int

property dangling

List of entities that aren’t included in a closed path

Returns

dangling – Index of self.entities

Return type

(n,) int

property discrete

A sequence of connected vertices in space, corresponding to self.paths.

Returns

discrete – A sequence of (m*, dimension) float

Return type

(len(self.paths),)

discretize_path(path)

Given a list of entities, return a list of connected points.

Parameters

path ((n,) int, indexes of self.entities) –

Returns

discrete

Return type

(m, dimension)

property entities

The actual entities making up the path.

Returns

entities – Entities such as Line, Arc, or BSpline curves

Return type

(n,) trimesh.path.entities.Entity

explode()

Turn every multi- segment entity into single segment entities in- place.

export(file_obj=None, file_type=None, **kwargs)

Export the path to a file object or return data.

Parameters
  • file_obj (None, str, or file object) – File object or string to export to

  • file_type (None or str) – Type of file: dxf, dict, svg

Returns

exported – Exported as specified type

Return type

bytes or str

property extents

The size of the axis aligned bounding box.

Returns

extents – Edge length of AABB

Return type

(dimension,) float

fill_gaps(distance=0.025)

Find vertices without degree 2 and try to connect to other vertices. Operations are done in-place.

Parameters

distance (float) – Connect vertices up to this distance

property is_closed

Are all entities connected to other entities.

Returns

closed – Every entity is connected at its ends

Return type

bool

property is_empty

Are any entities defined for the current path.

Returns

empty – True if no entities are defined

Return type

bool

property kdtree

A KDTree object holding the vertices of the path.

Returns

kdtree – Object holding self.vertices

Return type

scipy.spatial.cKDTree

property layers

Get a list of the layer for every entity.

Returns

layers – Whatever is stored in each entity.layer

Return type

(len(entities), ) any

property length

The total discretized length of every entity.

Returns

length

Return type

float, summed length of every entity

md5()

An MD5 hash of the current vertices and entities.

Returns

md5 – Appended MD5 hashes

Return type

str

merge_vertices(digits=None)

Merges vertices which are identical and replace references by altering self.entities and self.vertices

Parameters

digits (None, or int) – How many digits to consider when merging vertices

property paths

Sequence of closed paths, encoded by entity index.

Returns

paths – Referencing self.entities

Return type

(n,) sequence of (*,) int

process()

Apply basic cleaning functions to the Path object in- place.

property referenced_vertices

Which vertices are referenced by an entity.

Returns

referenced_vertices

Return type

(n,) int, indexes of self.vertices

remove_duplicate_entities()

Remove entities that are duplicated

self.entities: length same or shorter

remove_entities(entity_ids)

Remove entities by index.

Parameters

entity_ids ((n,) int) – Indexes of self.entities to remove

remove_invalid()

Remove entities which declare themselves invalid

self.entities: shortened

remove_unreferenced_vertices()

Removes all vertices which aren’t used by an entity.

self.vertices: reordered and shortened self.entities: entity.points references updated

replace_vertex_references(mask)

Replace the vertex index references in every entity.

Parameters
  • mask ((len(self.vertices), ) int) – Contains new vertex indexes

  • Alters

  • ------------

  • in self.entities (entity.points) – Replaced by mask[entity.points]

rezero()

Translate so that every vertex is positive in the current mesh is positive.

Returns

matrix – Homogeneous transformations that was applied to the current Path object.

Return type

(dimension + 1, dimension + 1) float

property scale

What is a representitive number that reflects the magnitude of the world holding the paths, for numerical comparisons.

Returns

scale – Approximate size of the world holding this path

Return type

float

scene()

Get a scene object containing the current Path3D object.

Returns

scene

Return type

trimesh.scene.Scene object containing current path

to_dict()
property units

If there are units defined in self.metadata return them.

Returns

units – Current unit system

Return type

str

property vertex_graph

Return a networkx.Graph object for the entity connectiviy

graphnetworkx.Graph

Holds vertex indexes

property vertex_nodes

Get a list of which vertex indices are nodes, which are either endpoints or points where the entity makes a direction change.

Returns

nodes – Indexes of self.vertices which are nodes

Return type

(n, 2) int

property vertices
class trimesh.path.path.Path2D(entities=None, vertices=None, metadata=None, process=True, colors=None, **kwargs)

Bases: trimesh.path.path.Path

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

Methods

apply_obb()

Transform the current path so that its OBB is axis aligned and OBB center is at the origin.

connected_paths(path_id[, include_self])

Given an index of self.paths find other paths which overlap with that path.

extrude(height, **kwargs)

Extrude the current 2D path into a 3D mesh.

medial_axis([resolution, clip])

Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon.

plot_discrete([show, annotations])

Plot the closed curves of the path.

plot_entities([show, annotations, color])

Plot the entities of the path, with no notion of topology

rasterize(pitch, origin[, resolution, fill, …])

Rasterize a Path2D object into a boolean image (“mode 1”).

sample(count, **kwargs)

Use rejection sampling to generate random points inside a polygon.

show([annotations])

Plot the current Path2D object using matplotlib.

simplify(**kwargs)

Return a version of the current path with colinear segments merged, and circles entities replacing segmented circular paths.

simplify_spline([smooth, verbose])

Convert paths into b-splines.

split(**kwargs)

If the current Path2D consists of n ‘root’ curves,

to_3D([transform])

Convert 2D path to 3D path on the XY plane.

triangulate(**kwargs)

Create a region- aware triangulation of the 2D path.

Attributes

area

Return the area of the polygons interior.

body_count

enclosure

Networkx Graph object of polygon enclosure.

enclosure_directed

Networkx DiGraph of polygon enclosure

enclosure_shell

A dictionary of path indexes which are ‘shell’ paths, and values of ‘hole’ paths.

identifier

A unique identifier for the path.

identifier_md5

Return an MD5 of the identifier

obb

Get a transform that centers and aligns the OBB of the referenced vertices with the XY axis.

path_valid

returns: path_valid – which are valid polygons

polygons_closed

Cycles in the vertex graph, as shapely.geometry.Polygons.

polygons_full

A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons.

root

Which indexes of self.paths/self.polygons_closed are root curves.

apply_obb()

Transform the current path so that its OBB is axis aligned and OBB center is at the origin.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property area

Return the area of the polygons interior.

Returns

area

Return type

float, total area of polygons minus interiors

property body_count
connected_paths(path_id, include_self=False)

Given an index of self.paths find other paths which overlap with that path.

Parameters
  • path_id (int) – Index of self.paths

  • include_self (bool) – Should the result include path_id or not

Returns

path_ids – Indexes of self.paths that overlap input path_id

Return type

(n, ) int

property enclosure

Networkx Graph object of polygon enclosure.

property enclosure_directed

Networkx DiGraph of polygon enclosure

property enclosure_shell

A dictionary of path indexes which are ‘shell’ paths, and values of ‘hole’ paths.

Returns

corresponding

Return type

dict, {index of self.paths of shell : [indexes of holes]}

extrude(height, **kwargs)

Extrude the current 2D path into a 3D mesh.

Parameters
  • height (float, how far to extrude the profile) –

  • kwargs (passed directly to meshpy.triangle.build:) –

    triangle.build(mesh_info,

    verbose=False, refinement_func=None, attributes=False, volume_constraints=True, max_volume=None, allow_boundary_steiner=True, allow_volume_steiner=True, quality_meshing=True, generate_edges=None, generate_faces=False, min_angle=None)

Returns

mesh

Return type

trimesh object representing extruded polygon

property identifier

A unique identifier for the path.

Returns

identifier

Return type

(5,) float, unique identifier

property identifier_md5

Return an MD5 of the identifier

medial_axis(resolution=None, clip=None)

Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon.

Parameters
  • resolution (None or float) – Distance between each sample on the polygon boundary

  • clip (None, or (2,) float) – Min, max number of samples

Returns

medial – Contains only medial axis of Path

Return type

Path2D object

property obb

Get a transform that centers and aligns the OBB of the referenced vertices with the XY axis.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property path_valid

returns: path_valid – which are valid polygons :rtype: (n,) bool, indexes of self.paths self.polygons_closed

plot_discrete(show=False, annotations=True)

Plot the closed curves of the path.

plot_entities(show=False, annotations=True, color=None)

Plot the entities of the path, with no notion of topology

property polygons_closed

Cycles in the vertex graph, as shapely.geometry.Polygons. These are polygon objects for every closed circuit, with no notion of whether a polygon is a hole or an area. Every polygon in this list will have an exterior, but NO interiors.

Returns

polygons_closed

Return type

(n,) list of shapely.geometry.Polygon objects

property polygons_full

A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons.

Returns

full – Polygons containing interiors

Return type

(len(self.root),) shapely.geometry.Polygon

rasterize(pitch, origin, resolution=None, fill=True, width=None, **kwargs)

Rasterize a Path2D object into a boolean image (“mode 1”).

Parameters
  • pitch (float, length in model space of a pixel edge) –

  • origin ((2,) float, origin position in model space) –

  • resolution ((2,) int, resolution in pixel space) –

  • fill (bool, if True will return closed regions as filled) –

  • width (int, if not None will draw outline this wide (pixels)) –

Returns

raster

Return type

PIL.Image object, mode 1

property root

Which indexes of self.paths/self.polygons_closed are root curves. Also known as ‘shell’ or ‘exterior.

Returns

root

Return type

(n,) int, list of indexes

sample(count, **kwargs)

Use rejection sampling to generate random points inside a polygon.

Parameters
  • count (int) – Number of points to return If there are multiple bodies, there will be up to count * bodies points returned

  • factor (float) – How many points to test per loop IE, count * factor

  • max_iter (int,) – Maximum number of intersection loops to run, total points sampled is count * factor * max_iter

Returns

hit – Random points inside polygon

Return type

(n, 2) float

show(annotations=True)

Plot the current Path2D object using matplotlib.

simplify(**kwargs)

Return a version of the current path with colinear segments merged, and circles entities replacing segmented circular paths.

Returns

simplified

Return type

Path2D object

simplify_spline(smooth=0.0002, verbose=False)

Convert paths into b-splines.

Parameters
  • smooth (float) – How much the spline should smooth the curve

  • verbose (bool) – Print detailed log messages

Returns

simplified – Discrete curves replaced with splines

Return type

Path2D

split(**kwargs)

If the current Path2D consists of n ‘root’ curves, split them into a list of n Path2D objects

Returns

split – Each connected region and interiors

Return type

(n,) list of Path2D objects

to_3D(transform=None)

Convert 2D path to 3D path on the XY plane.

Parameters

transform ((4, 4) float) – If passed, will transform vertices. If not passed and ‘to_3D’ is in metadata that transform will be used.

Returns

path_3D

Return type

Path3D version of current path

triangulate(**kwargs)

Create a region- aware triangulation of the 2D path.

Parameters

**kwargs (dict) – Passed to trimesh.creation.triangulate_polygon

Returns

  • vertices ((n, 2) float) – 2D vertices of triangulation

  • faces ((n, 3) int) – Indexes of vertices for triangles

class trimesh.path.path.Path3D(entities=None, vertices=None, metadata=None, process=True, colors=None, **kwargs)

Bases: trimesh.path.path.Path

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

Methods

plot_discrete([show])

Plot closed curves

plot_entities([show])

Plot discrete version of entities without regards for connectivity.

show(**kwargs)

Show the current Path3D object.

to_planar([to_2D, normal, check])

Check to see if current vectors are all coplanar.

plot_discrete(show=False)

Plot closed curves

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

plot_entities(show=False)

Plot discrete version of entities without regards for connectivity.

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

show(**kwargs)

Show the current Path3D object.

to_planar(to_2D=None, normal=None, check=True)

Check to see if current vectors are all coplanar.

If they are, return a Path2D and a transform which will transform the 2D representation back into 3 dimensions

Parameters
  • to_2D ((4,4) float) – Homogeneous transformation matrix to apply, If not passed a plane will be fitted to vertices.

  • normal ((3,) float, or None) – Approximate normal of direction of plane If to_2D is not specified sign will be applied to fit plane normal

  • check (bool) – If True: Raise a ValueError if points aren’t coplanar

Returns

  • planar (trimesh.path.Path2D) – Current path transformed onto plane

  • to_3D ((4,4) float) – Homeogenous transformations to move planar back into 3D space