本日はPython枠です。
先日open3Dを用いたメッシュのブーリアンを行いました。
https://redhologerbera.hatenablog.com/entry/2025/03/01/234833
ここではunion=2つのオブジェクトの合成を行いました。
今回は差分を行っていきます。
〇環境
・Windows11PC
・Open3D
・Anaconda Prompt
・Python3.11
〇ブーリアンで差分
差分を行うには、
result = mesh1_t.boolean_union(mesh2_t)
elif operation == "difference":
result = mesh1_t.boolean_difference(mesh2_t)
elif operation == "intersection":
result = mesh1_t.boolean_intersection(mesh2_t)
import open3d as o3d
import os
def boolean_operation(input_folder, output_folder, operation="union"):
os.makedirs(output_folder, exist_ok=True)
# OBJファイルの取得
obj_files = [f for f in os.listdir(input_folder) if f.lower().endswith(".obj")]
if len(obj_files) < 2:
print("エラー: OBJファイルが2つ必要です")
return
obj1_path = os.path.join(input_folder, obj_files[0])
obj2_path = os.path.join(input_folder, obj_files[1])
print(f"Processing: {obj1_path} and {obj2_path}")
# Open3D Triangle Meshとしてロード
mesh1 = o3d.io.read_triangle_mesh(obj1_path)
mesh2 = o3d.io.read_triangle_mesh(obj2_path)
# **メッシュが空でないかチェック**
if mesh1.is_empty() or mesh2.is_empty():
print("エラー: いずれかのOBJが正しく読み込めませんでした")
return
# **不要な頂点やエラーを削除**
mesh1.remove_unreferenced_vertices()
mesh2.remove_unreferenced_vertices()
mesh1.remove_degenerate_triangles()
mesh2.remove_degenerate_triangles()
# **Tensor Mesh に変換**
mesh1_t = o3d.t.geometry.TriangleMesh.from_legacy(mesh1)
mesh2_t = o3d.t.geometry.TriangleMesh.from_legacy(mesh2)
# **ブーリアン演算**
try:
if operation == "union":
result = mesh1_t.boolean_union(mesh2_t)
elif operation == "difference":
result = mesh1_t.boolean_difference(mesh2_t)
elif operation == "intersection":
result = mesh1_t.boolean_intersection(mesh2_t)
else:
print("エラー: operationは 'union', 'difference', 'intersection' のいずれかを指定してください")
return
except Exception as e:
print(f"ブーリアン演算に失敗: {e}")
return
# **法線を再計算**
result_legacy = result.to_legacy()
result_legacy.compute_triangle_normals()
result_legacy.compute_vertex_normals()
# **法線の向きを統一**
result_legacy.orient_triangles()
# **結果を保存**
output_file = os.path.join(output_folder, f"boolean_{operation}.obj")
o3d.io.write_triangle_mesh(output_file, result_legacy)
print(f"ブーリアン演算完了: {output_file}")
if __name__ == "__main__":
input_folder = "input"
output_folder = "output"
boolean_operation(input_folder, output_folder, operation="union") # 和演算