pmd.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #encoding=utf-8
  2. import time
  3. import os
  4. import sys
  5. import pandas as pd
  6. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  7. import time
  8. import glob
  9. import numpy as np
  10. np.random.seed(42)
  11. from datetime import datetime
  12. import json
  13. from src.utils import get_meshgrid, get_world_points, get_camera_points, get_screen_points, write_point_cloud, get_white_mask, get_meshgrid_contour, post_process, find_notch, post_process_with_grad
  14. from src.phase import extract_phase, unwrap_phase
  15. from src.recons import reconstruction_cumsum, poisson_recons_with_smoothed_gradients
  16. from src.pcl_postproc import smooth_pcl, align2ref
  17. import matplotlib.pyplot as plt
  18. from src.calibration import calibrate_world, calibrate_screen_chessboard, calibrate_screen_circlegrid, map_screen_to_world
  19. from src.calibration.get_camera_params import calibrate_world_aprilgrid
  20. import argparse
  21. from src.vis import plot_coords
  22. import cv2
  23. from src.eval import get_eval_result
  24. import pickle
  25. from collections import defaultdict
  26. from scipy.io import loadmat, savemat
  27. from scipy.optimize import minimize
  28. import copy
  29. def pmdstart(config_path, img_folder):
  30. start_time = time.time()
  31. print(f"config_path: {config_path}")
  32. #time.sleep(15)
  33. main(config_path, img_folder)
  34. print(f"img_folder: {img_folder}")
  35. print('test pass')
  36. end_time = time.time()
  37. print(f"Time taken: {end_time - start_time} seconds")
  38. return True
  39. def optimize_calibration_with_gradient_constraint(cam_params, screen_params, point_cloud, gradient_data, config_path):
  40. # 只使用屏幕参数(旋转矩阵和平移向量)
  41. initial_params = np.concatenate([
  42. screen_params['screen_rotation_matrix'].flatten(),
  43. screen_params['screen_translation_vector'].flatten()
  44. ])
  45. # 定义屏幕参数的尺度因子
  46. scale_factors = np.ones_like(initial_params)
  47. scale_factors[0:9] = 1.0 # 旋转矩阵
  48. scale_factors[9:] = 100.0 # 平移向量(假设单位是毫米)
  49. # 归一化初始参数
  50. normalized_params = initial_params / scale_factors
  51. iteration_count = [0]
  52. print("\nInitial screen parameters:")
  53. print(f"Rotation matrix:\n{screen_params['screen_rotation_matrix']}")
  54. print(f"Translation vector:\n{screen_params['screen_translation_vector']}")
  55. def objective_function(normalized_params):
  56. try:
  57. # 反归一化参数
  58. params = normalized_params * scale_factors
  59. iteration_count[0] += 1
  60. print(f"\nIteration {iteration_count[0]}:")
  61. # 解析屏幕参数
  62. screen_R = params[:9].reshape(3, 3)
  63. screen_T = params[9:].reshape(3, 1)
  64. # 构建参数字典
  65. temp_cam_params = [{
  66. 'camera_matrix': cam_params['camera_matrix'],
  67. 'distortion_coefficients': cam_params['distortion_coefficients'],
  68. 'rotation_matrix': cam_params['rotation_matrix'],
  69. 'rotation_vector': cam_params['rotation_vector'],
  70. 'translation_vector': cam_params['translation_vector']
  71. }]
  72. temp_screen_params = {
  73. 'screen_matrix': screen_params['screen_matrix'],
  74. 'screen_distortion': screen_params['screen_distortion'],
  75. 'screen_rotation_matrix': screen_R,
  76. 'screen_rotation_vector': cv2.Rodrigues(screen_R)[0],
  77. 'screen_translation_vector': screen_T
  78. }
  79. if iteration_count[0] % 5 == 0: # 每5次迭代打印一次详细信息
  80. print("\nCurrent screen parameters:")
  81. print(f"Rotation matrix:\n{screen_R}")
  82. print(f"Translation vector:\n{screen_T.flatten()}")
  83. try:
  84. reconstructed_points, reconstructed_gradients = reconstruct_surface(
  85. temp_cam_params,
  86. temp_screen_params,
  87. config_path,
  88. img_folder
  89. )
  90. # 只计算平面度误差
  91. planarity_error = compute_planarity_error(reconstructed_points)
  92. total_error = planarity_error
  93. print(f"Planarity error: {planarity_error:.6f}")
  94. # 监控点云变化
  95. if hasattr(objective_function, 'prev_points'):
  96. point_changes = reconstructed_points - objective_function.prev_points
  97. print(f"Max point change: {np.max(np.abs(point_changes)):.8f}")
  98. print(f"Mean point change: {np.mean(np.abs(point_changes)):.8f}")
  99. objective_function.prev_points = reconstructed_points.copy()
  100. return total_error
  101. except Exception as e:
  102. print(f"Error in reconstruction: {str(e)}")
  103. import traceback
  104. traceback.print_exc()
  105. return 1e10
  106. except Exception as e:
  107. print(f"Error in parameter processing: {str(e)}")
  108. import traceback
  109. traceback.print_exc()
  110. return 1e10
  111. # 设置边界(只针对屏幕参数)
  112. bounds = []
  113. # 旋转矩阵边界
  114. for i in range(9):
  115. bounds.append((normalized_params[i]-0.5, normalized_params[i]+0.5))
  116. # 平移向量边界
  117. for i in range(3):
  118. bounds.append((normalized_params[i+9]-0.5, normalized_params[i+9]+0.5))
  119. # 优化
  120. result = minimize(
  121. objective_function,
  122. normalized_params,
  123. method='L-BFGS-B',
  124. bounds=bounds,
  125. options={
  126. 'maxiter': 100,
  127. 'ftol': 1e-8,
  128. 'gtol': 1e-8,
  129. 'disp': True,
  130. 'eps': 1e-3
  131. }
  132. )
  133. # 反归一化获取最终结果
  134. final_params = result.x * scale_factors
  135. # 构建最终的参数字典
  136. optimized_screen_params = {
  137. 'screen_matrix': screen_params['screen_matrix'],
  138. 'screen_distortion': screen_params['screen_distortion'],
  139. 'screen_rotation_matrix': final_params[:9].reshape(3, 3),
  140. 'screen_rotation_vector': cv2.Rodrigues(final_params[:9].reshape(3, 3))[0],
  141. 'screen_translation_vector': final_params[9:].reshape(3, 1)
  142. }
  143. print("\nOptimization completed!")
  144. print("Final screen parameters:")
  145. print(f"Rotation matrix:\n{optimized_screen_params['screen_rotation_matrix']}")
  146. print(f"Translation vector:\n{optimized_screen_params['screen_translation_vector']}")
  147. return cam_params, optimized_screen_params
  148. def compute_planarity_error(points):
  149. """计算点云的平面度误差"""
  150. # 移除中心
  151. centered_points = points - np.mean(points, axis=0)
  152. # 使用SVD找到最佳拟合平面
  153. _, s, vh = np.linalg.svd(centered_points)
  154. # 最奇异值表示点到平面的平均距离
  155. planarity_error = s[2] / len(points)
  156. return planarity_error
  157. # 在主程序中使用
  158. def optimize_parameters(cam_params, screen_params, point_cloud, gradient_data):
  159. """
  160. 优化参数的包装函数
  161. """
  162. print("开始优化标定参数...")
  163. # 保存原始参数
  164. original_cam_params = copy.deepcopy(cam_params)
  165. original_screen_params = copy.deepcopy(screen_params)
  166. try:
  167. # 执行优化
  168. new_cam_params, new_screen_params = optimize_calibration_with_gradient_constraint(
  169. cam_params,
  170. screen_params,
  171. point_cloud,
  172. gradient_data,
  173. config_path
  174. )
  175. # 打印优化前后的参数变化
  176. print("\n参数优化结果:")
  177. print("机内参变化:")
  178. print("原始值:\n", original_cam_params['camera_matrix'])
  179. print("优化后:\n", new_cam_params['camera_matrix'])
  180. print("\n屏幕姿态变化:")
  181. print("原始平移向量:", original_screen_params['screen_translation_vector'])
  182. print("优化后平移向量:", new_screen_params['screen_translation_vector'])
  183. return new_cam_params, new_screen_params
  184. except Exception as e:
  185. print("优化过程出错:")
  186. print(f"错误类型: {type(e).__name__}")
  187. print(f"错误信息: {str(e)}")
  188. print("错误详细信息:")
  189. import traceback
  190. traceback.print_exc()
  191. return original_cam_params, original_screen_params
  192. def optimization_callback(xk):
  193. """
  194. 优化过程的回调函数,用于监控优化进度
  195. """
  196. global iteration_count
  197. iteration_count += 1
  198. # 每10次迭代打印一次当前误差
  199. if iteration_count % 10 == 0:
  200. error = objective_function(xk)
  201. print(f"Iteration {iteration_count}, Error: {error:.6f}")
  202. # 可以保存中间结果
  203. points, grads = reconstruct_surface(...)
  204. np.save(f'intermediate_points_{iteration_count}.npy', points)
  205. np.save(f'intermediate_grads_{iteration_count}.npy', grads)
  206. def validate_optimization(original_points, original_grads,
  207. optimized_points, optimized_grads):
  208. """
  209. 验证优化结果
  210. """
  211. # 计算平面度改善
  212. original_planarity = compute_planarity_error(original_points)
  213. optimized_planarity = compute_planarity_error(optimized_points)
  214. # 计算梯度改善 - 使用法向量梯度
  215. original_gradient_error = np.sum(np.abs(original_grads[:, 2:])) # gx, gy
  216. optimized_gradient_error = np.sum(np.abs(optimized_grads[:, 2:]))
  217. print("\n优化结果验证:")
  218. print(f"平面度误差: {original_planarity:.6f} -> {optimized_planarity:.6f}")
  219. print(f"梯度误差: {original_gradient_error:.6f} -> {optimized_gradient_error:.6f}")
  220. # 可视化结
  221. fig = plt.figure(figsize=(15, 5))
  222. # 原始点云
  223. ax1 = fig.add_subplot(131, projection='3d')
  224. ax1.scatter(original_points[:, 0], original_points[:, 1], original_points[:, 2],
  225. c=original_grads[:, 2], cmap='viridis')
  226. ax1.set_title('Original Surface')
  227. # 优化后点云
  228. ax2 = fig.add_subplot(132, projection='3d')
  229. ax2.scatter(optimized_points[:, 0], optimized_points[:, 1], optimized_points[:, 2],
  230. c=optimized_grads[:, 2], cmap='viridis')
  231. ax2.set_title('Optimized Surface')
  232. # 梯度分布对比
  233. ax3 = fig.add_subplot(133)
  234. ax3.hist([original_grads[:, 2], optimized_grads[:, 2]],
  235. label=['Original', 'Optimized'], bins=50, alpha=0.7)
  236. ax3.set_title('Gradient Distribution')
  237. ax3.legend()
  238. plt.tight_layout()
  239. plt.show()
  240. def reconstruct_surface(cam_params, screen_params, config_path, img_folder):
  241. # 添加参数验证
  242. # print("\nDebug - reconstruct_surface input parameters:")
  243. # print("Camera parameters:")
  244. # print(f"Matrix:\n{cam_params[0]['camera_matrix']}")
  245. # print(f"Translation:\n{cam_params[0]['translation_vector']}")
  246. cfg = json.load(open(config_path, 'r'))
  247. n_cam = cfg['cam_num']
  248. grid_spacing = cfg['grid_spacing']
  249. num_freq = cfg['num_freq']
  250. x_uns, y_uns = [], []
  251. binary_masks = []
  252. for cam_id in range(n_cam):
  253. print('cam_id = ', cam_id)
  254. # 验证使用的是传入的参数而不是其他来源
  255. #print(f"\nUsing camera parameters for camera {cam_id}:")
  256. #print(f"Matrix:\n{cam_params[cam_id]['camera_matrix']}")
  257. white_path = os.path.join(img_folder, f'{cam_id}_frame_24.bmp')
  258. #binary = get_white_mask(white_path, bin_thresh=82, size_thresh=0.5, debug=0) #凹 凸 平晶 平面镜
  259. binary = get_white_mask(white_path, bin_thresh=40, size_thresh=0.8, debug=0)
  260. #binary = get_white_mask(white_path, bin_thresh=30, size_thresh=0.8, debug=0) #四相机
  261. binary_masks.append(binary)
  262. mtx = cam_params[cam_id]['camera_matrix']
  263. dist_coeffs = cam_params[cam_id]['distortion_coefficients']
  264. phases = extract_phase(img_folder, cam_id, binary, mtx, dist_coeffs, num_freq)
  265. x_un, y_un = unwrap_phase(phases, num_freq, debug=0)
  266. x_uns.append(x_un)
  267. y_uns.append(y_un)
  268. np.save('./x_phase_unwrapped_python.npy', x_un)
  269. np.save('./y_phase_unwrapped_python.npy', y_un)
  270. if n_cam == 1:
  271. #screen_to_world = map_screen_to_world(screen_params, cam_params[0], -30, 10, 80)
  272. #screen_to_world = map_screen_to_world(screen_params, cam_params[0], -10, -10, 20)
  273. screen_to_world = map_screen_to_world(screen_params, cam_params[0], 0, 0, 0)
  274. elif n_cam == 4:
  275. screen_to_world = map_screen_to_world(screen_params, cam_params[3], 0, 0, 0)
  276. else:
  277. print('camera number should be 1 or 4')
  278. return 0
  279. print("\n4. 获得不同坐标系下点的位置")
  280. total_cloud_point = np.empty((0, 3))
  281. total_gradient = np.empty((0, 4))
  282. for i in range(n_cam):
  283. print('cam_id = ', i)
  284. contours_point = get_meshgrid_contour(binary_masks[i], debug=0)
  285. world_points, world_points_boundary, world_points_boundary_3 = get_world_points(contours_point, cam_params[i], i, grid_spacing, cfg['d'], erosion_pixels=0, debug=0)
  286. camera_points, u_p, v_p = get_camera_points(world_points, cam_params[i], i, debug=0)
  287. point_data = {'x_w': world_points[:, 0], 'y_w': world_points[:, 1], 'z_w': world_points[:, 2],
  288. 'x_c': camera_points[:, 0], 'y_c': camera_points[:, 1], 'z_c': camera_points[:, 2],
  289. 'u_p': u_p, 'v_p': v_p}
  290. screen_points = get_screen_points(point_data, x_uns[i], y_uns[i], screen_to_world, cfg, i, debug=0)
  291. # 添加调试信息
  292. # print(f"\nDebug - Reconstruction:")
  293. # print(f"Camera points shape: {camera_points.shape}")
  294. # print(f"Screen points shape: {screen_points.shape}")
  295. #ds(world_points, camera_points, screen_points)
  296. #plot_coords(world_points, camera_points, screen_points)
  297. z1_cumsum, gradient_xy = reconstruction_cumsum(world_points, camera_points, screen_points, debug=0)
  298. write_point_cloud(os.path.join(img_folder, str(i) + '_cloudpoint.txt'), np.round(z1_cumsum[:, 0]), np.round(z1_cumsum[:, 1]), z1_cumsum[:, 2])
  299. np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
  300. total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z1_cumsum[:, 0], z1_cumsum[:, 1], z1_cumsum[:, 2]))])
  301. total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
  302. # 检查返回值
  303. # print(f"z1_cumsum shape: {z1_cumsum.shape}")
  304. # print(f"gradient_xy shape: {gradient_xy.shape}")
  305. # print(f"Sample z1_cumsum values:\n{z1_cumsum[:3]}")
  306. return total_cloud_point, total_gradient
  307. def main(config_path, img_folder):
  308. current_dir = os.path.dirname(os.path.abspath(__file__))
  309. os.chdir(current_dir)
  310. cfg = json.load(open(config_path, 'r'))
  311. n_cam = cfg['cam_num']
  312. matlab_align = 0
  313. if n_cam == 4:
  314. screen_img_path = 'D:\\data\\four_cam\\calibrate\\cam3-screen-1008'
  315. camera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1016'
  316. elif n_cam == 1:
  317. camera_img_path = 'D:\\data\\one_cam\\padtest1125\\test1\\'
  318. screen_img_path = 'D:\\data\\one_cam\\pad-test-1125\\test4\\calibration\\screen\\'
  319. print(f"开始执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  320. print("\n1. 机标定")
  321. preprocess_start = time.time()
  322. cam_para_path = os.path.join(current_dir, 'config', cfg['cam_params'])
  323. print('cam_para_path = ', cam_para_path)
  324. if os.path.exists(cam_para_path):
  325. #if False:
  326. with open(cam_para_path, 'rb') as pkl_file:
  327. cam_params = pickle.load(pkl_file)
  328. else:
  329. if n_cam == 4:
  330. cam_params = []
  331. camera_subdir = [item for item in os.listdir(camera_img_path) if os.path.isdir(os.path.join(camera_img_path, item))]
  332. camera_subdir.sort()
  333. assert len(camera_subdir) == 4, f"found {len(camera_subdir)} cameras, should be 4"
  334. for i in range(n_cam):
  335. cam_img_path = glob.glob(os.path.join(camera_img_path, camera_subdir[i], "*.bmp"))
  336. cam_img_path.sort()
  337. cam_param_raw = calibrate_world_aprilgrid(cam_img_path, cfg['world_chessboard_size'], cfg['world_square_size'], cfg['world_square_spacing'], debug=1)
  338. cam_params.append(cam_param_raw)
  339. with open(cam_para_path, 'wb') as pkl_file:
  340. pickle.dump(cam_params, pkl_file)
  341. elif n_cam == 1:
  342. cam_params = []
  343. cam_img_path = glob.glob(os.path.join(camera_img_path, "*.bmp"))
  344. cam_img_path.sort()
  345. if matlab_align:
  346. cfg['world_chessboard_size'] = [41, 40]
  347. cfg['world_square_size'] = 2
  348. cam_param_raw = calibrate_world(cam_img_path, cfg['world_chessboard_size'], cfg['world_square_size'], debug=1)
  349. cam_params.append(cam_param_raw)
  350. with open(cam_para_path, 'wb') as pkl_file:
  351. pickle.dump(cam_params, pkl_file)
  352. print('raw cam_param = ', cam_params)
  353. print("\n2. 屏幕标定")
  354. screen_cal_start = time.time()
  355. screen_img_path = glob.glob(os.path.join(screen_img_path, "*.bmp"))
  356. screen_para_path = os.path.join('config', cfg['screen_params'])
  357. if os.path.exists(screen_para_path):
  358. #if False:
  359. with open(screen_para_path, 'rb') as pkl_file:
  360. screen_params = pickle.load(pkl_file)
  361. else:
  362. if n_cam == 3:
  363. screen_params = calibrate_screen_chessboard(screen_img_path, cam_params[3]['camera_matrix'], cam_params[3]['distortion_coefficients'], cfg['screen_chessboard_size'], cfg['screen_square_size'], debug=0)
  364. elif n_cam == 1:
  365. raw_cam_mtx = cam_params[0]['camera_matrix']
  366. screen_params = calibrate_screen_circlegrid(screen_img_path, raw_cam_mtx, cam_params[0]['distortion_coefficients'], cfg['screen_chessboard_size'], cfg['screen_square_size'], debug=1)
  367. with open(screen_para_path, 'wb') as pkl_file:
  368. pickle.dump(screen_params, pkl_file)
  369. screen_cal_end = time.time()
  370. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  371. print(f" 耗时: {screen_cal_end - screen_cal_start:.2f} s")
  372. total_cloud_point, total_gradient = reconstruct_surface(cam_params, screen_params, config_path, img_folder)
  373. print("\n5. 后处理")
  374. post_process_start = time.time()
  375. total_cloud_point[:,0] = np.round(total_cloud_point[:,0])
  376. total_cloud_point[:,1] = np.round(total_cloud_point[:,1])
  377. #fitted_points = post_process(total_cloud_point, debug=0)
  378. clout_points = post_process_with_grad(img_folder, n_cam, 1)
  379. fitted_points = total_cloud_point
  380. align_fitted = fitted_points
  381. write_point_cloud(os.path.join(img_folder, 'cloudpoint.txt'), np.round(clout_points[:, 0]-np.mean(clout_points[:, 0])), np.round(clout_points[:, 1]-np.mean(clout_points[:, 1])), 1000 * clout_points[:,2])
  382. print("\n6. 评估")
  383. eval_start = time.time()
  384. point_cloud_path = os.path.join(img_folder, 'cloudpoint.txt')
  385. json_path = os.path.join(img_folder, 'result.json')
  386. theta_notch = 0
  387. get_eval_result(point_cloud_path, json_path, theta_notch, 1)
  388. eval_end = time.time()
  389. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  390. print(f" 耗时: {eval_end - eval_start:.2f} 秒")
  391. # new_cam_params, new_screen_params = optimize_parameters(
  392. # cam_params[0], # 假设单相系统
  393. # screen_params,
  394. # total_cloud_point,
  395. # total_gradient
  396. # )
  397. #print('after optimazation:', new_cam_params, new_screen_params)
  398. #total_cloud_point, total_gradient = reconstruct_surface(cam_params, screen_params, config_path)
  399. #print('cam_params = ', cam_params)
  400. #print('screen_params = ', screen_params)
  401. # print("\n3. 相位提取,相位展开")
  402. # phase_start = time.time()
  403. # scales = [0.995291, 0.993975, 0.993085, 0.994463]
  404. # scales = [1,1,1,1]
  405. # phase_end = time.time()
  406. # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  407. # print(f" 耗时: {phase_end - phase_start:.2f} 秒")
  408. # z_raw_xy = np.round(z_poisson[:, :2]).astype(int)
  409. # #创建布尔掩码,初始为 True
  410. # mask = np.ones(len(z_raw_xy), dtype=bool)
  411. # # 使用掩码过滤出非边界点
  412. # non_boundary_points = z_poisson[mask]
  413. # z_raw_aligned, _ = align2ref(non_boundary_points)
  414. # #non_boundary_points = smoothed
  415. # write_point_cloud(os.path.join(img_folder, str(i) + '_cloudpoint.txt'), np.round(z_raw_aligned[:, 0]), np.round(z_raw_aligned[:, 1]), z_raw_aligned[:, 2])
  416. # np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
  417. # total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z_raw_aligned[:, 0], z_raw_aligned[:, 1], z_raw_aligned[:, 2]))])
  418. # total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
  419. # get_point_end = time.time()
  420. # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  421. # print(f" 耗时: {get_point_end - get_point_start:.2f} 秒")
  422. # if 0:
  423. # fig = plt.figure()
  424. # ax = fig.add_subplot(111, projection='3d')
  425. # # 提取 x, y, z 坐标
  426. # x_vals = np.round(fitted_points[:, 0]-np.mean(fitted_points[:, 0]))
  427. # y_vals = np.round(fitted_points[:, 1]-np.mean(fitted_points[:, 1]))
  428. # z_vals = align_fitted[:,2]-np.min(align_fitted[:,2])
  429. # x_vals = fitted_points[:, 0]
  430. # y_vals = fitted_points[:, 1]
  431. # z_vals = fitted_points[:, 2]
  432. # # 绘制3D点云
  433. # ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
  434. # # 设置轴标签和标题
  435. # ax.set_xlabel('X (mm)')
  436. # ax.set_ylabel('Y (mm)')
  437. # ax.set_zlabel('Z (mm)')
  438. # ax.set_title('post 3D Point Cloud Visualization')
  439. # plt.show()
  440. # post_process_end = time.time()
  441. # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  442. # print(f" 耗时: {post_process_end - post_process_start:.2f} 秒")
  443. return True
  444. if __name__ == '__main__':
  445. #config_path = 'config\\cfg_3freq_wafer_1226.json'
  446. config_path = 'config\\cfg_3freq_wafer_1226.json'
  447. #config_path = 'config\\cfg_3freq_wafer_matlab.json'
  448. img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test4\\pingjing\\'
  449. img_folder = 'D:\\data\\one_cam\\pad-test-1106\\1104-test-other\\'
  450. #img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213183308114\\' #凸
  451. #img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213183451799\\' #凹
  452. img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213182959977\\' #平面镜
  453. img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241219180143344\\' #平晶
  454. #img_folder = 'D:\\data\\four_cam\\1223\\20241223134629640-0\\' #晶圆
  455. #img_folder = 'D:\\data\\four_cam\\1223\\20241223135156305-1\\' #晶圆
  456. #img_folder = 'D:\\data\\four_cam\\1223\\20241223135626457-2-0\\' #晶圆
  457. img_folder = 'D:\\data\\four_cam\\1223\\20241223135935517-2-1\\' #晶圆
  458. #img_folder = 'D:\\data\\four_cam\\1223\\20241223172437775-2-0\\' #晶圆
  459. #img_folder = 'D:\\data\\four_cam\\1223\\20241223172712226-2-1\\' #晶圆
  460. # img_folder = 'D:\\data\\four_cam\\1223\\20241223172931654-1\\' #晶圆
  461. img_folder = 'D:\\data\\four_cam\\1223\\20241223173521117-0\\' #晶圆
  462. #img_folder = 'D:\\data\\four_cam\\betone_1011\\20241011142901251-2\\'
  463. # img_folder = 'D:\\data\\one_cam\\1226image\\20241226142937478\\' #凹
  464. # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226143014962\\' #凸
  465. # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226143043070\\' #平面镜
  466. # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226142826690\\' #平晶
  467. # img_folder = 'D:\\data\\one_cam\\1226image\\20241226143916513\\' #晶圆
  468. # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226144357273\\'
  469. # img_folder = 'D:\\data\\one_cam\\1226image\\20241226144616239\\'
  470. img_folder = 'D:\\data\\one_cam\\betone1230\\20241230110516029\\'
  471. img_folder = 'D:\\data\\one_cam\\betone1230\\20241230110826833\\' #2
  472. #img_folder = 'D:\\data\\one_cam\\betone1230\\20241230111002224\\'
  473. #img_folder = 'D:\\data\\one_cam\\betone1230\\20250103151342402-pingjing\\'
  474. # img_folder = 'D:\\data\\one_cam\\betone1230\\20250102181845157-1\\'
  475. #img_folder = 'D:\\data\\one_cam\\betone1230\\20250102181648331-2\\'
  476. #img_folder = 'D:\\data\\one_cam\\betone1230\\20250102182008126-3\\'
  477. json_path = os.path.join(img_folder, 'result.json')
  478. pmdstart(config_path, img_folder)