pmd.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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, map_screen_to_world
  19. import argparse
  20. from src.vis import plot_coords
  21. import cv2
  22. from src.eval import get_eval_result
  23. import pickle
  24. from collections import defaultdict
  25. def pmdstart(config_path, img_folder):
  26. start_time = time.time()
  27. print(f"config_path: {config_path}")
  28. #time.sleep(15)
  29. main(config_path, img_folder)
  30. print(f"img_folder: {img_folder}")
  31. print('test pass')
  32. end_time = time.time()
  33. print(f"Time taken: {end_time - start_time} seconds")
  34. return True
  35. def main(config_path, img_folder):
  36. current_dir = os.path.dirname(os.path.abspath(__file__))
  37. os.chdir(current_dir)
  38. cfg = json.load(open(config_path, 'r'))
  39. n_cam = 4
  40. num_freq = cfg['num_freq']
  41. save_path = 'debug'
  42. debug = False
  43. grid_spacing = cfg['grid_spacing']
  44. num_freq = cfg['num_freq']
  45. smooth = True
  46. align = True
  47. denoise = True
  48. #cammera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1008'
  49. screen_img_path = 'D:\\data\\four_cam\\calibrate\\cam3-screen-1008'
  50. cammera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1016'
  51. #screen_img_path = 'D:\\data\\four_cam\\calibrate\\screen0920'
  52. print(f"开始执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  53. print("\n1. 相机标定")
  54. preprocess_start = time.time()
  55. #cam_para_path = os.path.join('config', cfg['cam_params'])
  56. cam_para_path = 'D:\\code\\pmd-python\\config\\cam_params.pkl'
  57. if os.path.exists(cam_para_path):
  58. #if False:
  59. with open(cam_para_path, 'rb') as pkl_file:
  60. cam_params = pickle.load(pkl_file)
  61. else:
  62. cam_params = []
  63. camera_subdir = [item for item in os.listdir(cammera_img_path) if os.path.isdir(os.path.join(cammera_img_path, item))]
  64. camera_subdir.sort()
  65. assert len(camera_subdir) == 4, f"found {len(camera_subdir)} cameras, should be 4"
  66. for i in range(n_cam):
  67. cam_img_path = glob.glob(os.path.join(cammera_img_path, camera_subdir[i], "*.bmp"))
  68. cam_img_path.sort()
  69. #print('cam_img_path = ', cam_img_path)
  70. cam_param_raw = calibrate_world(cam_img_path, i, cfg['world_chessboard_size'], cfg['world_square_size'], debug=0)
  71. cam_params.append(cam_param_raw)
  72. with open(cam_para_path, 'wb') as pkl_file:
  73. pickle.dump(cam_params, pkl_file)
  74. print("\n2. 屏幕标定")
  75. screen_cal_start = time.time()
  76. screen_img_path = glob.glob(os.path.join(screen_img_path, "*.bmp"))
  77. screen_para_path = os.path.join('config', cfg['screen_params'])
  78. if os.path.exists(screen_para_path):
  79. #if False:
  80. with open(screen_para_path, 'rb') as pkl_file:
  81. screen_params = pickle.load(pkl_file)[0]
  82. else:
  83. screen_params = calibrate_screen(screen_img_path, cam_params[3]['camera_matrix'], cam_params[3]['distortion_coefficients'], cfg['screen_chessboard_size'], cfg['screen_square_size'], debug=0)
  84. with open(screen_para_path, 'wb') as pkl_file:
  85. pickle.dump([screen_params], pkl_file)
  86. screen_to_world = map_screen_to_world(screen_params, cam_params[3])
  87. screen_cal_end = time.time()
  88. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  89. print(f" 耗时: {screen_cal_end - screen_cal_start:.2f} 秒")
  90. print("\n3. 相位提取,相位展开")
  91. phase_start = time.time()
  92. x_uns, y_uns = [], []
  93. binary_masks = []
  94. for cam_id in range(n_cam):
  95. print('cam_id = ', cam_id)
  96. white_path = os.path.join(img_folder, f'{cam_id}_frame_24.bmp')
  97. binary = get_white_mask(white_path, bin_thresh=12, debug=0)
  98. binary_masks.append(binary)
  99. phases = extract_phase(img_folder, cam_id, binary, cam_params[cam_id]['camera_matrix'], cam_params[cam_id]['distortion_coefficients'], num_freq=num_freq)
  100. x_un, y_un = unwrap_phase(phases, save_path, num_freq, debug=0)
  101. x_uns.append(x_un)
  102. y_uns.append(y_un)
  103. phase_end = time.time()
  104. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  105. print(f" 耗时: {phase_end - phase_start:.2f} 秒")
  106. print("\n4. 获得不同坐标系下点的位置")
  107. get_point_start = time.time()
  108. total_cloud_point = np.empty((0, 3))
  109. total_gradient = np.empty((0, 4))
  110. total_boundary_point = np.empty((0, 3))
  111. for i in range(n_cam):
  112. print('cam_id = ', i)
  113. contours_point = get_meshgrid_contour(binary_masks[i], save_path, debug=False)
  114. world_points, world_points_boundary, world_points_boundary_3 = get_world_points(contours_point, cam_params[i], i, grid_spacing, cfg['d'], erosion_pixels=2, debug=0)
  115. camera_points, u_p, v_p = get_camera_points(world_points, cam_params[i], save_path, i, debug=0)
  116. point_data = {'x_w': world_points[:, 0], 'y_w': world_points[:, 1], 'z_w': world_points[:, 2],
  117. 'x_c': camera_points[:, 0], 'y_c': camera_points[:, 1], 'z_c': camera_points[:, 2],
  118. 'u_p': u_p, 'v_p': v_p}
  119. screen_points = get_screen_points(point_data, x_uns[i], y_uns[i], screen_params, screen_to_world, cfg, save_path, i, debug=debug)
  120. #plot_coords(world_points, camera_points, screen_points)
  121. z_raw, aligned, smoothed, denoised, gradient_xy = reconstruction_cumsum(world_points, camera_points, screen_points, save_path, i, debug=0, smooth=smooth, align=align, denoise=denoise)
  122. z_raw_xy = np.round(z_raw[:, :2]).astype(int)
  123. # # 创建布尔掩码,初始为 True
  124. # mask = np.ones(len(z_raw_xy), dtype=bool)
  125. # # 遍历每个边界点,标记它们在 aligned 中的位置
  126. # for boundary_point in world_points_boundary:
  127. # # 标记与当前边界点相同 xy 坐标的行
  128. # mask &= ~np.all(z_raw_xy == boundary_point[:2], axis=1)
  129. # # 使用掩码过滤出非边界点
  130. # non_boundary_points = z_raw[mask]
  131. # non_boundary_aligned, rotation_matrix = align2ref(non_boundary_points)
  132. # 创建布尔掩码,初始为 True
  133. mask = np.ones(len(z_raw_xy), dtype=bool)
  134. # 遍历每个边界点,标记它们在 aligned 中的位置
  135. for boundary_point in world_points_boundary_3:
  136. # 标记与当前边界点相同 xy 坐标的行
  137. mask &= ~np.all(z_raw_xy == boundary_point[:2], axis=1)
  138. # 使用掩码过滤出非边界点
  139. non_boundary_points = z_raw[mask]
  140. # z_raw_aligned = non_boundary_points @ rotation_matrix.T
  141. # z_raw_aligned[:,2] = z_raw_aligned[:,2] - np.mean(z_raw_aligned[:, 2])
  142. z_raw_aligned = non_boundary_points
  143. #non_boundary_points = smoothed
  144. write_point_cloud(os.path.join(img_folder, str(i) + '_cloudpoint.txt'), np.round(z_raw_aligned[:, 0]), np.round(z_raw_aligned[:, 1]), 1000*z_raw_aligned[:, 2])
  145. np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
  146. total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z_raw_aligned[:, 0], z_raw_aligned[:, 1], 1000*z_raw_aligned[:, 2]))])
  147. total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
  148. if 0:
  149. fig = plt.figure()
  150. ax = fig.add_subplot(111, projection='3d')
  151. # 提取 x, y, z 坐标
  152. x_vals = total_cloud_point[:, 0]
  153. y_vals = total_cloud_point[:, 1]
  154. z_vals = total_cloud_point[:, 2]
  155. # 绘制3D点云
  156. ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
  157. # 设置轴标签和标题
  158. ax.set_xlabel('X (mm)')
  159. ax.set_ylabel('Y (mm)')
  160. ax.set_zlabel('Z (mm)')
  161. ax.set_title('3D Point Cloud Visualization gradient')
  162. plt.show()
  163. # fig = plt.figure()
  164. # ax = fig.add_subplot(111, projection='3d')
  165. # smoothed_total = smooth_pcl(total_cloud_point, 3)
  166. # # 提取 x, y, z 坐标
  167. # x_vals = smoothed_total[:, 0]
  168. # y_vals = smoothed_total[:, 1]
  169. # z_vals = smoothed_total[:, 2]
  170. # # 绘制3D点云
  171. # ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
  172. # # 设置轴标签和标题
  173. # ax.set_xlabel('X (mm)')
  174. # ax.set_ylabel('Y (mm)')
  175. # ax.set_zlabel('Z (mm)')
  176. # ax.set_title('smoothed 3D Point Cloud Visualization')
  177. get_point_end = time.time()
  178. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  179. print(f" 耗时: {get_point_end - get_point_start:.2f} 秒")
  180. print("\n5. 后处理")
  181. post_process_start = time.time()
  182. total_cloud_point[:,0] = np.round(total_cloud_point[:,0])
  183. total_cloud_point[:,1] = np.round(total_cloud_point[:,1])
  184. #fitted_points = post_process(total_cloud_point, debug=0)
  185. fitted_points = post_process_with_grad(img_folder, 0)
  186. #fitted_points = total_cloud_point
  187. #align_fitted, _ = align2ref(fitted_points)
  188. align_fitted = fitted_points
  189. write_point_cloud(os.path.join(img_folder, 'cloudpoint.txt'), np.round(align_fitted[:, 0]-np.mean(align_fitted[:, 0])), np.round(align_fitted[:, 1]-np.mean(align_fitted[:, 1])), align_fitted[:,2]-np.min(align_fitted[:,2]))
  190. if 0:
  191. fig = plt.figure()
  192. ax = fig.add_subplot(111, projection='3d')
  193. # 提取 x, y, z 坐标
  194. x_vals = np.round(fitted_points[:, 0]-np.mean(fitted_points[:, 0]))
  195. y_vals = np.round(fitted_points[:, 1]-np.mean(fitted_points[:, 1]))
  196. z_vals = align_fitted[:,2]-np.min(align_fitted[:,2])
  197. # 绘制3D点云
  198. ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
  199. # 设置轴标签和标题
  200. ax.set_xlabel('X (mm)')
  201. ax.set_ylabel('Y (mm)')
  202. ax.set_zlabel('Z (mm)')
  203. ax.set_title('3D Point Cloud Visualization')
  204. plt.show()
  205. post_process_end = time.time()
  206. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  207. print(f" 耗时: {post_process_end - post_process_start:.2f} 秒")
  208. print("\n6. 评估")
  209. eval_start = time.time()
  210. point_cloud_path = os.path.join(img_folder, 'cloudpoint.txt')
  211. json_path = os.path.join(img_folder, 'result.json')
  212. theta_notch = 0
  213. get_eval_result(point_cloud_path, json_path, theta_notch, 0)
  214. eval_end = time.time()
  215. print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  216. print(f" 耗时: {eval_end - eval_start:.2f} 秒")
  217. return True
  218. if __name__ == '__main__':
  219. config_path = 'config\\cfg_3freq_wafer.json'
  220. #img_folder = 'D:\\data\\four_cam\\1008_storage\\pingjing_20241017092315228\\' #'D:\\data\\four_cam\\betone_1011\\20241011142348762-1'
  221. # img_folder = 'D:\\huchao\\inspect_server_202409241013_py\\storage\\20241023193453708\\'
  222. img_folder = 'D:\\data\\four_cam\\betone_1011\\20241011144821292-4\\'
  223. json_path = os.path.join(img_folder, 'result.json')
  224. # 20241011142348762-1 20241011142901251-2 20241011143925746-3 20241011144821292-4
  225. # 0.60 0.295 0.221 0.346
  226. # x max = 653.5925
  227. # y max = 692.1735648
  228. # x max = 251.0775
  229. # y max = 293.05856482
  230. # x max = 184.7275
  231. # y max = 239.00919669
  232. # x max = 342.2525
  233. # y max = 386.92087185
  234. pmdstart(config_path, img_folder)
  235. #fitted_points = post_process_with_grad(img_folder, 1)