Browse Source

初步完整接口

main
hesuicong 2 weeks ago
parent
commit
e821b820b1
  1. BIN
      __pycache__/compute_print_net.cpython-312.pyc
  2. BIN
      __pycache__/config.cpython-312.pyc
  3. BIN
      __pycache__/download_print.cpython-312.pyc
  4. BIN
      __pycache__/general.cpython-312.pyc
  5. BIN
      __pycache__/point_cloud_layout.cpython-312.pyc
  6. BIN
      __pycache__/print_factory_type_setting_obj_run.cpython-312.pyc
  7. BIN
      __pycache__/test_load_json.cpython-312.pyc
  8. 7
      clound_print.py
  9. 60
      compute_print_net.py
  10. 10
      config.py
  11. 14
      download_print.py
  12. 16
      general.py
  13. 23964
      output.log
  14. 35
      point_cloud_layout.py
  15. 34
      print_factory_type_setting_obj_run.py
  16. 121
      test_load_json.py

BIN
__pycache__/compute_print_net.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/config.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/download_print.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/general.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/point_cloud_layout.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/print_factory_type_setting_obj_run.cpython-312.pyc

Binary file not shown.

BIN
__pycache__/test_load_json.cpython-312.pyc

Binary file not shown.

7
clound_print.py

File diff suppressed because one or more lines are too long

60
compute_print_net.py

@ -6,21 +6,30 @@ import argparse @@ -6,21 +6,30 @@ import argparse
from general import *
# -------------------------- 开始:获取z值最低 --------------------------
# -------------------------- 开始:获取bbox数据 -------------------------
"""
对外部提供的获取最低z的接口
get_lowest_position_of_z_out
对外部提供的获取bbox数据的接口
compute_bbox_out
参数:
obj_path, 模型数据路径
返回:
total_matrix: 旋转矩阵
z_max: Z最高点
z_max: z最高点
min_bound:bbox最低点, 例如[-1.0, -1.0, 0.0]
max_bound:bbox最低点, 例如[0.0, 0.0, 1.0]
"""
def get_lowest_position_of_z_out(mesh_obj):
def compute_bbox_out(mesh_obj):
return compute_bbox(mesh_obj)
# -------------------------- 结束:获取bbox数据 --------------------------
# -------------------------- 开始:获取z值最低 --------------------------
def get_lowest_position_of_z_ext(mesh_obj):
total_matrix = np.eye(4)
@ -222,7 +231,7 @@ def get_lowest_position_of_z_out(mesh_obj): @@ -222,7 +231,7 @@ def get_lowest_position_of_z_out(mesh_obj):
# print(f"z_mean1={z_mean1}, z_mean2={z_mean2}")
# if (z_mean2 > z_mean1):
print(f"z_volume_center1={z_volume_center1}, z_volume_center2={z_volume_center2}")
# print(f"z_volume_center1={z_volume_center1}, z_volume_center2={z_volume_center2}")
if (z_volume_center2 > z_volume_center1):
R_y = pcd_transformed.get_rotation_matrix_from_axis_angle(np.array([0, 1, 0]) * -angle_rad)
centroid = pcd_transformed.get_center()
@ -265,8 +274,8 @@ def get_lowest_position_of_z_out(mesh_obj): @@ -265,8 +274,8 @@ def get_lowest_position_of_z_out(mesh_obj):
return total_matrix, z_max
def get_lowest_position_of_center_ext(mesh_obj, total_matrix):
# print(f"get_lowest_position_of_center_ext {obj_path}")
temp_matrix, z_max = get_lowest_position_of_z_out(mesh_obj)
print(f"get_lowest_position_of_center_ext mesh_obj={mesh_obj}")
temp_matrix, z_max = get_lowest_position_of_z_ext(mesh_obj)
total_matrix = temp_matrix @ total_matrix
@ -405,7 +414,7 @@ def compute_bbox_all_ext(base_original_obj_dir,compact_min_dis=True): @@ -405,7 +414,7 @@ def compute_bbox_all_ext(base_original_obj_dir,compact_min_dis=True):
return compute_bbox_all(dict_mesh_obj,compact_min_dis)
def compute_bbox_all(dict_mesh_obj,compact_min_dis):
def compute_bbox_all(dict_mesh_obj,is_downsample):
dict_total_matrix= {}
dict_pcd_fix= {}
for key, value in dict_mesh_obj.items():
@ -414,21 +423,24 @@ def compute_bbox_all(dict_mesh_obj,compact_min_dis): @@ -414,21 +423,24 @@ def compute_bbox_all(dict_mesh_obj,compact_min_dis):
obj_name = key
mesh_obj = value
total_matrix, pcd_fix, ply_name = compute_bbox(mesh_obj,obj_name,compact_min_dis)
total_matrix, min_bound, max_bound, pcd_fix, ply_name = compute_bbox(mesh_obj,obj_name,is_downsample)
dict_total_matrix[obj_name] = total_matrix
dict_pcd_fix[ply_name] = pcd_fix
print(f"compute_bbox {obj_name} time={time.time()-start_time}")
# dict_mesh_obj.clear()
# del dict_mesh_obj
all_models = get_models_bbox(dict_pcd_fix)
return dict_total_matrix,all_models
def compute_bbox(mesh_obj,obj_name,compact_min_dis):
def compute_bbox(mesh_obj, obj_name="", is_downsample=True):
total_matrix = np.eye(4)
total_matrix, z_min= get_lowest_position_of_center_ext(mesh_obj, total_matrix)
total_matrix, z_max= get_lowest_position_of_center_ext(mesh_obj, total_matrix)
transformed_vertices = mesh_transform_by_matrix(np.asarray(mesh_obj.vertices), total_matrix)
@ -439,9 +451,12 @@ def compute_bbox(mesh_obj,obj_name,compact_min_dis): @@ -439,9 +451,12 @@ def compute_bbox(mesh_obj,obj_name,compact_min_dis):
# 将点云摆正和X轴平衡
obj_transformed_second,total_matrix = arrange_box_correctly(obj_transformed,voxel_size,total_matrix)
obj_transformed,total_matrix,pcd_fix,ply_name = get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,total_matrix)
total_matrix, min_bound, max_bound, pcd_fix, ply_name = get_new_bbox(obj_transformed_second,obj_name,voxel_size,is_downsample,total_matrix)
del obj_transformed
del obj_transformed_second
return total_matrix,pcd_fix,ply_name
return total_matrix, z_max, min_bound, max_bound, pcd_fix, ply_name
def arrange_box_correctly(obj_transformed, voxel_size,total_matrix):
@ -491,7 +506,7 @@ def arrange_box_correctly(obj_transformed, voxel_size,total_matrix): @@ -491,7 +506,7 @@ def arrange_box_correctly(obj_transformed, voxel_size,total_matrix):
return obj_transformed, total_matrix
def get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,total_matrix):
def get_new_bbox(obj_transformed_second,obj_name,voxel_size,is_downsample,total_matrix):
# 计算点云的边界
points = np.asarray(obj_transformed_second.vertices)
@ -499,6 +514,8 @@ def get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,tota @@ -499,6 +514,8 @@ def get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,tota
min_bound = np.min(points, axis=0) # 获取点云的最小边界
max_bound = np.max(points, axis=0) # 获取点云的最大边界
# print(f"get_new_bbox1: min_bound={min_bound}, max_bound={max_bound}")
# 确保包围盒的Y坐标不低于0
min_bound[2] = max(min_bound[2], 0) # 确保Y坐标的最小值不低于0
@ -537,16 +554,23 @@ def get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,tota @@ -537,16 +554,23 @@ def get_new_bbox(obj_transformed_second,obj_name,voxel_size,compact_min_dis,tota
vertices = np.asarray(obj_transformed_second.vertices)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(vertices)
if compact_min_dis:
if is_downsample:
pcd_downsampled = down_sample(pcd, voxel_size, False)
pcd_fix = pcd_downsampled
else:
pcd_fix = pcd
min_bound = np.min(pcd.points, axis=0) # 获取点云的最小边界
max_bound = np.max(pcd.points, axis=0) # 获取点云的最大边界
# print(f"get_new_bbox2: min_bound={min_bound}, max_bound={max_bound}")
if (not obj_name == ""):
ply_print_pid = obj_name.replace(".obj","")
ply_name = f"{ply_print_pid}={z_length}+{y_length}+{x_length}.ply"
else:
ply_name = ""
return obj_transformed_second, total_matrix, pcd_fix, ply_name
return total_matrix, min_bound, max_bound, pcd_fix, ply_name
class Platform:
def __init__(self, width, depth, height):
@ -744,5 +768,5 @@ if __name__ == '__main__': @@ -744,5 +768,5 @@ if __name__ == '__main__':
args = parser.parse_args()
obj_path = args.obj_path
max, z = get_lowest_position_of_z_out(obj_path)
max, z = get_lowest_position_of_z_ext(obj_path)

10
config.py

@ -1,3 +1,5 @@ @@ -1,3 +1,5 @@
# -------------------------- 开始:运行模式 -------------------------------
from enum import Enum
class run_mode(Enum):
formal = 1
@ -6,13 +8,17 @@ class run_mode(Enum): @@ -6,13 +8,17 @@ class run_mode(Enum):
# !!!谨慎选择run_mode.fix,这将把修复的数据上传到正式的系统 !!!
curr_run_mode = run_mode.test
# -------------------------- 结束:运行模式 -------------------------------
is_test = True
# -------------------------- 开始:路径配置 -------------------------------
# print_factory_type_dir="/root/print_factory_type"
print_factory_type_dir="/home/algo/Documents/print_factory_type"
url_send_layout = 'https://mp.api.suwa3d.com/api/printTypeSettingOrder/printTypeSettingOrderSuccess'
# -------------------------- 结束:路径配置 -------------------------------
# -------------------------- 开始:机台尺寸 -------------------------------
big_machine_size = [600, 500, 300]
small_machine_size = [380, 345, 250]
# -------------------------- 结束:机台尺寸 -------------------------------

14
download_print.py

@ -14,7 +14,6 @@ import os @@ -14,7 +14,6 @@ import os
import argparse
from config import print_factory_type_dir
from config import is_test
from general import is_use_debug_oss
@ -1043,6 +1042,7 @@ class DataTransfer: @@ -1043,6 +1042,7 @@ class DataTransfer:
prefix_exists = True
if obj.key != prefix: # 跳过目录本身
objects.append(obj.key)
print(f"obj.key={obj.key}")
if not prefix_exists:
print(f"前缀 '{prefix}' 下没有找到任何文件或目录。")
@ -1109,6 +1109,7 @@ class DataTransfer: @@ -1109,6 +1109,7 @@ class DataTransfer:
new_mtl_name = f"{batch_model_info.order_id}_{old_mtl_name}"
f_out.write(f"mtllib {new_mtl_name}\n")
mtllib_modified = True
print("len(parts) > 1")
continue
f_out.write(line)
@ -1361,13 +1362,14 @@ def download_data_by_batch(batch_model_info, workdir, oss_client ): @@ -1361,13 +1362,14 @@ def download_data_by_batch(batch_model_info, workdir, oss_client ):
download_textures = DataTransfer(target_dir, f"{path}/", oss_client)
if not download_textures.download_data_rename_batch(batch_model_info):
print("fail download_data_rename_batch")
return False
# 下载后检查目标文件夹是否为空
if os.path.exists(target_dir) and not os.listdir(target_dir):
shutil.rmtree(target_dir)
print(f"下载后检查发现目标文件夹为空,已删除: {target_dir}")
except Exception as e:
print(f"卡通图片下载失败: {path}, 错误: {str(e)}")
print(f"下载失败: {path}, 错误: {str(e)}")
pass
return True
@ -1381,9 +1383,10 @@ def download_datas_by_batch(batch_id, workdir, oss_config): @@ -1381,9 +1383,10 @@ def download_datas_by_batch(batch_id, workdir, oss_config):
# 批量下载
for batch_model_info in list_print_model_info:
print(f"开始下载print_model_info: {batch_model_info}")
download_data_by_batch(batch_model_info, workdir, oss_client)
if not download_data_by_batch(batch_model_info, workdir, oss_client):
return datas, False
return datas
return datas, True
def download_datas_by_pre_layout(list_print_model_info, workdir, oss_config):
oss_client = get_oss_client(oss_config)
@ -1397,7 +1400,7 @@ def download_datas_by_pre_layout(list_print_model_info, workdir, oss_config): @@ -1397,7 +1400,7 @@ def download_datas_by_pre_layout(list_print_model_info, workdir, oss_config):
return True
def download_transform_save_by_batch(batch_id, workdir, oss_config):
datas = download_datas_by_batch(batch_id, workdir, oss_config)
datas, succ = download_datas_by_batch(batch_id, workdir, oss_config)
print("datas=", datas)
layout_data = datas["layout_data"]
@ -1439,7 +1442,6 @@ def upload_result(base_original_obj_dir, oss_config, batch_id): @@ -1439,7 +1442,6 @@ def upload_result(base_original_obj_dir, oss_config, batch_id):
oss_batch_dir = "batchPrint"
print(f"is_use_debug_oss={is_use_debug_oss()}")
if is_use_debug_oss():
# if is_test:
oss_batch_dir = "batchPrint/debug_hsc"
print(f"target_dir={target_dir}, batch_id={batch_id}")

16
general.py

@ -24,8 +24,8 @@ def is_use_debug_oss(): @@ -24,8 +24,8 @@ def is_use_debug_oss():
# -------------------------- 开始:模型 ----------------------------------
def read_mesh(obj_path):
mesh_obj = o3d.io.read_triangle_mesh(obj_path)
def read_mesh(obj_path, enable_post_processing=False):
mesh_obj = o3d.io.read_triangle_mesh(obj_path, enable_post_processing)
return mesh_obj
def down_sample(pcd, voxel_size, farthest_sample = False):
@ -119,6 +119,10 @@ def mesh_transform_by_matrix(vertices, transform_matrix): @@ -119,6 +119,10 @@ def mesh_transform_by_matrix(vertices, transform_matrix):
# 3. 转回非齐次坐标 (3xN) → (N, 3)
transformed_vertices = transformed_homogeneous[:3, :].T
del homogeneous_vertices
del transformed_homogeneous
return transformed_vertices
import os
@ -207,7 +211,7 @@ def transform_save_o3d(layout_data, original_obj_pid_dir): @@ -207,7 +211,7 @@ def transform_save_o3d(layout_data, original_obj_pid_dir):
obj_path = os.path.join(original_obj_pid_dir, obj_name)
# 加载网格
try:
mesh = o3d.io.read_triangle_mesh(obj_path, enable_post_processing=True)
mesh = read_mesh(obj_path, enable_post_processing=True)
if not mesh.has_vertices():
print(f"警告: 网格无有效顶点 - {obj_path}")
continue
@ -261,6 +265,12 @@ def is_same_obj(obj_name1, obj_name2): @@ -261,6 +265,12 @@ def is_same_obj(obj_name1, obj_name2):
return False
def get_blank_path(is_small_machine=False):
if is_small_machine:
return os.path.join(print_factory_type_dir, "blank/blank_bias/blank_small.obj")
else:
return os.path.join(print_factory_type_dir, "blank/blank_bias/blank2.obj")
# -------------------------- 结束:模型 ----------------------------------
# -------------------------- 开始:碰撞检测和越界 --------------------------

23964
output.log

File diff suppressed because it is too large Load Diff

35
point_cloud_layout.py

@ -9,21 +9,20 @@ import open3d as o3d @@ -9,21 +9,20 @@ import open3d as o3d
import numpy as np
from plyfile import PlyData, PlyElement
from config import is_test
from config import print_factory_type_dir
from general import mesh_tranform_to_pcd
from general import need_upload_result
from general import read_mesh
from compute_print_net import get_models_bbox
from compute_print_net import arrange_models_on_platform
from compute_print_net import Platform
from compute_print_net import down_sample
from compute_print_net import read_mesh
from compute_print_net import compute_bbox_all
from compute_print_net import compute_bbox_all_ext
def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_dis):
def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,is_downsample):
"""获取需要的盒子大小"""
start_time = time.time()
@ -31,8 +30,10 @@ def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_d @@ -31,8 +30,10 @@ def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_d
obj_id_list = obj_id_list
dict_mesh_obj = {}
index = 0
for pid_t_y in obj_id_list:
start_time1 = time.time()
obj_name = pid_t_y+".obj"
obj_path = os.path.join(base_original_obj_dir,obj_name)
mesh_obj = read_mesh(obj_path)
@ -46,14 +47,17 @@ def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_d @@ -46,14 +47,17 @@ def make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_d
print(f"Skipping invalid file: {obj_path}")
continue
# dict_origin[obj_path] = copy.deepcopy(mesh_obj)
dict_origin[obj_name] = copy.deepcopy(mesh_obj)
dict_origin[obj_name] = mesh_obj
dict_mesh_obj[obj_name] = mesh_obj
print(f"make_bbox_for_print {index} {obj_name} time={time.time()-start_time1}")
index = index + 1
print(f"make_bbox_for_print total_time={time.time()-start_time}")
dict_total_matrix,all_models = compute_bbox_all_ext(base_original_obj_dir, compact_min_dis)
# dict_total_matrix,all_models = compute_bbox_all(dict_mesh_obj, compact_min_dis)
# dict_total_matrix,all_models = compute_bbox_all_ext(base_original_obj_dir, is_downsample)
dict_total_matrix,all_models = compute_bbox_all(dict_mesh_obj, is_downsample)
return get_dict_pcd(dict_mesh_obj,dict_total_matrix,all_models)
def get_dict_pcd(dict_mesh_obj,dict_total_matrix,all_models):
@ -78,6 +82,9 @@ def get_pcd_by_matrix(dict_mesh_obj,dict_total_matrix,dict_ply_name): @@ -78,6 +82,9 @@ def get_pcd_by_matrix(dict_mesh_obj,dict_total_matrix,dict_ply_name):
pcd_fix = mesh_tranform_to_pcd(mesh_obj, dict_total_matrix[obj_name])
dict_pcd_fix[dict_ply_name[obj_name]] = pcd_fix
dict_mesh_obj.clear()
del dict_mesh_obj
return dict_pcd_fix
@ -1327,14 +1334,8 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp @@ -1327,14 +1334,8 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp
"type_setting_start_time": print_start_time
}
print("is_test=", is_test)
print(f"need_upload_result={need_upload_result()}")
# if need_upload_result():
if is_test:
is_send_layout_data = False
else:
is_send_layout_data = True
# is_send_layout_data = False
is_need_upload_result = need_upload_result()
obj_file_list = list(dict_mesh_obj.keys())
ply_path_dict = {}
@ -1350,12 +1351,12 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp @@ -1350,12 +1351,12 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp
ply_name_pid = obj_name.replace(".obj", "")
ply_name = ply_path_dict.get(ply_name_pid, None)
if is_send_layout_data:
if is_need_upload_result:
result = extract_numbers_from_filename(ply_name)
if not ply_name or ply_name in dict_unplaced:
if is_send_layout_data:
if is_need_upload_result:
print_id = result[2]
order_id = result[0]
status = 0
@ -1388,7 +1389,7 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp @@ -1388,7 +1389,7 @@ def move_obj_to_compact_bounds_json(base_original_obj_dir,dict_mesh_obj,dict_unp
}
})
if is_send_layout_data:
if is_need_upload_result:
print_id = result[2]
order_id = result[0]
status = 1

