Last active
August 8, 2023 15:42
-
-
Save diegoferigo/1a1fd48b35d2a41e5d6948d1a83aa881 to your computer and use it in GitHub Desktop.
Mesh conversion with trimesh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import pathlib | |
import trimesh.exchange.export | |
if __name__ == "__main__": | |
"""Mesh conversion script.""" | |
parser = argparse.ArgumentParser( | |
description="Convert a mesh file between different formats.", | |
) | |
parser.add_argument( | |
"-i", | |
"--input", | |
metavar="PATH", | |
type=pathlib.Path, | |
help="The input mesh file to convert", | |
) | |
parser.add_argument( | |
"-o", | |
"--output", | |
metavar="PATH", | |
type=pathlib.Path, | |
help="The output mesh file", | |
) | |
parser.add_argument( | |
"-t", | |
dest="type", | |
type=str, | |
default=None, | |
choices=list(trimesh.exchange.export._mesh_exporters.keys()), | |
help="The output format.", | |
) | |
# Parse the input arguments | |
args = parser.parse_args() | |
# ================================ | |
# Post-process the input arguments | |
# ================================ | |
# Expand the input path if not absolute | |
args.input = ( | |
(args.input if args.input.is_absolute() else pathlib.Path.cwd() / args.input) | |
.expanduser() | |
.absolute() | |
) | |
# Expand the output path if not absolute | |
args.output = ( | |
(args.output if args.output.is_absolute() else pathlib.Path.cwd() / args.output) | |
.expanduser() | |
.absolute() | |
) | |
# Automatically detect the output type if not explicitly specified | |
args.type = args.type if args.type is not None else args.output.suffix[1:] | |
if args.type not in trimesh.exchange.export._mesh_exporters.keys(): | |
raise ValueError(f"Unknown output format: '{args.type}'") | |
# =============== | |
# Import the mesh | |
# =============== | |
# Load the mesh | |
mesh = trimesh.load_mesh(args.input) | |
# =============== | |
# Export the mesh | |
# =============== | |
# Remove the output file if it exists | |
if args.output.exists(): | |
args.output.unlink() | |
# Create the output file if it doesn't exist | |
if not args.output.exists(): | |
args.output.parent.mkdir(parents=True, exist_ok=True) | |
# Export the mesh to the output format | |
mesh.export(file_obj=str(args.output), file_type=args.type) | |
try: | |
trimesh.load_mesh(args.output) | |
except Exception: | |
msg = "Failed to load the output mesh file. Something might have gone wrong." | |
raise RuntimeError(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment