Last active
January 10, 2025 11:14
-
-
Save lukicdarkoo/9e6ef42882fd18c34556bd7a4991c3cd to your computer and use it in GitHub Desktop.
Decimate meshes with the Blender Python API
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
# Installation: | |
# | |
# pip3 install bpy | |
# | |
# Usage: | |
# | |
# python3 decimate.py /path/to/meshes/* --ratio 0.025 | |
# | |
import bpy | |
import os | |
import argparse | |
MODIFIER_NAME = 'DecimateMod' | |
def main(): | |
parser = argparse.ArgumentParser(description='Decimate a mesh') | |
parser.add_argument('input', type=str, nargs='+', | |
help='Path to the mesh file') | |
parser.add_argument('--ratio', type=float, default=0.025, | |
help='Decimate ratio') | |
parser.add_argument('--subdir', type=str, default='simplified', | |
help='Subdirectory to save the decimated meshes') | |
parser.add_argument('--overwrite', action='store_true', default=False, | |
help='Overwrite existing meshes') | |
args = parser.parse_args() | |
for input in args.input: | |
if not input.endswith('.stl'): | |
print('File not supported, skipping', input) | |
continue | |
if not os.path.exists(input): | |
print('File doesn\'t exist, skipping', input) | |
continue | |
# Set output path | |
parent_dir = os.path.dirname(input) | |
decimated_dir = os.path.join(parent_dir, args.subdir) | |
if not os.path.exists(decimated_dir): | |
os.makedirs(decimated_dir) | |
output = os.path.join(decimated_dir, os.path.basename(input)) | |
if not args.overwrite and os.path.exists(output): | |
print('Output already exists, skipping', input) | |
continue | |
print('Decimating', input) | |
# Clear Blender scene | |
for obj in bpy.data.objects: | |
bpy.data.objects.remove(obj, do_unlink=True) | |
for mesh in bpy.data.meshes: | |
bpy.data.meshes.remove(mesh) | |
# Import mesh | |
bpy.ops.import_mesh.stl(filepath=input) | |
# Decimate mesh | |
modifier = bpy.context.object.modifiers.new(MODIFIER_NAME, 'DECIMATE') | |
modifier.ratio = args.ratio | |
bpy.ops.object.modifier_apply(modifier=MODIFIER_NAME) | |
# Export mesh | |
bpy.ops.export_mesh.stl(filepath=output) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment