object-assembler / code /cube3d /render /render_obj4view.py
0xZohar's picture
Add code/cube3d/render/render_obj4view.py
5b58e07 verified
import os
import pymeshlab as ml
input_dir = "/public/home/wangshuo/gap/assembly/data/car_1k/obj"
output_base_dir = "/public/home/wangshuo/gap/assembly/data/car_1k/pose_4view"
import os
import pymeshlab as ml
import numpy as np
# 四个视角的旋转角度
rotations = [
{"x": -90, "y": 0},
{"x": -90, "y": 90},
{"x": -90, "y": 180},
{"x": -90, "y": 270},
]
# 旋转矩阵计算函数
def get_rotation_matrix(x_angle, y_angle):
# 计算绕 x 轴的旋转矩阵
x_rot_matrix = np.array([
[1, 0, 0],
[0, np.cos(np.radians(x_angle)), -np.sin(np.radians(x_angle))],
[0, np.sin(np.radians(x_angle)), np.cos(np.radians(x_angle))]
])
# 计算绕 y 轴的旋转矩阵
y_rot_matrix = np.array([
[np.cos(np.radians(y_angle)), 0, np.sin(np.radians(y_angle))],
[0, 1, 0],
[-np.sin(np.radians(y_angle)), 0, np.cos(np.radians(y_angle))]
])
# 合成旋转矩阵(先绕 x 轴旋转,再绕 y 轴旋转)
rotation_matrix = np.dot(y_rot_matrix, x_rot_matrix)
return rotation_matrix
# 遍历每个 obj 文件
for filename in os.listdir(input_dir):
if filename.endswith(".obj"):
obj_path = os.path.join(input_dir, filename)
base_name = os.path.splitext(filename)[0]
# 创建渲染输出目录
for i, rotation in enumerate(rotations):
output_dir = os.path.join(output_base_dir, f"view_{i+1}")
os.makedirs(output_dir, exist_ok=True)
# 加载网格
ms = ml.MeshSet()
ms.load_new_mesh(obj_path)
# 获取旋转矩阵
rot_matrix = get_rotation_matrix(rotation["x"], rotation["y"])
# 应用旋转矩阵
ms.apply_filter("transform_apply", matrix=rot_matrix.flatten().tolist())
# 渲染并保存图片
output_image_path = os.path.join(output_dir, f"{base_name}.png")
ms.save_current_mesh_image(output_image_path, image_width=800, image_height=600)
print(f"Rendered {filename} at rotation x={rotation['x']}°, y={rotation['y']}° -> {output_image_path}")
print("All OBJ files rendered.")