Skip to content

Instantly share code, notes, and snippets.

@mjm522
Created March 9, 2021 15:43
Show Gist options
  • Save mjm522/812a8e5da30fd3330582571c56502cc5 to your computer and use it in GitHub Desktop.
Save mjm522/812a8e5da30fd3330582571c56502cc5 to your computer and use it in GitHub Desktop.
import trimesh
from numpy.linalg import inv
import numpy as np

def pretty_print(array):
    print(np.round(array, 2))

def change_centroid(mesh_path, save_path, additional_T=None):
    mesh = trimesh.load_mesh(mesh_path)
    mesh_new = mesh.copy()
    curr_T = mesh_new.bounding_box_oriented.primitive.transform
    print("Current centroid", mesh_new.centroid)
    pretty_print(mesh_new.centroid)
    mesh_new = mesh_new.apply_transform(inv(curr_T))
    update_T = mesh_new.bounding_box_oriented.primitive.transform
    if additional_T is not None:
      mesh_new=mesh_new.apply_transform(additional_T)
    print("Current Transformation")
    pretty_print(curr_T)
    print("Update Transformation", update_T)
    pretty_print(update_T)
    print("Centroid after updation")
    pretty_print(mesh_new.centroid)
    mesh_new.export(meshpath_save)

Dependency:

pip install trimesh

Example:

change_centroid(meshpath_src, meshpath_save)

where meshpath_src and meshpath_save are absolute paths to your stl files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment