|
@@ -17,7 +17,8 @@ from src.phase import extract_phase, unwrap_phase
|
17
|
17
|
from src.recons import reconstruction_cumsum, poisson_recons_with_smoothed_gradients
|
18
|
18
|
from src.pcl_postproc import smooth_pcl, align2ref
|
19
|
19
|
import matplotlib.pyplot as plt
|
20
|
|
-from src.calibration import calibrate_world, calibrate_screen, map_screen_to_world
|
|
20
|
+from src.calibration import calibrate_world, calibrate_screen_chessboard, calibrate_screen_circlegrid, map_screen_to_world
|
|
21
|
+from src.calibration.get_camera_params import calibrate_world_aprilgrid
|
21
|
22
|
import argparse
|
22
|
23
|
from src.vis import plot_coords
|
23
|
24
|
import cv2
|
|
@@ -25,6 +26,8 @@ from src.eval import get_eval_result
|
25
|
26
|
import pickle
|
26
|
27
|
from collections import defaultdict
|
27
|
28
|
from scipy.io import loadmat, savemat
|
|
29
|
+from scipy.optimize import minimize
|
|
30
|
+import copy
|
28
|
31
|
|
29
|
32
|
|
30
|
33
|
|
|
@@ -40,359 +43,570 @@ def pmdstart(config_path, img_folder):
|
40
|
43
|
return True
|
41
|
44
|
|
42
|
45
|
|
43
|
|
-def main(config_path, img_folder):
|
44
|
|
- current_dir = os.path.dirname(os.path.abspath(__file__))
|
45
|
|
- os.chdir(current_dir)
|
|
46
|
+def optimize_calibration_with_gradient_constraint(cam_params, screen_params, point_cloud, gradient_data, config_path):
|
|
47
|
+ # 只使用屏幕参数(旋转矩阵和平移向量)
|
|
48
|
+ initial_params = np.concatenate([
|
|
49
|
+ screen_params['screen_rotation_matrix'].flatten(),
|
|
50
|
+ screen_params['screen_translation_vector'].flatten()
|
|
51
|
+ ])
|
46
|
52
|
|
47
|
|
- cfg = json.load(open(config_path, 'r'))
|
48
|
|
- n_cam = cfg['cam_num']
|
49
|
|
- num_freq = cfg['num_freq']
|
50
|
|
- save_path = 'debug'
|
51
|
|
- debug = False
|
52
|
|
- grid_spacing = cfg['grid_spacing']
|
53
|
|
- num_freq = cfg['num_freq']
|
54
|
|
- smooth = False
|
55
|
|
- align = False
|
56
|
|
- denoise = False
|
57
|
|
- #cammera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1008'
|
58
|
|
- screen_img_path = 'D:\\data\\four_cam\\calibrate\\cam3-screen-1008'
|
59
|
|
- cammera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1016'
|
60
|
|
- #screen_img_path = 'D:\\data\\four_cam\\calibrate\\screen0920'
|
61
|
|
-
|
62
|
|
- print(f"开始执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
63
|
|
- print("\n1. 相机标定")
|
64
|
|
- preprocess_start = time.time()
|
|
53
|
+ # 定义屏幕参数的尺度因子
|
|
54
|
+ scale_factors = np.ones_like(initial_params)
|
|
55
|
+ scale_factors[0:9] = 1.0 # 旋转矩阵
|
|
56
|
+ scale_factors[9:] = 100.0 # 平移向量(假设单位是毫米)
|
65
|
57
|
|
66
|
|
- cam_para_path = os.path.join(current_dir, 'config', cfg['cam_params'])
|
67
|
|
- print('cam_para_path = ', cam_para_path)
|
68
|
|
- print('current_dir = ', current_dir)
|
69
|
|
- #cam_para_path = 'D:\\code\\pmd-python\\config\\cam_params.pkl'
|
70
|
|
- if os.path.exists(cam_para_path):
|
71
|
|
- #if False:
|
72
|
|
- with open(cam_para_path, 'rb') as pkl_file:
|
73
|
|
- cam_params = pickle.load(pkl_file)
|
74
|
|
- else:
|
75
|
|
- cam_params = []
|
76
|
|
- camera_subdir = [item for item in os.listdir(cammera_img_path) if os.path.isdir(os.path.join(cammera_img_path, item))]
|
77
|
|
- camera_subdir.sort()
|
78
|
|
- assert len(camera_subdir) == 4, f"found {len(camera_subdir)} cameras, should be 4"
|
79
|
|
- for i in range(n_cam):
|
80
|
|
- cam_img_path = glob.glob(os.path.join(cammera_img_path, camera_subdir[i], "*.bmp"))
|
81
|
|
- cam_img_path.sort()
|
82
|
|
- #print('cam_img_path = ', cam_img_path)
|
83
|
|
- cam_param_raw = calibrate_world(cam_img_path, i, cfg['world_chessboard_size'], cfg['world_square_size'], debug=0)
|
84
|
|
- cam_params.append(cam_param_raw)
|
85
|
|
- # with open(cam_para_path, 'wb') as pkl_file:
|
86
|
|
- # pickle.dump(cam_params, pkl_file)
|
|
58
|
+ # 归一化初始参数
|
|
59
|
+ normalized_params = initial_params / scale_factors
|
|
60
|
+ iteration_count = [0]
|
87
|
61
|
|
88
|
|
- print("\n2. 屏幕标定")
|
89
|
|
- screen_cal_start = time.time()
|
|
62
|
+ print("\nInitial screen parameters:")
|
|
63
|
+ print(f"Rotation matrix:\n{screen_params['screen_rotation_matrix']}")
|
|
64
|
+ print(f"Translation vector:\n{screen_params['screen_translation_vector']}")
|
90
|
65
|
|
91
|
|
- screen_img_path = glob.glob(os.path.join(screen_img_path, "*.bmp"))
|
92
|
|
- screen_para_path = os.path.join('config', cfg['screen_params'])
|
93
|
|
- if os.path.exists(screen_para_path):
|
94
|
|
- #if False:
|
95
|
|
- with open(screen_para_path, 'rb') as pkl_file:
|
96
|
|
- screen_params = pickle.load(pkl_file)[0]
|
97
|
|
- else:
|
98
|
|
- 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)
|
99
|
|
- # with open(screen_para_path, 'wb') as pkl_file:
|
100
|
|
- # pickle.dump([screen_params], pkl_file)
|
|
66
|
+ def objective_function(normalized_params):
|
|
67
|
+ try:
|
|
68
|
+ # 反归一化参数
|
|
69
|
+ params = normalized_params * scale_factors
|
|
70
|
+
|
|
71
|
+ iteration_count[0] += 1
|
|
72
|
+ print(f"\nIteration {iteration_count[0]}:")
|
|
73
|
+
|
|
74
|
+ # 解析屏幕参数
|
|
75
|
+ screen_R = params[:9].reshape(3, 3)
|
|
76
|
+ screen_T = params[9:].reshape(3, 1)
|
|
77
|
+
|
|
78
|
+ # 构建参数字典
|
|
79
|
+ temp_cam_params = [{
|
|
80
|
+ 'camera_matrix': cam_params['camera_matrix'],
|
|
81
|
+ 'distortion_coefficients': cam_params['distortion_coefficients'],
|
|
82
|
+ 'rotation_matrix': cam_params['rotation_matrix'],
|
|
83
|
+ 'rotation_vector': cam_params['rotation_vector'],
|
|
84
|
+ 'translation_vector': cam_params['translation_vector']
|
|
85
|
+ }]
|
|
86
|
+
|
|
87
|
+ temp_screen_params = {
|
|
88
|
+ 'screen_matrix': screen_params['screen_matrix'],
|
|
89
|
+ 'screen_distortion': screen_params['screen_distortion'],
|
|
90
|
+ 'screen_rotation_matrix': screen_R,
|
|
91
|
+ 'screen_rotation_vector': cv2.Rodrigues(screen_R)[0],
|
|
92
|
+ 'screen_translation_vector': screen_T
|
|
93
|
+ }
|
|
94
|
+
|
|
95
|
+ if iteration_count[0] % 5 == 0: # 每5次迭代打印一次详细信息
|
|
96
|
+ print("\nCurrent screen parameters:")
|
|
97
|
+ print(f"Rotation matrix:\n{screen_R}")
|
|
98
|
+ print(f"Translation vector:\n{screen_T.flatten()}")
|
|
99
|
+
|
|
100
|
+ try:
|
|
101
|
+ reconstructed_points, reconstructed_gradients = reconstruct_surface(
|
|
102
|
+ temp_cam_params,
|
|
103
|
+ temp_screen_params,
|
|
104
|
+ config_path,
|
|
105
|
+ img_folder
|
|
106
|
+ )
|
|
107
|
+
|
|
108
|
+ # 只计算平面度误差
|
|
109
|
+ planarity_error = compute_planarity_error(reconstructed_points)
|
|
110
|
+ total_error = planarity_error
|
|
111
|
+
|
|
112
|
+ print(f"Planarity error: {planarity_error:.6f}")
|
|
113
|
+
|
|
114
|
+ # 监控点云变化
|
|
115
|
+ if hasattr(objective_function, 'prev_points'):
|
|
116
|
+ point_changes = reconstructed_points - objective_function.prev_points
|
|
117
|
+ print(f"Max point change: {np.max(np.abs(point_changes)):.8f}")
|
|
118
|
+ print(f"Mean point change: {np.mean(np.abs(point_changes)):.8f}")
|
|
119
|
+ objective_function.prev_points = reconstructed_points.copy()
|
|
120
|
+
|
|
121
|
+ return total_error
|
|
122
|
+
|
|
123
|
+ except Exception as e:
|
|
124
|
+ print(f"Error in reconstruction: {str(e)}")
|
|
125
|
+ import traceback
|
|
126
|
+ traceback.print_exc()
|
|
127
|
+ return 1e10
|
|
128
|
+
|
|
129
|
+ except Exception as e:
|
|
130
|
+ print(f"Error in parameter processing: {str(e)}")
|
|
131
|
+ import traceback
|
|
132
|
+ traceback.print_exc()
|
|
133
|
+ return 1e10
|
|
134
|
+
|
|
135
|
+ # 设置边界(只针对屏幕参数)
|
|
136
|
+ bounds = []
|
|
137
|
+ # 旋转矩阵边界
|
|
138
|
+ for i in range(9):
|
|
139
|
+ bounds.append((normalized_params[i]-0.5, normalized_params[i]+0.5))
|
|
140
|
+ # 平移向量边界
|
|
141
|
+ for i in range(3):
|
|
142
|
+ bounds.append((normalized_params[i+9]-0.5, normalized_params[i+9]+0.5))
|
|
143
|
+
|
|
144
|
+ # 优化
|
|
145
|
+ result = minimize(
|
|
146
|
+ objective_function,
|
|
147
|
+ normalized_params,
|
|
148
|
+ method='L-BFGS-B',
|
|
149
|
+ bounds=bounds,
|
|
150
|
+ options={
|
|
151
|
+ 'maxiter': 100,
|
|
152
|
+ 'ftol': 1e-8,
|
|
153
|
+ 'gtol': 1e-8,
|
|
154
|
+ 'disp': True,
|
|
155
|
+ 'eps': 1e-3
|
|
156
|
+ }
|
|
157
|
+ )
|
|
158
|
+
|
|
159
|
+ # 反归一化获取最终结果
|
|
160
|
+ final_params = result.x * scale_factors
|
101
|
161
|
|
|
162
|
+ # 构建最终的参数字典
|
|
163
|
+ optimized_screen_params = {
|
|
164
|
+ 'screen_matrix': screen_params['screen_matrix'],
|
|
165
|
+ 'screen_distortion': screen_params['screen_distortion'],
|
|
166
|
+ 'screen_rotation_matrix': final_params[:9].reshape(3, 3),
|
|
167
|
+ 'screen_rotation_vector': cv2.Rodrigues(final_params[:9].reshape(3, 3))[0],
|
|
168
|
+ 'screen_translation_vector': final_params[9:].reshape(3, 1)
|
|
169
|
+ }
|
102
|
170
|
|
103
|
|
- screen_cal_end = time.time()
|
104
|
|
- print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
105
|
|
- print(f" 耗时: {screen_cal_end - screen_cal_start:.2f} 秒")
|
106
|
|
-
|
107
|
|
- print("\n3. 相位提取,相位展开")
|
108
|
|
- phase_start = time.time()
|
109
|
|
- x_uns, y_uns = [], []
|
110
|
|
- binary_masks = []
|
111
|
|
- for cam_id in range(n_cam):
|
112
|
|
- print('cam_id = ', cam_id)
|
113
|
|
- #white_path = os.path.join(img_folder, f'{cam_id}_frame_24.bmp')
|
114
|
|
- white_path = 'D:\\code\\code of PMD\\code of PMD\\picture\\white.bmp'
|
115
|
|
- if n_cam == 3:
|
116
|
|
- binary = get_white_mask(white_path, bin_thresh=12, debug=0)
|
117
|
|
-
|
118
|
|
- elif n_cam == 1:
|
119
|
|
- #angle_rad, binary = find_notch(white_path, n_cam, debug=0)
|
120
|
|
- binary = get_white_mask(white_path, bin_thresh=12, debug=0)
|
121
|
|
-
|
122
|
|
- binary_masks.append(binary)
|
|
171
|
+ print("\nOptimization completed!")
|
|
172
|
+ print("Final screen parameters:")
|
|
173
|
+ print(f"Rotation matrix:\n{optimized_screen_params['screen_rotation_matrix']}")
|
|
174
|
+ print(f"Translation vector:\n{optimized_screen_params['screen_translation_vector']}")
|
|
175
|
+
|
|
176
|
+ return cam_params, optimized_screen_params
|
123
|
177
|
|
124
|
|
- #phases = extract_phase(img_folder, cam_id, binary, cam_params[cam_id]['camera_matrix'], cam_params[cam_id]['distortion_coefficients'], num_freq=num_freq)
|
125
|
|
- #x_un, y_un = unwrap_phase(phases, save_path, num_freq, debug=0)
|
|
178
|
+def compute_planarity_error(points):
|
|
179
|
+ """计算点云的平面度误差"""
|
|
180
|
+ # 移除中心
|
|
181
|
+ centered_points = points - np.mean(points, axis=0)
|
|
182
|
+
|
|
183
|
+ # 使用SVD找到最佳拟合平面
|
|
184
|
+ _, s, vh = np.linalg.svd(centered_points)
|
|
185
|
+
|
|
186
|
+ # 最奇异值表示点到平面的平均距离
|
|
187
|
+ planarity_error = s[2] / len(points)
|
|
188
|
+
|
|
189
|
+ return planarity_error
|
|
190
|
+
|
|
191
|
+# 在主程序中使用
|
|
192
|
+def optimize_parameters(cam_params, screen_params, point_cloud, gradient_data):
|
|
193
|
+ """
|
|
194
|
+ 优化参数的包装函数
|
|
195
|
+ """
|
|
196
|
+ print("开始优化标定参数...")
|
|
197
|
+
|
|
198
|
+ # 保存原始参数
|
|
199
|
+ original_cam_params = copy.deepcopy(cam_params)
|
|
200
|
+ original_screen_params = copy.deepcopy(screen_params)
|
|
201
|
+
|
|
202
|
+ try:
|
|
203
|
+ # 执行优化
|
|
204
|
+ new_cam_params, new_screen_params = optimize_calibration_with_gradient_constraint(
|
|
205
|
+ cam_params,
|
|
206
|
+ screen_params,
|
|
207
|
+ point_cloud,
|
|
208
|
+ gradient_data,
|
|
209
|
+ config_path
|
|
210
|
+ )
|
126
|
211
|
|
127
|
|
- #x_uns.append(x_un)
|
128
|
|
- #y_uns.append(y_un)
|
129
|
|
-
|
130
|
|
- phase_end = time.time()
|
131
|
|
- print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
132
|
|
- print(f" 耗时: {phase_end - phase_start:.2f} 秒")
|
|
212
|
+ # 打印优化前后的参数变化
|
|
213
|
+ print("\n参数优化结果:")
|
|
214
|
+ print("机内参变化:")
|
|
215
|
+ print("原始值:\n", original_cam_params['camera_matrix'])
|
|
216
|
+ print("优化后:\n", new_cam_params['camera_matrix'])
|
|
217
|
+
|
|
218
|
+ print("\n屏幕姿态变化:")
|
|
219
|
+ print("原始平移向量:", original_screen_params['screen_translation_vector'])
|
|
220
|
+ print("优化后平移向量:", new_screen_params['screen_translation_vector'])
|
|
221
|
+
|
|
222
|
+ return new_cam_params, new_screen_params
|
|
223
|
+
|
|
224
|
+ except Exception as e:
|
|
225
|
+ print("优化过程出错:")
|
|
226
|
+ print(f"错误类型: {type(e).__name__}")
|
|
227
|
+ print(f"错误信息: {str(e)}")
|
|
228
|
+ print("错误详细信息:")
|
|
229
|
+ import traceback
|
|
230
|
+ traceback.print_exc()
|
|
231
|
+ return original_cam_params, original_screen_params
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+def optimization_callback(xk):
|
|
235
|
+ """
|
|
236
|
+ 优化过程的回调函数,用于监控优化进度
|
|
237
|
+ """
|
|
238
|
+ global iteration_count
|
|
239
|
+ iteration_count += 1
|
133
|
240
|
|
134
|
|
- # matlab align
|
135
|
|
- #cam_params = loadmat('D:\\code\\code of PMD\\code of PMD\\calibration\\calibrationSessionworld.mat')
|
136
|
|
- #screen_params = loadmat('D:\\code\\code of PMD\\code of PMD\\calibration\\calibrationSessionscreen.mat')
|
137
|
|
-
|
138
|
|
- #print('cam_params = ', cam_params)
|
139
|
|
- #print('screen_params = ', screen_params)
|
|
241
|
+ # 每10次迭代打印一次当前误差
|
|
242
|
+ if iteration_count % 10 == 0:
|
|
243
|
+ error = objective_function(xk)
|
|
244
|
+ print(f"Iteration {iteration_count}, Error: {error:.6f}")
|
|
245
|
+
|
|
246
|
+ # 可以保存中间结果
|
|
247
|
+ points, grads = reconstruct_surface(...)
|
|
248
|
+ np.save(f'intermediate_points_{iteration_count}.npy', points)
|
|
249
|
+ np.save(f'intermediate_grads_{iteration_count}.npy', grads)
|
140
|
250
|
|
141
|
|
- cam_params = []
|
142
|
|
- screen_params = []
|
143
|
|
- mtx = np.array([[6944.89018564351, 0, 2709.44699784446], [0, 6942.91962497637, 1882.05677580185], [0,0,1]])
|
144
|
|
- R = cv2.Rodrigues(np.array([0.0732148059333282,-0.265812028310130,-0.0532640604086260]).reshape(3,1))[0]
|
145
|
|
- T = np.array([-15.179977,-42.247126,246.92182]).reshape(3,1)
|
146
|
|
-
|
147
|
|
- cam_calibration_data = {
|
148
|
|
- 'camera_matrix': mtx,
|
149
|
|
- 'distortion_coefficients': 0,
|
150
|
|
- 'rotation_matrix': R,
|
151
|
|
- 'translation_vector': T,
|
152
|
|
- 'error': 0
|
153
|
|
- }
|
154
|
251
|
|
155
|
|
- mtx = np.array([[6944.89018564351, 0, 2709.44699784446], [0, 6942.91962497637, 1882.05677580185], [0,0,1]])
|
156
|
|
- R = np.array([[0.96514996,-0.042578806,0.25821037],[0.029285983,0.99805061,0.055111798],[-0.26005361,-0.045629206,0.96451547]])
|
157
|
|
- T = np.array([30.1970,-49.3108,507.4424]).reshape(3,1)
|
158
|
|
-
|
159
|
|
- screen_calibration_data = {
|
160
|
|
- 'screen_matrix': mtx,
|
161
|
|
- 'screen_distortion': 0,
|
162
|
|
- 'screen_rotation_matrix': R,
|
163
|
|
- 'screen_translation_vector': T,
|
164
|
|
- 'screen_error': 0
|
165
|
|
- }
|
166
|
252
|
|
|
253
|
+def validate_optimization(original_points, original_grads,
|
|
254
|
+ optimized_points, optimized_grads):
|
|
255
|
+ """
|
|
256
|
+ 验证优化结果
|
|
257
|
+ """
|
|
258
|
+ # 计算平面度改善
|
|
259
|
+ original_planarity = compute_planarity_error(original_points)
|
|
260
|
+ optimized_planarity = compute_planarity_error(optimized_points)
|
|
261
|
+
|
|
262
|
+ # 计算梯度改善 - 使用法向量梯度
|
|
263
|
+ original_gradient_error = np.sum(np.abs(original_grads[:, 2:])) # gx, gy
|
|
264
|
+ optimized_gradient_error = np.sum(np.abs(optimized_grads[:, 2:]))
|
|
265
|
+
|
|
266
|
+ print("\n优化结果验证:")
|
|
267
|
+ print(f"平面度误差: {original_planarity:.6f} -> {optimized_planarity:.6f}")
|
|
268
|
+ print(f"梯度误差: {original_gradient_error:.6f} -> {optimized_gradient_error:.6f}")
|
167
|
269
|
|
168
|
|
- cam_params.append(cam_calibration_data)
|
169
|
|
- #screen_params.append(screen_calibration_data)
|
170
|
|
- screen_params = screen_calibration_data
|
|
270
|
+ # 可视化结
|
|
271
|
+ fig = plt.figure(figsize=(15, 5))
|
|
272
|
+
|
|
273
|
+ # 原始点云
|
|
274
|
+ ax1 = fig.add_subplot(131, projection='3d')
|
|
275
|
+ ax1.scatter(original_points[:, 0], original_points[:, 1], original_points[:, 2],
|
|
276
|
+ c=original_grads[:, 2], cmap='viridis')
|
|
277
|
+ ax1.set_title('Original Surface')
|
|
278
|
+
|
|
279
|
+ # 优化后点云
|
|
280
|
+ ax2 = fig.add_subplot(132, projection='3d')
|
|
281
|
+ ax2.scatter(optimized_points[:, 0], optimized_points[:, 1], optimized_points[:, 2],
|
|
282
|
+ c=optimized_grads[:, 2], cmap='viridis')
|
|
283
|
+ ax2.set_title('Optimized Surface')
|
|
284
|
+
|
|
285
|
+ # 梯度分布对比
|
|
286
|
+ ax3 = fig.add_subplot(133)
|
|
287
|
+ ax3.hist([original_grads[:, 2], optimized_grads[:, 2]],
|
|
288
|
+ label=['Original', 'Optimized'], bins=50, alpha=0.7)
|
|
289
|
+ ax3.set_title('Gradient Distribution')
|
|
290
|
+ ax3.legend()
|
|
291
|
+
|
|
292
|
+ plt.tight_layout()
|
|
293
|
+ plt.show()
|
171
|
294
|
|
172
|
|
- x_un = loadmat('D:\\code\\code of PMD\\code of PMD\\phase_information\\x_phase_unwrapped.mat')
|
173
|
|
- y_un = loadmat('D:\\code\\code of PMD\\code of PMD\\phase_information\\y_phase_unwrapped.mat')
|
174
|
295
|
|
175
|
|
- x_un = x_un['x_phase_unwrapped']
|
176
|
|
- y_un = y_un['y_phase_unwrapped']
|
177
|
296
|
|
178
|
|
- x_uns, y_uns = [], []
|
179
|
|
- x_uns.append(x_un)
|
180
|
|
- y_uns.append(y_un)
|
181
|
|
-
|
182
|
|
- #fig, axes = plt.subplots(1, 2, figsize=(12, 6))
|
183
|
297
|
|
|
298
|
+def reconstruct_surface(cam_params, screen_params, config_path, img_folder):
|
|
299
|
+ # 添加参数验证
|
|
300
|
+ # print("\nDebug - reconstruct_surface input parameters:")
|
|
301
|
+ # print("Camera parameters:")
|
|
302
|
+ # print(f"Matrix:\n{cam_params[0]['camera_matrix']}")
|
|
303
|
+ # print(f"Translation:\n{cam_params[0]['translation_vector']}")
|
|
304
|
+
|
|
305
|
+ cfg = json.load(open(config_path, 'r'))
|
|
306
|
+ n_cam = cfg['cam_num']
|
|
307
|
+ grid_spacing = cfg['grid_spacing']
|
|
308
|
+ num_freq = cfg['num_freq']
|
|
309
|
+
|
|
310
|
+ x_uns, y_uns = [], []
|
|
311
|
+ binary_masks = []
|
|
312
|
+
|
|
313
|
+ for cam_id in range(n_cam):
|
|
314
|
+ print('cam_id = ', cam_id)
|
|
315
|
+ # 验证使用的是传入的参数而不是其他来源
|
|
316
|
+ #print(f"\nUsing camera parameters for camera {cam_id}:")
|
|
317
|
+ #print(f"Matrix:\n{cam_params[cam_id]['camera_matrix']}")
|
|
318
|
+
|
|
319
|
+ white_path = os.path.join(img_folder, f'{cam_id}_frame_24.bmp')
|
|
320
|
+ #binary = get_white_mask(white_path, bin_thresh=82, size_thresh=0.5, debug=0) #凹 凸 平晶 平面镜
|
184
|
321
|
|
185
|
|
- # 第一个子图
|
186
|
|
- # cax0 = axes[0].imshow(x_un)
|
187
|
|
- # axes[0].set_title('x_phase_unwrapped')
|
188
|
|
- # axes[0].set_xlabel('X Axis')
|
189
|
|
- # axes[0].set_ylabel('Y Axis')
|
190
|
|
- # fig.colorbar(cax0, ax=axes[0])
|
|
322
|
+ binary = get_white_mask(white_path, bin_thresh=40, size_thresh=0.8, debug=0)
|
191
|
323
|
|
192
|
|
- # # 第二个子图
|
193
|
|
- # cax1 = axes[1].imshow(y_un)
|
194
|
|
- # axes[1].set_title('y_phase_unwrapped')
|
195
|
|
- # axes[1].set_xlabel('X Axis')
|
196
|
|
- # axes[1].set_ylabel('Y Axis')
|
197
|
|
- # fig.colorbar(cax0, ax=axes[1])
|
|
324
|
+ #binary = get_white_mask(white_path, bin_thresh=30, size_thresh=0.8, debug=0) #四相机
|
198
|
325
|
|
199
|
|
- # # 调整子图之间的间距
|
200
|
|
- # plt.tight_layout()
|
201
|
|
- #plt.savefig(os.path.join(save_path, "phase_unwrapped.png"))
|
202
|
|
- #plt.show()
|
|
326
|
+ binary_masks.append(binary)
|
|
327
|
+ mtx = cam_params[cam_id]['camera_matrix']
|
|
328
|
+ dist_coeffs = cam_params[cam_id]['distortion_coefficients']
|
|
329
|
+ phases = extract_phase(img_folder, cam_id, binary, mtx, dist_coeffs, num_freq)
|
|
330
|
+ x_un, y_un = unwrap_phase(phases, num_freq, debug=0)
|
|
331
|
+ x_uns.append(x_un)
|
|
332
|
+ y_uns.append(y_un)
|
|
333
|
+
|
|
334
|
+ np.save('./x_phase_unwrapped_python.npy', x_un)
|
|
335
|
+ np.save('./y_phase_unwrapped_python.npy', y_un)
|
203
|
336
|
|
204
|
|
- #return 0
|
205
|
|
- print('screen_params = ', screen_params)
|
206
|
|
-
|
207
|
337
|
if n_cam == 1:
|
208
|
|
- screen_to_world = map_screen_to_world(screen_params, cam_params[0])
|
|
338
|
+ #screen_to_world = map_screen_to_world(screen_params, cam_params[0], -30, 10, 80)
|
|
339
|
+ #screen_to_world = map_screen_to_world(screen_params, cam_params[0], -10, -10, 20)
|
|
340
|
+ screen_to_world = map_screen_to_world(screen_params, cam_params[0], 0, 0, 0)
|
209
|
341
|
elif n_cam == 4:
|
210
|
|
- screen_to_world = map_screen_to_world(screen_params, cam_params[3])
|
|
342
|
+ screen_to_world = map_screen_to_world(screen_params, cam_params[3], 0, 0, 0)
|
211
|
343
|
else:
|
212
|
344
|
print('camera number should be 1 or 4')
|
213
|
345
|
return 0
|
214
|
346
|
|
215
|
|
-
|
216
|
347
|
print("\n4. 获得不同坐标系下点的位置")
|
217
|
|
- get_point_start = time.time()
|
218
|
348
|
total_cloud_point = np.empty((0, 3))
|
219
|
349
|
total_gradient = np.empty((0, 4))
|
220
|
|
- total_boundary_point = np.empty((0, 3))
|
|
350
|
+
|
221
|
351
|
for i in range(n_cam):
|
222
|
352
|
print('cam_id = ', i)
|
223
|
|
- contours_point = get_meshgrid_contour(binary_masks[i], save_path, debug=False)
|
224
|
|
- #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)
|
225
|
|
- #world_points_x, world_points_y = np.meshgrid(np.linspace(31.8020, 77.9135, 1), np.linspace(33.5894,79.9621,1))
|
226
|
|
- min_x, max_x, min_y, max_y = 31.8020, 77.9135-1, 33.5894, 79.9621-1
|
227
|
|
- meshwidth = 1
|
228
|
|
- world_points_x, world_points_y = np.meshgrid(np.arange(min_x, max_x + meshwidth, meshwidth), np.arange(min_y, max_y + meshwidth, meshwidth))
|
229
|
|
- world_points_z = np.zeros_like(world_points_x)-cfg['d']
|
230
|
|
- #print()
|
231
|
|
- print('world_points_z = ', world_points_x.reshape(-1, 1).shape, world_points_y.reshape(-1, 1).shape, world_points_z.reshape(-1, 1).shape)
|
232
|
|
-
|
233
|
|
- world_points = np.hstack((world_points_x.reshape(-1, 1), world_points_y.reshape(-1, 1), world_points_z.reshape(-1, 1)))
|
234
|
|
- camera_points, u_p, v_p = get_camera_points(world_points, cam_params[i], save_path, i, debug=0)
|
|
353
|
+ contours_point = get_meshgrid_contour(binary_masks[i], debug=0)
|
|
354
|
+ 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)
|
|
355
|
+ camera_points, u_p, v_p = get_camera_points(world_points, cam_params[i], i, debug=0)
|
235
|
356
|
point_data = {'x_w': world_points[:, 0], 'y_w': world_points[:, 1], 'z_w': world_points[:, 2],
|
236
|
357
|
'x_c': camera_points[:, 0], 'y_c': camera_points[:, 1], 'z_c': camera_points[:, 2],
|
237
|
358
|
'u_p': u_p, 'v_p': v_p}
|
238
|
|
- screen_points = get_screen_points(point_data, x_uns[i], y_uns[i], screen_params, screen_to_world, cfg, save_path, i, debug=debug)
|
239
|
|
- #plot_coords(world_points, camera_points, screen_points)
|
240
|
|
- z_raw, gradient_xy = reconstruction_cumsum(world_points, camera_points, screen_points, debug=0, smooth=smooth, align=align, denoise=denoise)
|
|
359
|
+ screen_points = get_screen_points(point_data, x_uns[i], y_uns[i], screen_to_world, cfg, i, debug=0)
|
241
|
360
|
|
242
|
|
- z_raw_xy = np.round(z_raw[:, :2]).astype(int)
|
243
|
|
-
|
244
|
|
- print('world_points =', world_points)
|
|
361
|
+ # 添加调试信息
|
|
362
|
+ # print(f"\nDebug - Reconstruction:")
|
245
|
363
|
|
246
|
|
- # # 创建布尔掩码,初始为 True
|
247
|
|
- # mask = np.ones(len(z_raw_xy), dtype=bool)
|
248
|
|
-
|
249
|
|
- # # 遍历每个边界点,标记它们在 aligned 中的位置
|
250
|
|
- # for boundary_point in world_points_boundary:
|
251
|
|
- # # 标记与当前边界点相同 xy 坐标的行
|
252
|
|
- # mask &= ~np.all(z_raw_xy == boundary_point[:2], axis=1)
|
253
|
364
|
|
254
|
|
- # # 使用掩码过滤出非边界点
|
255
|
|
- # non_boundary_points = z_raw[mask]
|
256
|
|
- # non_boundary_aligned, rotation_matrix = align2ref(non_boundary_points)
|
|
365
|
+ # print(f"Camera points shape: {camera_points.shape}")
|
|
366
|
+ # print(f"Screen points shape: {screen_points.shape}")
|
|
367
|
+ #ds(world_points, camera_points, screen_points)
|
|
368
|
+ #plot_coords(world_points, camera_points, screen_points)
|
257
|
369
|
|
258
|
|
- # 创建布尔掩码,初始为 True
|
259
|
|
- mask = np.ones(len(z_raw_xy), dtype=bool)
|
260
|
|
-
|
261
|
|
- # 遍历每个边界点,标记它们在 aligned 中的位置
|
262
|
|
- # for boundary_point in world_points_boundary_3:
|
263
|
|
- # # 标记与当前边界点相同 xy 坐标的行
|
264
|
|
- # mask &= ~np.all(z_raw_xy == boundary_point[:2], axis=1)
|
|
370
|
+ z1_cumsum, gradient_xy = reconstruction_cumsum(world_points, camera_points, screen_points, debug=0)
|
|
371
|
+ 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])
|
|
372
|
+ np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
|
|
373
|
+ total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z1_cumsum[:, 0], z1_cumsum[:, 1], z1_cumsum[:, 2]))])
|
|
374
|
+ total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
|
|
375
|
+ # 检查返回值
|
|
376
|
+ # print(f"z1_cumsum shape: {z1_cumsum.shape}")
|
|
377
|
+ # print(f"gradient_xy shape: {gradient_xy.shape}")
|
|
378
|
+ # print(f"Sample z1_cumsum values:\n{z1_cumsum[:3]}")
|
265
|
379
|
|
266
|
|
- # 使用掩码过滤出非边界点
|
267
|
|
- non_boundary_points = z_raw[mask]
|
268
|
|
- # z_raw_aligned = non_boundary_points @ rotation_matrix.T
|
269
|
|
- # z_raw_aligned[:,2] = z_raw_aligned[:,2] - np.mean(z_raw_aligned[:, 2])
|
|
380
|
+ return total_cloud_point, total_gradient
|
270
|
381
|
|
271
|
|
- #z_raw_aligned = non_boundary_points
|
272
|
|
- z_raw_aligned, _ = align2ref(non_boundary_points)
|
|
382
|
+
|
273
|
383
|
|
274
|
|
- #non_boundary_points = smoothed
|
275
|
|
- 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])
|
276
|
|
- np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
|
277
|
|
- total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z_raw_aligned[:, 0], z_raw_aligned[:, 1], z_raw_aligned[:, 2]))])
|
278
|
|
- total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
|
|
384
|
+def main(config_path, img_folder):
|
|
385
|
+ current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
386
|
+ os.chdir(current_dir)
|
|
387
|
+
|
|
388
|
+ cfg = json.load(open(config_path, 'r'))
|
|
389
|
+ n_cam = cfg['cam_num']
|
|
390
|
+
|
279
|
391
|
|
280
|
|
- if 0:
|
281
|
|
- fig = plt.figure()
|
282
|
|
- ax = fig.add_subplot(111, projection='3d')
|
283
|
|
-
|
284
|
|
- # 提取 x, y, z 坐标
|
285
|
|
- x_vals = total_cloud_point[:, 0]
|
286
|
|
- y_vals = total_cloud_point[:, 1]
|
287
|
|
- z_vals = total_cloud_point[:, 2]
|
288
|
|
-
|
289
|
|
- # 绘制3D点云
|
290
|
|
- ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
|
291
|
|
-
|
292
|
|
- # 设置轴标签和标题
|
293
|
|
- ax.set_xlabel('X (mm)')
|
294
|
|
- ax.set_ylabel('Y (mm)')
|
295
|
|
- ax.set_zlabel('Z (mm)')
|
296
|
|
- ax.set_title('z_raw 3D Point Cloud Visualization gradient')
|
297
|
|
- plt.show()
|
298
|
|
-
|
299
|
|
- # fig = plt.figure()
|
300
|
|
- # ax = fig.add_subplot(111, projection='3d')
|
301
|
|
- # smoothed_total = smooth_pcl(total_cloud_point, 3)
|
302
|
|
- # # 提取 x, y, z 坐标
|
303
|
|
- # x_vals = smoothed_total[:, 0]
|
304
|
|
- # y_vals = smoothed_total[:, 1]
|
305
|
|
- # z_vals = smoothed_total[:, 2]
|
306
|
|
-
|
307
|
|
- # # 绘制3D点云
|
308
|
|
- # ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
|
309
|
|
-
|
310
|
|
- # # 设置轴标签和标题
|
311
|
|
- # ax.set_xlabel('X (mm)')
|
312
|
|
- # ax.set_ylabel('Y (mm)')
|
313
|
|
- # ax.set_zlabel('Z (mm)')
|
314
|
|
- # ax.set_title('smoothed 3D Point Cloud Visualization')
|
315
|
|
-
|
316
|
|
-
|
317
|
|
- get_point_end = time.time()
|
|
392
|
+ matlab_align = 0
|
|
393
|
+
|
|
394
|
+ if n_cam == 4:
|
|
395
|
+ screen_img_path = 'D:\\data\\four_cam\\calibrate\\cam3-screen-1008'
|
|
396
|
+ camera_img_path = 'D:\\data\\four_cam\\calibrate\\calibrate-1016'
|
|
397
|
+ elif n_cam == 1:
|
|
398
|
+ camera_img_path = 'D:\\data\\one_cam\\padtest1125\\test1\\'
|
|
399
|
+ screen_img_path = 'D:\\data\\one_cam\\pad-test-1125\\test4\\calibration\\screen\\'
|
|
400
|
+
|
|
401
|
+ print(f"开始执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
402
|
+ print("\n1. 机标定")
|
|
403
|
+ preprocess_start = time.time()
|
|
404
|
+
|
|
405
|
+ cam_para_path = os.path.join(current_dir, 'config', cfg['cam_params'])
|
|
406
|
+ print('cam_para_path = ', cam_para_path)
|
|
407
|
+ if os.path.exists(cam_para_path):
|
|
408
|
+ #if False:
|
|
409
|
+ with open(cam_para_path, 'rb') as pkl_file:
|
|
410
|
+ cam_params = pickle.load(pkl_file)
|
|
411
|
+ else:
|
|
412
|
+ if n_cam == 4:
|
|
413
|
+ cam_params = []
|
|
414
|
+ camera_subdir = [item for item in os.listdir(camera_img_path) if os.path.isdir(os.path.join(camera_img_path, item))]
|
|
415
|
+ camera_subdir.sort()
|
|
416
|
+ assert len(camera_subdir) == 4, f"found {len(camera_subdir)} cameras, should be 4"
|
|
417
|
+ for i in range(n_cam):
|
|
418
|
+ cam_img_path = glob.glob(os.path.join(camera_img_path, camera_subdir[i], "*.bmp"))
|
|
419
|
+ cam_img_path.sort()
|
|
420
|
+ cam_param_raw = calibrate_world_aprilgrid(cam_img_path, cfg['world_chessboard_size'], cfg['world_square_size'], cfg['world_square_spacing'], debug=1)
|
|
421
|
+ cam_params.append(cam_param_raw)
|
|
422
|
+ with open(cam_para_path, 'wb') as pkl_file:
|
|
423
|
+ pickle.dump(cam_params, pkl_file)
|
|
424
|
+ elif n_cam == 1:
|
|
425
|
+ cam_params = []
|
|
426
|
+ cam_img_path = glob.glob(os.path.join(camera_img_path, "*.bmp"))
|
|
427
|
+ cam_img_path.sort()
|
|
428
|
+ if matlab_align:
|
|
429
|
+ cfg['world_chessboard_size'] = [41, 40]
|
|
430
|
+ cfg['world_square_size'] = 2
|
|
431
|
+ cam_param_raw = calibrate_world(cam_img_path, cfg['world_chessboard_size'], cfg['world_square_size'], debug=1)
|
|
432
|
+ cam_params.append(cam_param_raw)
|
|
433
|
+ with open(cam_para_path, 'wb') as pkl_file:
|
|
434
|
+ pickle.dump(cam_params, pkl_file)
|
|
435
|
+ print('raw cam_param = ', cam_params)
|
|
436
|
+ print("\n2. 屏幕标定")
|
|
437
|
+ screen_cal_start = time.time()
|
|
438
|
+
|
|
439
|
+ screen_img_path = glob.glob(os.path.join(screen_img_path, "*.bmp"))
|
|
440
|
+ screen_para_path = os.path.join('config', cfg['screen_params'])
|
|
441
|
+ if os.path.exists(screen_para_path):
|
|
442
|
+ #if False:
|
|
443
|
+ with open(screen_para_path, 'rb') as pkl_file:
|
|
444
|
+ screen_params = pickle.load(pkl_file)
|
|
445
|
+ else:
|
|
446
|
+ if n_cam == 3:
|
|
447
|
+ 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)
|
|
448
|
+ elif n_cam == 1:
|
|
449
|
+ raw_cam_mtx = cam_params[0]['camera_matrix']
|
|
450
|
+ 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)
|
|
451
|
+ with open(screen_para_path, 'wb') as pkl_file:
|
|
452
|
+ pickle.dump(screen_params, pkl_file)
|
|
453
|
+
|
|
454
|
+ screen_cal_end = time.time()
|
318
|
455
|
print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
319
|
|
- print(f" 耗时: {get_point_end - get_point_start:.2f} 秒")
|
|
456
|
+ print(f" 耗时: {screen_cal_end - screen_cal_start:.2f} s")
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+ total_cloud_point, total_gradient = reconstruct_surface(cam_params, screen_params, config_path, img_folder)
|
320
|
460
|
|
321
|
461
|
print("\n5. 后处理")
|
322
|
462
|
post_process_start = time.time()
|
323
|
463
|
total_cloud_point[:,0] = np.round(total_cloud_point[:,0])
|
324
|
464
|
total_cloud_point[:,1] = np.round(total_cloud_point[:,1])
|
325
|
465
|
#fitted_points = post_process(total_cloud_point, debug=0)
|
326
|
|
- test = post_process_with_grad(img_folder, n_cam, 1)
|
|
466
|
+ clout_points = post_process_with_grad(img_folder, n_cam, 1)
|
327
|
467
|
fitted_points = total_cloud_point
|
328
|
|
- #fitted_points = total_cloud_point
|
329
|
|
- #align_fitted, _ = align2ref(fitted_points)
|
330
|
468
|
align_fitted = fitted_points
|
331
|
469
|
|
332
|
|
- 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]))
|
333
|
|
- if 0:
|
334
|
|
- fig = plt.figure()
|
335
|
|
- ax = fig.add_subplot(111, projection='3d')
|
336
|
|
-
|
337
|
|
- # 提取 x, y, z 坐标
|
338
|
|
- x_vals = np.round(fitted_points[:, 0]-np.mean(fitted_points[:, 0]))
|
339
|
|
- y_vals = np.round(fitted_points[:, 1]-np.mean(fitted_points[:, 1]))
|
340
|
|
- z_vals = align_fitted[:,2]-np.min(align_fitted[:,2])
|
341
|
|
-
|
342
|
|
- x_vals = fitted_points[:, 0]
|
343
|
|
- y_vals = fitted_points[:, 1]
|
344
|
|
- z_vals = fitted_points[:, 2]
|
345
|
|
-
|
346
|
|
- # 绘制3D点云
|
347
|
|
- ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
|
348
|
|
-
|
349
|
|
- # 设置轴标签和标题
|
350
|
|
- ax.set_xlabel('X (mm)')
|
351
|
|
- ax.set_ylabel('Y (mm)')
|
352
|
|
- ax.set_zlabel('Z (mm)')
|
353
|
|
- ax.set_title('post 3D Point Cloud Visualization')
|
354
|
|
- plt.show()
|
|
470
|
+ 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])
|
355
|
471
|
|
356
|
|
- post_process_end = time.time()
|
357
|
|
- print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
358
|
|
- print(f" 耗时: {post_process_end - post_process_start:.2f} 秒")
|
359
|
472
|
|
360
|
473
|
print("\n6. 评估")
|
361
|
474
|
eval_start = time.time()
|
362
|
475
|
point_cloud_path = os.path.join(img_folder, 'cloudpoint.txt')
|
363
|
476
|
json_path = os.path.join(img_folder, 'result.json')
|
364
|
477
|
theta_notch = 0
|
365
|
|
- #get_eval_result(point_cloud_path, json_path, theta_notch, 0)
|
|
478
|
+ get_eval_result(point_cloud_path, json_path, theta_notch, 1)
|
366
|
479
|
eval_end = time.time()
|
367
|
480
|
print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
368
|
481
|
print(f" 耗时: {eval_end - eval_start:.2f} 秒")
|
|
482
|
+ # new_cam_params, new_screen_params = optimize_parameters(
|
|
483
|
+ # cam_params[0], # 假设单相系统
|
|
484
|
+ # screen_params,
|
|
485
|
+ # total_cloud_point,
|
|
486
|
+ # total_gradient
|
|
487
|
+ # )
|
|
488
|
+
|
|
489
|
+ #print('after optimazation:', new_cam_params, new_screen_params)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+ #total_cloud_point, total_gradient = reconstruct_surface(cam_params, screen_params, config_path)
|
|
493
|
+
|
|
494
|
+ #print('cam_params = ', cam_params)
|
|
495
|
+ #print('screen_params = ', screen_params)
|
|
496
|
+
|
|
497
|
+ # print("\n3. 相位提取,相位展开")
|
|
498
|
+ # phase_start = time.time()
|
|
499
|
+
|
|
500
|
+ # scales = [0.995291, 0.993975, 0.993085, 0.994463]
|
|
501
|
+ # scales = [1,1,1,1]
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+ # phase_end = time.time()
|
|
507
|
+ # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
508
|
+ # print(f" 耗时: {phase_end - phase_start:.2f} 秒")
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+ # z_raw_xy = np.round(z_poisson[:, :2]).astype(int)
|
|
514
|
+
|
|
515
|
+ # #创建布尔掩码,初始为 True
|
|
516
|
+ # mask = np.ones(len(z_raw_xy), dtype=bool)
|
|
517
|
+
|
|
518
|
+ # # 使用掩码过滤出非边界点
|
|
519
|
+ # non_boundary_points = z_poisson[mask]
|
|
520
|
+
|
|
521
|
+ # z_raw_aligned, _ = align2ref(non_boundary_points)
|
|
522
|
+
|
|
523
|
+ # #non_boundary_points = smoothed
|
|
524
|
+ # 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])
|
|
525
|
+ # np.savetxt(os.path.join(img_folder, str(i) + '_gradient.txt'), gradient_xy, fmt='%.10f', delimiter=',')
|
|
526
|
+ # total_cloud_point = np.vstack([total_cloud_point, np.column_stack((z_raw_aligned[:, 0], z_raw_aligned[:, 1], z_raw_aligned[:, 2]))])
|
|
527
|
+ # total_gradient = np.vstack([total_gradient, np.column_stack((gradient_xy[:, 0], gradient_xy[:, 1], gradient_xy[:, 2], gradient_xy[:, 3]))])
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+ # get_point_end = time.time()
|
|
531
|
+ # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
532
|
+ # print(f" 耗时: {get_point_end - get_point_start:.2f} 秒")
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+ # if 0:
|
|
536
|
+ # fig = plt.figure()
|
|
537
|
+ # ax = fig.add_subplot(111, projection='3d')
|
|
538
|
+
|
|
539
|
+ # # 提取 x, y, z 坐标
|
|
540
|
+ # x_vals = np.round(fitted_points[:, 0]-np.mean(fitted_points[:, 0]))
|
|
541
|
+ # y_vals = np.round(fitted_points[:, 1]-np.mean(fitted_points[:, 1]))
|
|
542
|
+ # z_vals = align_fitted[:,2]-np.min(align_fitted[:,2])
|
|
543
|
+
|
|
544
|
+ # x_vals = fitted_points[:, 0]
|
|
545
|
+ # y_vals = fitted_points[:, 1]
|
|
546
|
+ # z_vals = fitted_points[:, 2]
|
|
547
|
+
|
|
548
|
+ # # 绘制3D点云
|
|
549
|
+ # ax.scatter(x_vals, y_vals, z_vals, c=z_vals, cmap='viridis', marker='o')
|
|
550
|
+
|
|
551
|
+ # # 设置轴标签和标题
|
|
552
|
+ # ax.set_xlabel('X (mm)')
|
|
553
|
+ # ax.set_ylabel('Y (mm)')
|
|
554
|
+ # ax.set_zlabel('Z (mm)')
|
|
555
|
+ # ax.set_title('post 3D Point Cloud Visualization')
|
|
556
|
+ # plt.show()
|
|
557
|
+
|
|
558
|
+ # post_process_end = time.time()
|
|
559
|
+ # print(f" 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
560
|
+ # print(f" 耗时: {post_process_end - post_process_start:.2f} 秒")
|
|
561
|
+
|
|
562
|
+
|
369
|
563
|
|
370
|
564
|
return True
|
371
|
565
|
|
372
|
566
|
|
373
|
567
|
if __name__ == '__main__':
|
374
|
|
- config_path = 'config\\cfg_3freq_wafer_matlab.json'
|
375
|
|
- #img_folder = 'D:\\data\\four_cam\\1008_storage\\pingjing_20241017092315228\\' #'D:\\data\\four_cam\\betone_1011\\20241011142348762-1'
|
376
|
|
- # img_folder = 'D:\\huchao\\inspect_server_202409241013_py\\storage\\20241023193453708\\'
|
377
|
|
- img_folder = 'D:\\data\\one_cam\\pingjing_20241024154405250\\'
|
378
|
|
- #img_folder = 'D:\\data\\one_cam\\betone-20241025095352783\\'
|
379
|
|
- #img_folder = 'D:\\data\\one_cam\\20241025113857041-neg\\'
|
380
|
|
- #'
|
381
|
|
- json_path = os.path.join(img_folder, 'result.json')
|
|
568
|
+ #config_path = 'config\\cfg_3freq_wafer_1226.json'
|
|
569
|
+ config_path = 'config\\cfg_3freq_wafer_1226.json'
|
|
570
|
+
|
|
571
|
+ #config_path = 'config\\cfg_3freq_wafer_matlab.json'
|
|
572
|
+ img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test4\\pingjing\\'
|
|
573
|
+ img_folder = 'D:\\data\\one_cam\\pad-test-1106\\1104-test-other\\'
|
|
574
|
+ #img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213183308114\\' #凸
|
|
575
|
+ #img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213183451799\\' #凹
|
|
576
|
+ img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241213182959977\\' #平面镜
|
|
577
|
+ img_folder = 'D:\\data\\one_cam\\pad-test-1125\\test7-4\\20241219180143344\\' #平晶
|
|
578
|
+ #img_folder = 'D:\\data\\four_cam\\1223\\20241223134629640-0\\' #晶圆
|
|
579
|
+ #img_folder = 'D:\\data\\four_cam\\1223\\20241223135156305-1\\' #晶圆
|
|
580
|
+ #img_folder = 'D:\\data\\four_cam\\1223\\20241223135626457-2-0\\' #晶圆
|
|
581
|
+ img_folder = 'D:\\data\\four_cam\\1223\\20241223135935517-2-1\\' #晶圆
|
|
582
|
+
|
|
583
|
+ #img_folder = 'D:\\data\\four_cam\\1223\\20241223172437775-2-0\\' #晶圆
|
|
584
|
+ #img_folder = 'D:\\data\\four_cam\\1223\\20241223172712226-2-1\\' #晶圆
|
|
585
|
+ # img_folder = 'D:\\data\\four_cam\\1223\\20241223172931654-1\\' #晶圆
|
|
586
|
+ img_folder = 'D:\\data\\four_cam\\1223\\20241223173521117-0\\' #晶圆
|
|
587
|
+ #img_folder = 'D:\\data\\four_cam\\betone_1011\\20241011142901251-2\\'
|
|
588
|
+
|
|
589
|
+ # img_folder = 'D:\\data\\one_cam\\1226image\\20241226142937478\\' #凹
|
|
590
|
+ # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226143014962\\' #凸
|
|
591
|
+ # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226143043070\\' #平面镜
|
|
592
|
+ # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226142826690\\' #平晶
|
|
593
|
+ # img_folder = 'D:\\data\\one_cam\\1226image\\20241226143916513\\' #晶圆
|
|
594
|
+ # #img_folder = 'D:\\data\\one_cam\\1226image\\20241226144357273\\'
|
|
595
|
+ # img_folder = 'D:\\data\\one_cam\\1226image\\20241226144616239\\'
|
|
596
|
+ img_folder = 'D:\\data\\one_cam\\betone1230\\20241230110516029\\'
|
|
597
|
+ img_folder = 'D:\\data\\one_cam\\betone1230\\20241230110826833\\' #2
|
|
598
|
+ #img_folder = 'D:\\data\\one_cam\\betone1230\\20241230111002224\\'
|
|
599
|
+
|
|
600
|
+ #img_folder = 'D:\\data\\one_cam\\betone1230\\20250103151342402-pingjing\\'
|
382
|
601
|
|
383
|
|
- # 20241011142348762-1 20241011142901251-2 20241011143925746-3 20241011144821292-4
|
384
|
|
- # 0.60 0.295 0.221 0.346
|
|
602
|
+
|
|
603
|
+ # img_folder = 'D:\\data\\one_cam\\betone1230\\20250102181845157-1\\'
|
|
604
|
+ #img_folder = 'D:\\data\\one_cam\\betone1230\\20250102181648331-2\\'
|
|
605
|
+ #img_folder = 'D:\\data\\one_cam\\betone1230\\20250102182008126-3\\'
|
385
|
606
|
|
386
|
|
- # x max = 653.5925
|
387
|
|
- # y max = 692.1735648
|
388
|
|
- # x max = 251.0775
|
389
|
|
- # y max = 293.05856482
|
390
|
|
- # x max = 184.7275
|
391
|
|
- # y max = 239.00919669
|
392
|
|
- # x max = 342.2525
|
393
|
|
- # y max = 386.92087185
|
|
607
|
+
|
|
608
|
+ json_path = os.path.join(img_folder, 'result.json')
|
394
|
609
|
|
395
|
610
|
pmdstart(config_path, img_folder)
|
396
|
|
- #fitted_points = post_process_with_grad(img_folder, 1)
|
397
|
611
|
|
398
|
612
|
|