34
print_factory_type_setting_obj_run.py

@ -13,12 +13,12 @@ from test_load_json import load_show_save @@ -13,12 +13,12 @@ from test_load_json import load_show_save
from download_print import upload_result
from config import print_factory_type_dir
from config import is_test
from config import url_send_layout
from config import big_machine_size
from config import small_machine_size
from general import need_upload_result
from general import get_blank_path
from point_cloud_layout import make_bbox_for_print
@ -66,7 +66,8 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode=" @@ -66,7 +66,8 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode="
dict_bad = {}
dict_origin = {}
dict_total_matrix, all_models, dict_pcd_fix = make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,compact_min_dis)
is_downsample = compact_min_dis
dict_total_matrix, all_models, dict_pcd_fix = make_bbox_for_print(base_original_obj_dir,dict_bad,dict_origin,is_downsample)
mesh_count = len(dict_origin)
if mesh_count<=0:
print("选择的文件夹没有模型")
@ -131,8 +132,7 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode=" @@ -131,8 +132,7 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode="
is_screenshot = True
if is_screenshot:
start_time = time.time()
blank_path = get_blank_path(is_small_machine)
load_show_save(base_original_obj_dir, dict_origin, blank_path, batch_id)
load_show_save(base_original_obj_dir, dict_origin, batch_id)
elapsed_seconds5 = time.time() - start_time
elapsed_minutes5 = int(elapsed_seconds5 // 60)
print(f"保存截图耗时::{elapsed_minutes5} 分 / {elapsed_seconds5}")
@ -149,15 +149,8 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode=" @@ -149,15 +149,8 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode="
upload_result(base_original_obj_dir, oss_config, batch_id)
print(f"is_test={is_test}")
print(f"need_upload_result={need_upload_result()}")
# if need_upload_result():
if is_test :
is_send_layout_data = False
else :
is_send_layout_data = True
if is_send_layout_data:
if need_upload_result():
print(f"send_layout_data={send_layout_data}")
# url = 'https://mp.api.suwa3d.com/api/printTypeSettingOrder/printTypeSettingOrderSuccess'
url = url_send_layout
@ -188,20 +181,9 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode=" @@ -188,20 +181,9 @@ def print_type_setting_obj(base_original_obj_dir=None,batch_id=0,selected_mode="
return 0
def get_blank_path(is_small_machine=False):
if is_small_machine:
return os.path.join(print_factory_type_dir, "blank/blank_bias/blank_small.obj")
else:
return os.path.join(print_factory_type_dir, "blank/blank_bias/blank2.obj")
def preview(base_original_obj_dir=None, batch_id=0, is_small_machine=False):
base_path = get_base_directory()
parent_dir = os.path.dirname(base_path)
# blank_dir = os.path.join(parent_dir, "blank", "blank_bias")
blank_path = get_blank_path(is_small_machine)
def preview(base_original_obj_dir=None, batch_id=0):
load_show_save(base_original_obj_dir, {}, blank_path, batch_id, True)
load_show_save(base_original_obj_dir, {}, batch_id, True)
def get_pcd(obj, is_down_sample=True):
vertices = np.asarray(obj.vertices)
@ -221,7 +203,7 @@ if __name__ == '__main__': @@ -221,7 +203,7 @@ if __name__ == '__main__':
# args = parser.parse_args()
# batch_id = args.batch_id
batch_id = "1"
batch_id = "9910032"
src_dir = batch_id
selected_mode="紧凑" # 标准 紧凑
output_format="JSON" # 模型 JSON

121
test_load_json.py

@ -4,11 +4,14 @@ import json @@ -4,11 +4,14 @@ import json
import os
from PIL import Image
import argparse
import gc
from config import print_factory_type_dir
from general import mesh_transform_by_matrix
from general import read_mesh
from general import get_blank_path
def load_and_transform_models(base_path, dict_origin, blank_path, json_name):
def load_and_transform_models(base_path, dict_origin, json_name):
meshes = [] # 存储所有变换后的网格
@ -30,8 +33,13 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name): @@ -30,8 +33,13 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name):
print(f"读取JSON文件失败: {e}")
return []
print(f"选择机型={data.get('summary')['selected_machine']}")
selected_machine = data.get('summary')['selected_machine']
print(f"选择机型={selected_machine}")
is_small_machine = True if selected_machine=="小机型" else False
blank_path = get_blank_path(is_small_machine)
index = 0
# 处理每个模型
for model in data.get('models', []):
obj_name = model.get('file_name', '')
@ -54,11 +62,11 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name): @@ -54,11 +62,11 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name):
key = obj_path
if key in dict_origin:
# print("key in dict_origin")
mesh = dict_origin[key]
mesh_obj = dict_origin[key]
else :
# print("key not in dict_origin")
mesh = o3d.io.read_triangle_mesh(obj_path, enable_post_processing=True)
if not mesh.has_vertices():
mesh_obj = read_mesh(obj_path,True)
if not mesh_obj.has_vertices():
print(f"警告: 网格无有效顶点 - {obj_path}")
continue
except Exception as e:
@ -71,22 +79,31 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name): @@ -71,22 +79,31 @@ def load_and_transform_models(base_path, dict_origin, blank_path, json_name):
reconstructed_matrix = np.array(homo_matrix, dtype=np.float64)
# 手动变换顶点
original_vertices = np.asarray(mesh.vertices)
original_vertices = np.asarray(mesh_obj.vertices)
transformed_vertices = mesh_transform_by_matrix(original_vertices, reconstructed_matrix)
mesh.vertices = o3d.utility.Vector3dVector(transformed_vertices)
mesh_obj.vertices = o3d.utility.Vector3dVector(transformed_vertices)
del original_vertices, transformed_vertices, reconstructed_matrix
# 添加到列表
meshes.append(mesh)
print(f"已加载并变换: {os.path.basename(obj_path)}")
meshes.append(mesh_obj)
del mesh_obj
gc.collect()
print(f"已加载并变换: {index} {os.path.basename(obj_path)}")
index = index + 1
#if (index > 100):
# break
add_plank = True
if add_plank:
# obj_path = os.path.join(blank_dir, "blank2.obj")
obj_path = blank_path
print("add_plank",obj_path)
try:
mesh = o3d.io.read_triangle_mesh(obj_path, enable_post_processing=True)
mesh = read_mesh(obj_path, True)
if not mesh.has_vertices():
print(f"警告: 网格无有效顶点 - {obj_path}")
except Exception as e:
@ -130,9 +147,9 @@ def compute_mesh_center(vertices): @@ -130,9 +147,9 @@ def compute_mesh_center(vertices):
centroid = np.array([sum_x / n, sum_y / n, sum_z / n])
return centroid
def load_and_show(base_path, blank_dir, json_name="3DPrintLayout.json"):
def load_and_show(base_path, json_name="3DPrintLayout.json"):
# 加载并变换所有模型
transformed_meshes = load_and_transform_models(base_path, {}, blank_dir, json_name)
transformed_meshes = load_and_transform_models(base_path, {}, json_name)
if not transformed_meshes:
print("没有加载到任何模型,请检查错误信息")
@ -305,17 +322,13 @@ def set_orthographic_projection(view_control, ortho_scale=10.0): @@ -305,17 +322,13 @@ def set_orthographic_projection(view_control, ortho_scale=10.0):
print(f"在配置 ViewControl 参数时出错: {e}")
return False
def set_orthographic(meshes, output_path, width=1920, height=1080,
def set_orthographic(meshes, width=1920, height=1080,
background_color=[1, 1, 1], camera_position=None,
ortho_width=None, zoom=1.0):
vis = o3d.visualization.Visualizer()
vis.create_window(width=width, height=height, visible=False)
# 添加几何体
for mesh in meshes:
vis.add_geometry(mesh)
# 设置渲染选项
render_opt = vis.get_render_option()
render_opt.background_color = np.asarray(background_color)
@ -323,12 +336,12 @@ def set_orthographic(meshes, output_path, width=1920, height=1080, @@ -323,12 +336,12 @@ def set_orthographic(meshes, output_path, width=1920, height=1080,
render_opt.mesh_show_wireframe = False
render_opt.point_size = 3.0
# 视角控制
view_control = vis.get_view_control()
# 计算所有网格的合并边界框,用于自适应设置投影参数
all_points = []
index = 0
# 添加几何体
for mesh in meshes:
vis.add_geometry(mesh)
if hasattr(mesh, 'vertices'):
points = np.asarray(mesh.vertices)
elif hasattr(mesh, 'points'):
@ -338,10 +351,24 @@ def set_orthographic(meshes, output_path, width=1920, height=1080, @@ -338,10 +351,24 @@ def set_orthographic(meshes, output_path, width=1920, height=1080,
if len(points) > 0:
all_points.append(points)
del mesh
del points
gc.collect()
print(f"set_orthographic {index}")
index = index + 1
del meshes
gc.collect()
# 视角控制
view_control = vis.get_view_control()
if len(all_points) > 0:
all_points = np.vstack(all_points)
bbox_min = np.min(all_points, axis=0)
bbox_max = np.max(all_points, axis=0)
all_points_v = np.vstack(all_points)
del all_points
gc.collect()
bbox_min = np.min(all_points_v, axis=0)
bbox_max = np.max(all_points_v, axis=0)
bbox_center = (bbox_min + bbox_max) / 2.0
bbox_size = np.max(bbox_max - bbox_min)
@ -365,6 +392,9 @@ def set_orthographic(meshes, output_path, width=1920, height=1080, @@ -365,6 +392,9 @@ def set_orthographic(meshes, output_path, width=1920, height=1080,
ortho_width *= aspect_ratio
if ortho_width <= 0:
ortho_width = 10.0
del all_points_v
gc.collect()
else:
# 如果没有顶点,使用默认值
if not camera_position:
@ -373,37 +403,39 @@ def set_orthographic(meshes, output_path, width=1920, height=1080, @@ -373,37 +403,39 @@ def set_orthographic(meshes, output_path, width=1920, height=1080,
view_control.set_up([0, 1, 0])
ortho_width = ortho_width or 10.0
for _ in range(2):
vis.poll_events()
vis.update_renderer()
print("set_orthographic 1")
#for _ in range(2):
# vis.poll_events()
# vis.update_renderer()
# 设置正交投影
try:
set_orthographic_camera(view_control)
print("set_orthographic 2")
except AttributeError:
set_orthographic_projection(view_control, ortho_scale=15.0)
print("set_orthographic 3")
for _ in range(5):
vis.poll_events()
vis.update_renderer()
#for _ in range(5):
# vis.poll_events()
# vis.update_renderer()
return vis
print("set_orthographic End")
def render_to_texture(meshes, output_path, width=1920, height=1080,
background_color=[1, 1, 1], camera_position=None,
ortho_width=None, zoom=1.0):
return vis
def render_to_texture(meshes, output_image_path):
vis = set_orthographic(meshes, output_path)
vis = set_orthographic(meshes)
# 渲染并保存
vis.capture_screen_image(output_path, do_render=True)
vis.capture_screen_image(output_image_path, do_render=True)
print(f"高级渲染图片已保存到: {output_path}")
print(f"高级渲染图片已保存到: {output_image_path}")
return vis
def load_show_save(base_path, dict_origin, blank_path, batch_id, is_show=False):
def load_show_save(base_path, dict_origin, batch_id, is_show=False):
folder_name = batch_id
@ -413,14 +445,14 @@ def load_show_save(base_path, dict_origin, blank_path, batch_id, is_show=False): @@ -413,14 +445,14 @@ def load_show_save(base_path, dict_origin, blank_path, batch_id, is_show=False):
output_image_path = os.path.join(base_path, f"{folder_name}.jpg")
# 加载并变换所有模型
transformed_meshes = load_and_transform_models(base_path, dict_origin, blank_path, json_name)
transformed_meshes = load_and_transform_models(base_path, dict_origin, json_name)
if not transformed_meshes:
print("没有加载到任何模型,请检查错误信息")
else:
print(f"成功加载并变换了 {len(transformed_meshes)} 个模型")
render_to_texture(transformed_meshes, output_image_path, background_color=[0.9, 0.9, 0.9])
render_to_texture(transformed_meshes, output_image_path)
if is_show:
# 可视化所有模型
@ -457,12 +489,9 @@ if __name__ == "__main__": @@ -457,12 +489,9 @@ if __name__ == "__main__":
args = parser.parse_args()
# batch_id = args.batch_id
batch_id = "test" # 1113-MY-4
batch_id = "9910032"
base_path = f"{print_factory_type_dir}/{batch_id}/"
blank_path = f"{print_factory_type_dir}/blank/blank_bias/blank2.obj"
# blank_path = f"{print_factory_type_dir}/blank/blank_bias/blank_small.obj"
print(f"blank_path={blank_path}")
load_show_save(base_path, {}, blank_path, batch_id, True)
load_show_save(base_path, {}, batch_id, False)
Loading…
Cancel
Save