Clean meshes automatically in Blender with Python

Dion Moult

2018-03-06

I wrote a little Python script to clean up imported meshes (OBJs, DXFs, etc) in Blender. It's quite useful if you often process meshes from other sources, in particular IFCs. Even better is that Blender can be run heedlessly and invoke the script automatically so you can clean meshes server side even before you open it up on my computer.

From my initial script, Paul Spooner at the BlenderArtists forums was kind enough to rewrite it with improvements. For the record, here it is. Simply copy and paste into the text editor and hit the Run Script button. It will only impact selected objects.

import bpy
checked = set()
selected_objects = bpy.context.selected_objects
for selected_object in selected_objects:
    if selected_object.type != 'MESH':
        continue
    meshdata = selected_object.data
    if meshdata in checked:
        continue
    else:
        checked.add(meshdata)
    bpy.context.scene.objects.active = selected_object
    bpy.ops.object.editmode_toggle()
    bpy.ops.mesh.select_all(action='SELECT')
    bpy.ops.mesh.remove_doubles()
    bpy.ops.mesh.tris_convert_to_quads()
    bpy.ops.mesh.normals_make_consistent()
    bpy.ops.object.editmode_toggle()

Although it is pretty self explanatory, what it does is weld vertices, convert tris to quads, and recalculate normals.

Comments

If you have any comments, please send them to dion@thinkmoult.com.