UAV/tools/merge_two_obj.py

66 lines
2.4 KiB
Python
Raw Normal View History

2024-12-31 20:37:35 +08:00
def read_obj(file_path):
"""
读取.obj文件返回顶点列表和面列表
"""
vertices = []
faces = []
with open(file_path, 'r') as file:
for line in file:
parts = line.split()
if len(parts) == 0:
continue
if parts[0] == 'v': # 顶点
vertices.append([float(parts[1]), float(parts[2]), float(parts[3])])
elif parts[0] == 'f': # 面
faces.append([int(parts[1].split('/')[0]), int(parts[2].split('/')[0]), int(parts[3].split('/')[0])])
return vertices, faces
def write_obj(file_path, vertices, faces):
"""
将修改后的顶点和面列表写入到.obj文件
"""
with open(file_path, 'w') as file:
for vertex in vertices:
file.write(f"v {vertex[0]} {vertex[1]} {vertex[2]}\n")
for face in faces:
file.write(f"f {face[0]} {face[1]} {face[2]}\n")
def translate_vertices(vertices, translation):
"""
平移顶点translation 是一个三维向量例如 (500, 0, 0) 会沿 X 轴平移 500
"""
return [[v[0] + translation[0], v[1] + translation[1], v[2] + translation[2]] for v in vertices]
def merge_objs(obj1_path, obj2_path, output_path, translation=(500, 0, 0)):
"""
合并两个.obj文件并对第二个文件的顶点进行平移
obj1_path obj2_path 是输入的.obj文件路径
output_path 是输出的合并后的.obj文件路径
translation 是平移向量默认为沿 X 轴平移 500
"""
# 读取第一个 obj 文件
vertices1, faces1 = read_obj(obj1_path)
# 读取第二个 obj 文件
vertices2, faces2 = read_obj(obj2_path)
# 平移第二个 obj 文件的顶点
vertices2_translated = translate_vertices(vertices2, translation)
# 合并顶点和面
all_vertices = vertices1 + vertices2_translated
all_faces = faces1 + [[f[0] + len(vertices1), f[1] + len(vertices1), f[2] + len(vertices1)] for f in faces2]
# 写入合并后的 obj 文件
write_obj(output_path, all_vertices, all_faces)
print(f"合并完成,结果保存在 {output_path}")
# 示例调用
obj1_path = 'model1.obj' # 第一个 .obj 文件
obj2_path = 'model2.obj' # 第二个 .obj 文件
output_path = 'merged_model.obj' # 输出合并后的 .obj 文件
merge_objs(obj1_path, obj2_path, output_path, translation=(500, 0, 0))