如何用Python将两个3D网格(头部与身体)在指定位置合并为单个网格
头部与身体3D网格颈部合并方案
一、Blender Python脚本实现
如果之前手动合并没达到预期,大概率是没处理好颈部顶点的对齐与缝合,以下是可直接运行的脚本流程:
- 导入网格并定位
先确保头部和身体网格的颈部位置匹配,手动调整或脚本内通过坐标偏移定位后,执行合并与缝合:
import bpy # 清除场景默认物体 bpy.ops.object.select_all(action='SELECT') bpy.ops.object.delete() # 导入头部和身体网格(替换为你的文件路径) bpy.ops.import_scene.obj(filepath="head.obj") bpy.ops.import_scene.obj(filepath="body.obj") # 选中两个网格对象 head = bpy.context.scene.objects["head"] body = bpy.context.scene.objects["body"] bpy.context.view_layer.objects.active = body head.select_set(True) body.select_set(True) # 合并为单个网格 bpy.ops.object.join() merged_obj = bpy.context.active_object # 进入编辑模式,缝合颈部顶点 bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_mode(type='VERT') bpy.ops.mesh.select_all(action='DESELECT') # 按坐标范围选择颈部顶点(根据实际网格调整Z值范围) bpy.ops.mesh.select_by_location(axis='Z', value_min=1.0, value_max=1.2, extend=False) # 合并邻近重合顶点 bpy.ops.mesh.remove_doubles(threshold=0.01) # 补全断开的面 bpy.ops.mesh.edge_face_add() # 返回对象模式并导出结果 bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.export_scene.obj(filepath="merged_body.obj")
关键提示:remove_doubles的阈值需根据网格精度调整,确保颈部重叠顶点被合并;若顶点未对齐,可通过head.location = (0, 0, 0.5)这类代码先调整头部位置,让颈部完全贴合。
二、纯Python库方案(无需Blender)
如果不想依赖Blender,推荐用trimesh库,适合批量处理网格:
- 安装依赖
pip install trimesh
- 合并与缝合代码
import trimesh # 加载头部和身体网格 head_mesh = trimesh.load("head.obj") body_mesh = trimesh.load("body.obj") # 调整头部位置到颈部(根据实际坐标偏移调整) head_mesh.apply_translation([0, 0, 0.5]) # 合并两个网格 merged_mesh = trimesh.util.concatenate([head_mesh, body_mesh]) # 清理重合顶点并修复网格 merged_mesh.merge_vertices() # 补全颈部可能存在的缝隙 merged_mesh.fill_holes() # 导出结果 merged_mesh.export("merged_body.obj")
关键提示:若颈部有明显缝隙,可先用trimesh.proximity.closest_point找到头部和身体颈部的对应顶点,调整位置后再合并;merge_vertices支持手动指定阈值,比如merged_mesh.merge_vertices(threshold=0.01)。
内容的提问来源于stack exchange,提问作者Ujjawal Kumar Singh
相关产品推荐
相关产品推荐

