-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattention_window_implementation (1).py
More file actions
515 lines (401 loc) · 23.1 KB
/
attention_window_implementation (1).py
File metadata and controls
515 lines (401 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# -*- coding: utf-8 -*-
"""Attention_Window_Implementation.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1SRkTaSyTqSbZn4JET69jYLNsVUmIDAxd
"""
def thread_grasping_local_visual_servoing(self, actual_pixel_for_grasping, attention_window_pixel_for_grasping, psm_quaternion_during_servoing, psm_number_character):
image = self.cv_bridge_.imgmsg_to_cv2(self.left_image)
# input the number of PSM1 or PSM2
self.psm_number = psm_number_character
if self.psm_number == "1":
self.psm_visual_servoing = self.psm1
elif self.psm_number == "2":
self.psm_visual_servoing = self.psm2
self.stop_flag_threading = False
square_length_smaller_window_x = 10
square_length_smaller_window_y = 10
self.click_pixel_dictionary[1] = actual_pixel_for_grasping
self.click_pixel_dictionary[2] = attention_window_pixel_for_grasping
print("====== Phase 1: Autonomous X and Y direction servo ======")
x_target, y_target = self.click_pixel_dictionary[1]
x_target_smaller_window, y_target_smaller_window = self.click_pixel_dictionary[2]
x1_smaller_window = max(x_target_smaller_window - square_length_smaller_window_x, 0)
y1_smaller_window = max(y_target_smaller_window - square_length_smaller_window_y, 0)
x2_smaller_window = min(x_target_smaller_window + square_length_smaller_window_x, image.shape[1])
y2_smaller_window = min(y_target_smaller_window + square_length_smaller_window_y, image.shape[0])
# start thread
worker_thread = threading.Thread(target=self.move_worker_autonomous_camera_space_for_PSM1andPSM2(psm_quat_initial = psm_quaternion_during_servoing), daemon=True)
worker_thread.start()
print("Control robot using keyboard (Enter to quit)")
### vs pre parameters
Kp = 1
stop_position_threshold = 0.001
stop_pixel_threshold = 20
fx = self.K[0, 0]
fy = self.K[1, 1]
cx = self.K[0, 2]
cy = self.K[1, 2]
psm_pos_initial, _ = self.psm_visual_servoing.get_current_pose()
psm_pos_initial = np.asarray(psm_pos_initial, dtype=float).reshape(3,)
z_fixed_phase_1_robot_base = psm_pos_initial[2].copy()
### solution 1: same robot Z
if self.psm_number == "1":
x_goal_phase_1_robot_base, y_goal_phase_1_robot_base, Z_cam_goal_phase2_SameZinRobot = solve_robot_xy_for_pixel(self.av_left_to_psm1_new, fx, fy, cx, cy,
x_target, y_target, z_fixed_phase_1_robot_base)
click_point_3D_RefPSM_phase1_SameZinRobotSpace = np.array([x_goal_phase_1_robot_base, y_goal_phase_1_robot_base,
z_fixed_phase_1_robot_base])
if self.psm_number == "2":
x_goal_phase_1_robot_base, y_goal_phase_1_robot_base, Z_cam_goal_phase2_SameZinRobot = solve_robot_xy_for_pixel(self.av_left_to_psm2_new, fx, fy, cx, cy,
x_target, y_target, z_fixed_phase_1_robot_base)
click_point_3D_RefPSM_phase1_SameZinRobotSpace = np.array([x_goal_phase_1_robot_base, y_goal_phase_1_robot_base,
z_fixed_phase_1_robot_base])
### solution 2: same camera Z
if self.psm_number == "1":
psm_p_cam_initial = single_point_transform(self.av_left_to_psm1_new, psm_pos_initial)
elif self.psm_number == "2":
psm_p_cam_initial = single_point_transform(self.av_left_to_psm2_new, psm_pos_initial)
Z_cam_initial = psm_p_cam_initial[2]
# Reverse project back to the camera coordinate system from the new pixel coordinates, assuming Z remains unchanged
X_cam_goal = (x_target - cx) * Z_cam_initial / fx
Y_cam_goal = (y_target - cy) * Z_cam_initial / fy
Z_cam_goal = Z_cam_initial # Keep the same Z value
Z_cam_goal_phase2_SameZinCamera = Z_cam_goal.copy()
click_point_3D_cam_phase1 = np.array([X_cam_goal, Y_cam_goal, Z_cam_goal])
if self.psm_number == "1":
click_point_3D_RefPSM_phase1_SameZinCameraSpace = single_point_transform(self.psm1_to_av_left_new, click_point_3D_cam_phase1)
elif self.psm_number == "2":
click_point_3D_RefPSM_phase1_SameZinCameraSpace = single_point_transform(self.psm2_to_av_left_new, click_point_3D_cam_phase1)
if click_point_3D_RefPSM_phase1_SameZinRobotSpace[2] < click_point_3D_RefPSM_phase1_SameZinCameraSpace[2]:
click_point_3D_RefPSM_phase1 = click_point_3D_RefPSM_phase1_SameZinRobotSpace.copy()
Z_cam_goal_phase2 = Z_cam_goal_phase2_SameZinRobot.copy()
print("choose same Z in Robot space")
print("dif is: ", click_point_3D_RefPSM_phase1_SameZinRobotSpace - click_point_3D_RefPSM_phase1_SameZinCameraSpace)
else:
click_point_3D_RefPSM_phase1 = click_point_3D_RefPSM_phase1_SameZinCameraSpace.copy()
Z_cam_goal_phase2 = Z_cam_goal_phase2_SameZinCamera.copy()
print("choose same Z in Camera space")
print("dif is: ", click_point_3D_RefPSM_phase1_SameZinRobotSpace - click_point_3D_RefPSM_phase1_SameZinCameraSpace)
while True:
image = self.cv_bridge_.imgmsg_to_cv2(self.left_image)
img_vis = image.copy()
cv2.circle(img_vis, (x_target, y_target), 3, (0, 255, 0), -1)
cv2.rectangle(img_vis, (x1_smaller_window, y1_smaller_window), (x2_smaller_window, y2_smaller_window), (255, 0, 0), 3)
cv2.circle(img_vis, (x_target_smaller_window, y_target_smaller_window), 3, (255, 0, 0), -1)
psm_pos, _ = self.psm_visual_servoing.get_current_pose()
psm_pos = np.asarray(psm_pos, dtype=float).reshape(3,)
if self.psm_number == "1":
rvec_cam_psm, _ = cv2.Rodrigues(self.av_left_to_psm1_new[:3,:3])
psm_p_pixel, _ = cv2.projectPoints(psm_pos, rvec_cam_psm, self.av_left_to_psm1_new[:3,3], self.K, self.D)
elif self.psm_number == "2":
rvec_cam_psm, _ = cv2.Rodrigues(self.av_left_to_psm2_new[:3,:3])
psm_p_pixel, _ = cv2.projectPoints(psm_pos, rvec_cam_psm, self.av_left_to_psm2_new[:3,3], self.K, self.D)
u_current, v_current = psm_p_pixel.squeeze().astype(int)
print(f"PSM pixel: ({u_current:.2f}, {v_current:.2f})")
cv2.circle(img_vis, (int(u_current), int(v_current)), 3, (0, 0, 255), -1)
img_vis_msg = self.cv_bridge_.cv2_to_imgmsg(img_vis, encoding="bgr8")
self.img_servoing.publish(img_vis_msg)
e_x = click_point_3D_RefPSM_phase1[0] - psm_pos[0]
e_y = click_point_3D_RefPSM_phase1[1] - psm_pos[1]
e_z = click_point_3D_RefPSM_phase1[2] - psm_pos[2]
print(f"Position error in camera space: (e_x: {e_x:.2f}, e_y: {e_y:.2f}, e_z: {e_z:.2f})")
if (abs(e_x) < stop_position_threshold and abs(e_y) < stop_position_threshold and abs(e_z) < stop_position_threshold) or \
(abs(x_target - u_current) < stop_pixel_threshold and abs(y_target - v_current) < stop_pixel_threshold):
print("Reach goal XY")
print("position error is: (%s, %s, %s)" % (abs(e_x), abs(e_y), abs(e_z)))
print("position error bool is: ", (abs(e_x) < stop_position_threshold and abs(e_y) < stop_position_threshold and abs(e_z) < stop_position_threshold))
print("pixel error bool is: ", abs(x_target - u_current) < stop_pixel_threshold and abs(y_target - v_current) < stop_pixel_threshold)
print("pixel error is (%s, %s)" % (abs(x_target - u_current), abs(y_target - v_current)))
self.cmd_queue.put(('set_position', psm_pos))
break
delta_x_position = Kp * e_x
delta_y_position = Kp * e_y
delta_z_position = Kp * e_z
print(f"Position delta: (dx: {delta_x_position:.2f}, dy: {delta_y_position:.2f}, dz: {delta_z_position:.2f})")
target_position = np.array([psm_pos[0] + delta_x_position, psm_pos[1] + delta_y_position, psm_pos[2] + delta_z_position])
# pdb.set_trace()
self.cmd_queue.put(('set_position', target_position))
rlist, _, _ = select.select([sys.stdin], [], [], 0)
if rlist:
cmd = sys.stdin.readline().strip()
if cmd == "q" or cmd == "": # Enter key
break
else:
print(f"Unknown command: {cmd}")
# Wait for a short period of time to allow the robot to move
time.sleep(0.1)
time.sleep(1)
# Phase 2: Autonomous Z servoing with XY correction
print("====== Enter Phase 2: Autonomous Z direction servo ======")
print("Press ENTER to stop...")
# pdb.set_trace()
servoing_distance = 0.001
position_correction_for_hitting_thread = 0.002
skip_initial_frames_phase2_count = 1
prev_gray_smaller_window = []
collision_detected_smaller_window = False
while not self.stop_flag_threading:
# Calculate the ratio of ray directions
D_x = (x_target - cx) / fx
D_y = (y_target - cy) / fy
# Set the direction and step size for movement
# Here it is assumed to move away from the camera, increase Z_cam; adjust the direction as needed
Z_cam_goal_phase2 += servoing_distance # Move away from camera (dist)
# Keep the pixel position unchanged and calculate the new X_cam, Y_cam
X_cam_new = D_x * Z_cam_goal_phase2
Y_cam_new = D_y * Z_cam_goal_phase2
point_cam_new = np.array([X_cam_new, Y_cam_new, Z_cam_goal_phase2])
# Convert the new camera coordinates back to the robot base coordinate system
if self.psm_number == "1":
pos_ref_PSM_base_new = single_point_transform(self.psm1_to_av_left_new, point_cam_new)
if self.psm_number == "2":
pos_ref_PSM_base_new = single_point_transform(self.psm2_to_av_left_new, point_cam_new)
pos_ref_PSM_base_new = np.asarray(pos_ref_PSM_base_new, dtype=np.float64) # Ensure it's a deep copy
pos_ref_PSM_base_new[2] -= position_correction_for_hitting_thread
pos_ref_PSM_base_new_copy = pos_ref_PSM_base_new.copy()
self.cmd_queue.put(('set_position_phase_2', pos_ref_PSM_base_new_copy))
# Update image
image = self.cv_bridge_.imgmsg_to_cv2(self.left_image)
image_servoing_window_smaller = image[y1_smaller_window:y2_smaller_window, x1_smaller_window:x2_smaller_window].copy()
if skip_initial_frames_phase2_count > 0:
b, g, r = cv2.split(image_servoing_window_smaller)
diff = r.astype(np.int32) + g.astype(np.int32) - b.astype(np.int32)
diff = np.clip(diff, 0, 255).astype(np.uint8)
prev_gray_smaller_window_unit = cv2.GaussianBlur(diff, (5, 5), 0)
# save prev_gray_smaller_window_unit into prev_gray_smaller_window and keep len(prev_gray_smaller_window) == 5
prev_gray_smaller_window.append(prev_gray_smaller_window_unit)
if len(prev_gray_smaller_window) > 3:
prev_gray_smaller_window.pop(0)
skip_initial_frames_phase2_count -= 1
print("number is:", skip_initial_frames_phase2_count)
if skip_initial_frames_phase2_count == 0:
b, g, r = cv2.split(image_servoing_window_smaller)
diff = r.astype(np.int32) + g.astype(np.int32) - b.astype(np.int32)
diff = np.clip(diff, 0, 255).astype(np.uint8)
current_gray_smaller_window = cv2.GaussianBlur(diff, (5, 5), 0)
collision_detected_smaller_window, img_vis_debug_smaller_window = self.collision_detection_two_windows(prev_gray_smaller_window[0], current_gray_smaller_window)
prev_gray_smaller_window.append(current_gray_smaller_window)
if len(prev_gray_smaller_window) > 3:
prev_gray_smaller_window.pop(0)
img_vis_debug_msg_smaller_window = self.cv_bridge_.cv2_to_imgmsg(img_vis_debug_smaller_window, encoding="bgr8")
self.img_servoing_debug_smaller_window.publish(img_vis_debug_msg_smaller_window)
img_vis = image.copy()
cv2.circle(img_vis, (x_target, y_target), 3, (0, 255, 0), -1)
cv2.rectangle(img_vis, (x1_smaller_window, y1_smaller_window), (x2_smaller_window, y2_smaller_window), (255, 0, 0), 3)
cv2.circle(img_vis, (x_target_smaller_window, y_target_smaller_window), 3, (255, 0, 0), -1)
img_vis_msg = self.cv_bridge_.cv2_to_imgmsg(img_vis, encoding="bgr8")
self.img_servoing.publish(img_vis_msg)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
cmd = sys.stdin.readline().strip()
if cmd == "":
print("Manually Stop Phase 2")
break
if collision_detected_smaller_window:
print("Collision detected")
self.cmd_queue.put(('stop_motion', None))
break
self.stop_flag_threading = True
worker_thread.join() #timeout=1
self.cmd_queue = Queue()
print("====== Grasp the thread ======")
time.sleep(0.5)
psm_pos, _ = self.psm_visual_servoing.get_current_pose()
# psm_quat_initial = np.array([0,0,0,1])
psm_quat_initial = psm_quaternion_during_servoing
psm_pos[2] += 2 * position_correction_for_hitting_thread
self.psm_visual_servoing.set_pose(psm_pos, psm_quat_initial)
time.sleep(0.2)
if self.psm_number == "1":
self.psm1_open(True)
elif self.psm_number == "2":
self.psm2_open(True)
time.sleep(1.5)
psm_pos[2] -= (2.5 * position_correction_for_hitting_thread)
self.psm_visual_servoing.set_pose(psm_pos, psm_quat_initial)
if self.psm_number == "1":
self.psm1_open(False)
elif self.psm_number == "2":
self.psm2_open(False)
def collision_detection_two_windows(self, prev_gray, current_gray,
threshold=15,
threshold_area=30,
stability_threshold=1,
flow_threshold=2.5
):
# Calculate the absolute difference between the current frame and the previous frame
delta = cv2.absdiff(prev_gray, current_gray)
# Apply a Gaussian blur to the image, reduce the noise
delta_blur = cv2.GaussianBlur(delta, (5, 5), 0)
# Convert the difference image to a binary image
_, thresh = cv2.threshold(delta_blur, threshold, 255, cv2.THRESH_BINARY)
thresh_raw = thresh.copy()
# Morphological operation (closed operation+dilation): Enhance lines, remove small noise
# Closed operation: first expand and then corrode, fill voids, connect adjacent areas
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
thresh_raw_3 = thresh.copy()
# Find contours and filter out small areas
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
large_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > threshold_area]
# for i, cnt in enumerate(contours):
# print("%s - contour_area: %s" % (i, cv2.contourArea(cnt)))
# Use optical flow to calculate the motion vector of the object
flow = cv2.calcOpticalFlowFarneback(prev_gray, current_gray,
None, # flow output size can be automatically generated
0.5, # Pyramid scale
3, # Pyramid Layers
15, # Select neighborhood window size
3, # number of iterations
5, # Polynomial neighborhood size
1.2, # Gaussian Sigma
0 # flags
)
flow_x = flow[...,0]
flow_y = flow[...,1]
mag, ang = cv2.cartToPolar(flow_x, flow_y, angleInDegrees=True) #Convert to polar coordinate, mag is the magnitude of the vector, ang is the angle of the vector
mag[mag < flow_threshold] = 0 # filter out small motion vectors
# fluactuation detection
moving_pixels = np.sum(mag > flow_threshold)
total_pixels = mag.size
ratio = moving_pixels / (total_pixels+1e-5)
mean_magnitude= np.mean(mag)
max_magnitude = np.max(mag)
wave_detected = False
print(f"Moving pixels ratio: {ratio:.3f}, Mean mag: {mean_magnitude:.3f}, Max mag: {max_magnitude:.3f}")
if ratio>0.2 and mean_magnitude>0.5 and max_magnitude>2.4:
wave_detected = True
motion_detected = False
print("large_contours: %s and wave_detected: %s" %(len(large_contours) != 0, wave_detected))
if large_contours and wave_detected:
motion_detected = True
if motion_detected:
self.collision_frame_count += 1
if self.collision_frame_count >= stability_threshold:
collision_detected = True
self.collision_frame_count = 1 # Reset the counter
else:
collision_detected = False
else:
self.collision_frame_count = 0
collision_detected = False
# visualization
hsv = np.zeros((prev_gray.shape[0], prev_gray.shape[1], 3), dtype=np.uint8)
hsv[...,1] = 255 # Set to the maximum value (255) to ensure color saturation and easy recognition
hsv[...,0] = ang / 2 # Angle range 0~360=>0~180
max_display_threshold = 10
hsv[..., 2] = np.clip((mag / max_display_threshold) * 255, 0, 255)
prev_bgr = cv2.cvtColor(prev_gray, cv2.COLOR_GRAY2BGR)
curr_bgr = cv2.cvtColor(current_gray, cv2.COLOR_GRAY2BGR)
delta_bgr = cv2.cvtColor(delta, cv2.COLOR_GRAY2BGR)
delta_blur_bgr = cv2.cvtColor(delta_blur, cv2.COLOR_GRAY2BGR)
thresh_bgr = cv2.cvtColor(thresh_raw, cv2.COLOR_GRAY2BGR)
thresh_bgr_3 = cv2.cvtColor(thresh_raw_3, cv2.COLOR_GRAY2BGR)
flow_bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
# Calculate orientation of the thread
if large_contours:
all_points = np.vstack(large_contours)
# Calculate the minimum external rectangle of the contour
rotated_rect = cv2.minAreaRect(all_points) # ((cx, cy), (w, h), angle)
box = cv2.boxPoints(rotated_rect) # Acquire the four vertices of the rectangle
box = box.astype(int)
# Calculate the center, width, height, and angle of the rectangle
center = tuple(map(int, rotated_rect[0]))
width, height = rotated_rect[1]
line_angle = rotated_rect[2]
# Confirm that the width is greater than the height
if width < height:
width, height = height, width
line_angle += 90
# Keep the angle between -90 and 90 degrees
line_angle = line_angle % 180
if line_angle > 90:
line_angle -= 180
elif line_angle <= -90:
line_angle += 180
# Calculate the center line of the rectangle
angle_rad = math.radians(line_angle)
half_length = width / 2
dx = int(half_length * math.cos(angle_rad))
dy = int(half_length * math.sin(angle_rad))
pt1 = (int(center[0] - dx), int(center[1] - dy))
pt2 = (int(center[0] + dx), int(center[1] + dy))
lines_bgr_with_rect = thresh_bgr_3.copy()
cv2.drawContours(lines_bgr_with_rect, [box], 0, (255, 0, 0), 2)
cv2.line(lines_bgr_with_rect, pt1, pt2, (0, 255, 0), 2)
else:
lines_bgr_with_rect = thresh_bgr_3.copy()
line_angle = None
# Visualization
row1 = np.hstack((prev_bgr, curr_bgr, delta_bgr, delta_blur_bgr))
row2 = np.hstack((thresh_bgr, thresh_bgr_3, lines_bgr_with_rect, flow_bgr))
img_vis = np.vstack((row1, row2))
scale_ratio = 4
height, width = img_vis.shape[:2]
new_width = int(width * scale_ratio)
new_height = int(height * scale_ratio)
img_vis = cv2.resize(img_vis, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
return collision_detected, img_vis
def move_worker_autonomous_camera_space_for_PSM1andPSM2(self, psm_quat_initial = np.array([0, 0, 0, 1], dtype=np.float64)):
while not self.stop_flag_threading:
try:
cmd = self.cmd_queue.get(timeout=0.01) # Non blocking acquisition
if cmd[0] == 'set_position' or cmd[0] == 'set_position_phase_2':
target_pos_ = np.array(cmd[1], dtype=np.float64, copy=True) # Convert back to NumPy
# psm_quat_initial = np.array([0, 0, 0, 1], dtype=np.float64)
self.psm_visual_servoing.set_pose(target_pos_, psm_quat_initial)
if cmd[0] == 'stop_motion':
print("PSM stops moving.")
with self.cmd_queue.mutex:
self.cmd_queue.queue.clear()
break
except Empty:
pass
time.sleep(0.01)
def solve_robot_xy_for_pixel(
T_cam_to_robot: np.ndarray,
fx: float, fy: float, cx: float, cy: float,
x_target: float, y_target: float,
z_robot_fixed: float
):
"""
Solve for (x_robot, y_robot) given:
- T_cam_to_robot
- (fx, fy, cx, cy): camera intrinsics
- (x_target, y_target): desired pixel
- z_robot_fixed: keep this Z in robot coords
Returns (x_robot_new, y_robot_new).
"""
# Unpack matrix elements for convenience
# T_cam_to_robot = [ [T00, T01, T02, T03],
# [T10, T11, T12, T13],
# [T20, T21, T22, T23],
# [ 0, 0, 0, 1] ]
T = T_cam_to_robot
A = T[0,0]; B = T[0,1]; _Cz = T[0,2]; Cw = T[0,3]
D = T[1,0]; E = T[1,1]; _Fz = T[1,2]; Fw = T[1,3]
G = T[2,0]; H = T[2,1]; _Iz = T[2,2]; Iw = T[2,3]
# Because z_robot_fixed is constant, incorporate it into "C, F, I"
C = _Cz * z_robot_fixed + Cw
F = _Fz * z_robot_fixed + Fw
I = _Iz * z_robot_fixed + Iw
xtc = (x_target - cx) # "x_target shifted by cx"
ytc = (y_target - cy) # "y_target shifted by cy"
# Build the linear system:
# alpha1 * x_rob + beta1 * y_rob = gamma1
alpha1 = G*xtc - A*fx
beta1 = H*xtc - B*fx
gamma1 = fx*C - I*xtc
# alpha2 * x_rob + beta2 * y_rob = gamma2
alpha2 = G*ytc - D*fy
beta2 = H*ytc - E*fy
gamma2 = fy*F - I*ytc
# Solve the 2x2 system
M = np.array([[alpha1, beta1],
[alpha2, beta2]], dtype=float)
b = np.array([gamma1, gamma2], dtype=float)
# Check for singularity
if abs(np.linalg.det(M)) < 1e-12:
raise ValueError("Singular system: cannot solve for (x_robot, y_robot).")
x_robot_new, y_robot_new = np.linalg.solve(M, b)
Z_cam = G*x_robot_new + H*y_robot_new + I
return x_robot_new, y_robot_new, Z_cam