-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrasp_process_optimized.py
More file actions
executable file
·3078 lines (2619 loc) · 140 KB
/
Copy pathgrasp_process_optimized.py
File metadata and controls
executable file
·3078 lines (2619 loc) · 140 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import numpy as np
import torch
import open3d as o3d
# 设为 True 可跳过 Open3D 弹窗(GUI 模式下由 ui_main.py 设置)
HEADLESS = False
# GUI 模式下注入渲染回调,每隔 _RENDER_INTERVAL 步调用一次以更新相机视图
_render_callback = None
_RENDER_INTERVAL = 40 # 每 40 步渲染一次(约 12fps @ 500Hz sim)
# ==================== 物体来源记忆 ====================
# 记录每次抓取/放置的物体位置历史,用于"放回原处"/"放回货架"等功能
# 格式: {物体名称: {
# "initial": {"position": [x,y,z], "is_shelf": bool, "shelf_layer": int}, # 第一次抓取的位置
# "last_grasp": {"position": [x,y,z], "is_shelf": bool, "shelf_layer": int}, # 最近一次抓取前的位置
# "last_place": {"position": [x,y,z]}, # 最近一次放置的位置
# }}
_object_origin_memory = {}
def _fuzzy_match_name(object_name):
"""模糊匹配物体名称,返回匹配到的 key 或 None"""
if object_name in _object_origin_memory:
return object_name
for key in _object_origin_memory:
if object_name in key or key in object_name:
return key
return None
def record_grasp(object_name, grasp_world_pos, is_shelf, shelf_layer=-1):
"""记录物体被抓取时的位置(抓取前位置)"""
entry = {"position": list(grasp_world_pos), "is_shelf": is_shelf, "shelf_layer": shelf_layer}
if object_name not in _object_origin_memory:
_object_origin_memory[object_name] = {"initial": entry, "last_grasp": entry}
else:
_object_origin_memory[object_name]["last_grasp"] = entry
print(f"[MEMORY] 记录抓取 '{object_name}': pos={grasp_world_pos}, "
f"is_shelf={is_shelf}, layer={shelf_layer}")
def record_place(object_name, place_world_pos, is_shelf=None, shelf_layer=-1):
"""记录物体被放置后的位置。is_shelf/shelf_layer 可选,不传则自动检测。"""
matched = _fuzzy_match_name(object_name)
if matched is None:
_object_origin_memory[object_name] = {}
matched = object_name
pos = list(place_world_pos)
# 自动检测是否为货架位置
if is_shelf is None:
is_shelf, shelf_layer = _auto_detect_shelf(pos)
_object_origin_memory[matched]["last_place"] = {
"position": pos, "is_shelf": is_shelf, "shelf_layer": shelf_layer,
}
print(f"[MEMORY] 记录放置 '{matched}': pos={place_world_pos}, "
f"is_shelf={is_shelf}, layer={shelf_layer}")
# 货架判定常量(与 task_executor.py 保持一致)
_SHELF_X_MIN = 1.61
_SHELF_X_MAX = 1.97
_SHELF_LAYER_HEIGHTS = [0.09, 0.414, 0.738, 1.053, 1.377]
_SHELF_LAYER_TOL = 0.15
def _auto_detect_shelf(pos):
"""根据世界坐标自动判断是否在货架上,返回 (is_shelf, shelf_layer)。"""
if _SHELF_X_MIN <= pos[0] <= _SHELF_X_MAX:
for i, lz in enumerate(_SHELF_LAYER_HEIGHTS):
if abs(pos[2] - lz) < _SHELF_LAYER_TOL:
return True, i
return False, -1
def get_position(object_name, which="initial"):
"""按类型查询物体位置。
which: "initial" / "last_grasp" / "last_place" / "shelf"
返回对应的记录 dict 或 None。
"""
matched = _fuzzy_match_name(object_name)
if matched is None:
return None
mem = _object_origin_memory[matched]
if which == "shelf":
# 优先从 initial 找货架位置,再从 last_grasp 找
for key in ("initial", "last_grasp"):
rec = mem.get(key)
if rec and rec.get("is_shelf"):
return rec
return None
return mem.get(which)
# 向后兼容旧接口
def record_object_origin(object_name, grasp_world_pos, is_shelf, shelf_layer=-1):
record_grasp(object_name, grasp_world_pos, is_shelf, shelf_layer)
def get_object_origin(object_name):
"""向后兼容:返回 initial 位置"""
return get_position(object_name, "initial")
def get_all_origins():
"""返回所有记忆的物体来源(initial 位置)"""
result = {}
for name, mem in _object_origin_memory.items():
if "initial" in mem:
result[name] = mem["initial"]
return result
from PIL import Image
import spatialmath as sm
from manipulator_grasp.arm.motion_planning import *
# ============================================================
# ==================== 桌面抓取参数配置区 ==========================
# ============================================================
# 抓取接近方向(世界坐标系):
# [0, 0, -1] = 纯垂直向下
# [0, 0.5, -0.866] = 向+Y倾斜30度
# [0, 0.6428, -0.7660] = 向+Y倾斜40度
# 公式: [0, sin(角度), -cos(角度)]
GRASP_APPROACH_WORLD = np.array([0, 0.6428, -0.7660]) # 40度
# 抓取点回退距离(米):沿 approach 反方向拉出,避免深入物体
GRASP_PULLBACK = 0.01 # 10mm
# 位置微调偏移(世界坐标系,米)
GRASP_OFFSET_WORLD = np.array([0.0, 0.0, 0.0])
# 是否强制用点云 bounding box 中心作为抓取位置
FORCE_CENTER = True
# ============================================================
# ==================== 抓取居中性检查 ====================
def check_grasp_bilateral(grasp, cloud_points, min_points_per_side=10):
"""
检查抓取是否双侧对称——即夹爪两侧都有物体点云。
如果只有一侧有点,说明抓取在物体边缘,手指会穿过物体。
返回 True 表示抓取居中良好(两侧都有点且比例均衡)。
"""
R = grasp.rotation_matrix
t = grasp.translation
width = grasp.width
height = grasp.height if grasp.height > 0 else 0.02
# 将点云变换到抓取坐标系
local_pts = (cloud_points - t) @ R # (N, 3)
# 只看夹爪附近的点(沿 approach 方向在指尖范围内)
finger_length = 0.06
near_mask = (
(local_pts[:, 0] > -finger_length * 0.5) &
(local_pts[:, 0] < finger_length) &
(np.abs(local_pts[:, 2]) < max(height, 0.02) / 2 + 0.01) &
(np.abs(local_pts[:, 1]) < width / 2 + 0.01)
)
near_pts = local_pts[near_mask]
if len(near_pts) < min_points_per_side * 2:
return False
# 检查 y 轴两侧是否都有足够的点
left_count = np.sum(near_pts[:, 1] < -0.003)
right_count = np.sum(near_pts[:, 1] > 0.003)
if left_count < min_points_per_side or right_count < min_points_per_side:
return False
# 左右比例检查:两侧点数不能差太多(防止严重偏心)
ratio = min(left_count, right_count) / max(left_count, right_count)
return ratio > 0.2 # 至少 20% 的比例平衡
def recenter_grasp(grasp, cloud_points):
"""
沿 binormal(手指连线方向)测量物体实际范围,
将抓取中心校正到物体正中间。
"""
R = grasp.rotation_matrix
t = grasp.translation
height = grasp.height if grasp.height > 0 else 0.02
# 变换到抓取坐标系
local_pts = (cloud_points - t) @ R
# 只看抓取区域附近的点
finger_length = 0.06
near_mask = (
(local_pts[:, 0] > -finger_length * 0.3) &
(local_pts[:, 0] < finger_length) &
(np.abs(local_pts[:, 2]) < max(height, 0.02) / 2 + 0.005)
)
near_pts = local_pts[near_mask]
if len(near_pts) < 20:
print(f" [RECENTER] 附近点太少({len(near_pts)}),跳过校正")
return
# 沿 y 轴(binormal)测量物体实际范围
y_vals = near_pts[:, 1]
y_lo = np.percentile(y_vals, 10)
y_hi = np.percentile(y_vals, 90)
y_center = (y_lo + y_hi) / 2.0
obj_width = y_hi - y_lo
print(f" [RECENTER] y_lo={y_lo*1000:.1f}mm, y_hi={y_hi*1000:.1f}mm, "
f"center_offset={y_center*1000:.1f}mm, obj_width={obj_width*1000:.1f}mm, "
f"near_pts={len(near_pts)}")
# 如果偏移量大于 2mm,执行校正
if abs(y_center) > 0.002:
shift_cam = R[:, 1] * y_center
grasp.translation = t + shift_cam
print(f" [RECENTER] 校正 {y_center*1000:.1f}mm (shift_cam={shift_cam})")
else:
print(f" [RECENTER] 偏移量 {y_center*1000:.1f}mm < 2mm,无需校正")
from graspnetAPI import GraspGroup
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'models'))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'dataset'))
sys.path.append(os.path.join(ROOT_DIR, 'graspnet-baseline', 'utils'))
sys.path.append(os.path.join(ROOT_DIR, 'manipulator_grasp'))
from graspnet import GraspNet, pred_decode
from graspnet_dataset import GraspNetDataset
from collision_detector import ModelFreeCollisionDetector
from data_utils import CameraInfo, create_point_cloud_from_depth_image
# ==================== 点云融合工具 ====================
def fuse_point_clouds(clouds_world, colors_list, T_wc_primary, voxel_size=0.005,
remove_outliers=True, nb_neighbors=20, std_ratio=2.0):
"""
融合多个世界坐标系点云,并变换回主相机坐标系供 GraspNet 使用。
参数:
clouds_world: list of np.ndarray, 每个元素是 (N, 3) 的世界坐标点云
colors_list: list of np.ndarray, 每个元素是 (N, 3) 的颜色
T_wc_primary: sm.SE3, 主相机的世界到相机变换(用于最终输出)
voxel_size: 下采样体素大小
remove_outliers: 是否移除离群点(默认True)
nb_neighbors: 统计离群点去除的邻居数量(默认20)
std_ratio: 标准差倍数阈值(默认2.0,越小过滤越严格)
返回:
cloud_cam: np.ndarray, 融合后的相机坐标系点云
colors_cam: np.ndarray, 对应的颜色
cloud_o3d: o3d.geometry.PointCloud, 用于可视化的 Open3D 点云
"""
# 合并所有点云
all_points = np.vstack(clouds_world)
all_colors = np.vstack(colors_list)
print(f" [FUSION] 原始点云: {len(all_points)} 个点")
# 创建 Open3D 点云用于下采样
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(all_points)
pcd.colors = o3d.utility.Vector3dVector(all_colors)
# 体素下采样去除重复点
pcd_down = pcd.voxel_down_sample(voxel_size=voxel_size)
print(f" [FUSION] 体素下采样后: {len(pcd_down.points)} 个点")
# 统计离群点去除(移除噪声点)
if remove_outliers and len(pcd_down.points) > nb_neighbors:
pcd_filtered, ind = pcd_down.remove_statistical_outlier(
nb_neighbors=nb_neighbors,
std_ratio=std_ratio
)
print(f" [FUSION] 离群点去除后: {len(pcd_filtered.points)} 个点 (移除了 {len(pcd_down.points) - len(pcd_filtered.points)} 个噪声点)")
pcd_down = pcd_filtered
cloud_world = np.asarray(pcd_down.points)
colors = np.asarray(pcd_down.colors)
# 变换回主相机坐标系 (T_cw = T_wc^-1)
T_cw = T_wc_primary.inv()
R_cw = T_cw.R
t_cw = T_cw.t
cloud_cam = (R_cw @ cloud_world.T).T + t_cw
# 创建用于可视化的点云(相机坐标系)
cloud_o3d = o3d.geometry.PointCloud()
cloud_o3d.points = o3d.utility.Vector3dVector(cloud_cam)
cloud_o3d.colors = o3d.utility.Vector3dVector(colors)
return cloud_cam, colors, cloud_o3d
def transform_cloud_to_world(cloud_cam, T_wc):
"""将相机坐标系点云变换到世界坐标系"""
R = T_wc.R
t = T_wc.t
return (R @ cloud_cam.T).T + t
def filter_largest_cluster(cloud, colors, eps=0.02, min_points=10):
"""
使用DBSCAN聚类,只保留最大的点云簇。
参数:
cloud: np.ndarray, (N, 3) 点云
colors: np.ndarray, (N, 3) 颜色
eps: DBSCAN的邻域半径(米)
min_points: DBSCAN的最小点数
返回:
filtered_cloud: np.ndarray, 过滤后的点云
filtered_colors: np.ndarray, 过滤后的颜色
"""
if len(cloud) < min_points:
return cloud, colors
# 创建Open3D点云
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(cloud)
# DBSCAN聚类
labels = np.array(pcd.cluster_dbscan(eps=eps, min_points=min_points))
# 找到最大的簇(排除噪声点,label=-1)
if len(labels) == 0 or np.all(labels == -1):
return cloud, colors
# 统计每个簇的点数
unique_labels = labels[labels >= 0]
if len(unique_labels) == 0:
return cloud, colors
label_counts = np.bincount(unique_labels)
largest_cluster_label = np.argmax(label_counts)
# 只保留最大簇的点
mask = (labels == largest_cluster_label)
filtered_cloud = cloud[mask]
filtered_colors = colors[mask]
removed_count = len(cloud) - len(filtered_cloud)
if removed_count > 0:
print(f" 聚类过滤: 保留最大簇 {len(filtered_cloud)} 个点,移除 {removed_count} 个离散点")
return filtered_cloud, filtered_colors
# ==================== 网络加载 ====================
def get_net():
"""
加载训练好的 GraspNet 模型
"""
net = GraspNet(input_feature_dim=0,
num_view=300,
num_angle=12,
num_depth=4,
cylinder_radius=0.05,
hmin=-0.02,
hmax_list=[0.01, 0.02, 0.03, 0.04],
is_training=False)
net.to(torch.device('cuda:0' if torch.cuda.is_available() else 'cpu'))
checkpoint = torch.load('./logs/log_rs/checkpoint-rs.tar') # checkpoint_path
net.load_state_dict(checkpoint['model_state_dict'])
net.eval()
return net
# ================= 数据处理并生成输入 ====================
def get_and_process_data(color_path, depth_path, mask_path, fovy=np.pi/4):
"""
根据给定的 RGB 图、深度图、掩码图,生成输入点云及其它必要数据
fovy: 垂直视场角 (弧度)
"""
#---------------------------------------
# 1. 加载 color(可能是路径,也可能是数组)
if isinstance(color_path, str):
color = np.array(Image.open(color_path), dtype=np.float32) / 255.0
elif isinstance(color_path, np.ndarray):
color = color_path.astype(np.float32)
color /= 255.0
else:
raise TypeError("color_path 既不是字符串路径也不是 NumPy 数组!")
# 2. 加载 depth(可能是路径,也可能是数组)
if isinstance(depth_path, str):
depth_img = Image.open(depth_path)
depth = np.array(depth_img)
elif isinstance(depth_path, np.ndarray):
depth = depth_path
else:
raise TypeError("depth_path 既不是字符串路径也不是 NumPy 数组!")
# 3. 加载 mask(可能是路径,也可能是数组)
if isinstance(mask_path, str):
workspace_mask = np.array(Image.open(mask_path))
elif isinstance(mask_path, np.ndarray):
workspace_mask = mask_path
else:
raise TypeError("mask_path 既不是字符串路径也不是 NumPy 数组!")
# print("\n=== 尺寸验证 ===")
# print("深度图尺寸:", depth.shape)
# print("颜色图尺寸:", color.shape[:2])
# print("工作空间尺寸:", workspace_mask.shape)
# 构造相机内参矩阵
height = color.shape[0]
width = color.shape[1]
# fovy = np.pi / 4 # 定义的仿真相机
focal = height / (2.0 * np.tan(fovy / 2.0)) # 焦距计算(基于垂直视场角fovy和高度height)
c_x = width / 2.0 # 水平中心
c_y = height / 2.0 # 垂直中心
intrinsic = np.array([
[focal, 0.0, c_x],
[0.0, focal, c_y],
[0.0, 0.0, 1.0]
])
factor_depth = 1.0 # 深度因子,根据实际数据调整
# 利用深度图生成点云 (H,W,3) 并保留组织结构
camera = CameraInfo(width, height, intrinsic[0][0], intrinsic[1][1], intrinsic[0][2], intrinsic[1][2], factor_depth)
cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
# mask = depth < 2.0
# mask = (workspace_mask > 0) & (depth < 2.0)
mask = (workspace_mask > 0) & (depth < 3.5) & (depth > 0.1)
cloud_masked = cloud[mask]
color_masked = color[mask]
# print(f"mask过滤后的点云数量 (color_masked): {len(color_masked)}") # 在采样前打印原始过滤后的点数
NUM_POINT = 5000 # 10000或5000
# 如果点数足够,随机采样NUM_POINT个点(不重复)
if len(cloud_masked) >= NUM_POINT:
idxs = np.random.choice(len(cloud_masked), NUM_POINT, replace=False)
# 如果点数不足,先保留所有点,再随机重复补足NUM_POINT个点
else:
idxs1 = np.arange(len(cloud_masked))
idxs2 = np.random.choice(len(cloud_masked), NUM_POINT - len(cloud_masked), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_masked[idxs]
color_sampled = color_masked[idxs] # 提取点云和颜色
cloud_o3d = o3d.geometry.PointCloud()
cloud_o3d.points = o3d.utility.Vector3dVector(cloud_masked.astype(np.float32))
cloud_o3d.colors = o3d.utility.Vector3dVector(color_masked.astype(np.float32))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
cloud_sampled = torch.from_numpy(cloud_sampled[np.newaxis].astype(np.float32)).to(device)
# end_points = {'point_clouds': cloud_sampled}
end_points = dict()
end_points['point_clouds'] = cloud_sampled
end_points['cloud_colors'] = color_sampled
return end_points, cloud_o3d
# ==================== 主函数:获取抓取预测 ====================
def run_grasp_inference(color_path, depth_path, sam_mask_path=None, T_wc=None, fovy=np.pi/4):
# 1. 加载网络
net = get_net()
# 2. 处理数据,此处使用返回的工作空间掩码路径
end_points, cloud_o3d = get_and_process_data(color_path, depth_path, sam_mask_path, fovy=fovy)
# 2.1 获取相机外参
if T_wc is None:
# 默认值 (当外部未传递时使用旧的硬编码值作为回退)
n_wc = np.array([0.0, -1.0, 0.0])
o_wc = np.array([-1.0, 0.0, -0.5])
t_wc = np.array([0.85, 0.8, 1.6])
T_wc = sm.SE3.Trans(t_wc) * sm.SE3(sm.SO3.TwoVectors(x=n_wc, y=o_wc))
R_wc = T_wc.R
R_cw = R_wc.T # 相机坐标系相对于世界坐标系的旋转
# 计算世界坐标系下的“向上”向量在相机坐标系中的投影
world_up_w = np.array([0, 0, 1])
world_up_c = R_cw @ world_up_w # 相机视角里“天顶”的方向
# 计算世界坐标系下的“垂直向下”向量在相机坐标系中的投影 (抓取接近方向)
world_down_w = np.array([0, 0, -1])
world_down_c = R_cw @ world_down_w # 相机视角里“正下方”的方向
# 3. 前向推理
with torch.no_grad():
end_points = net(end_points)
grasp_preds = pred_decode(end_points)
# 4. 构造 GraspGroup 对象(这里 gg 是列表或类似列表的对象)
gg = GraspGroup(grasp_preds[0].detach().cpu().numpy())
# 5. 碰撞检测
COLLISION_THRESH = 0.01
if COLLISION_THRESH > 0:
voxel_size = 0.01
collision_thresh = 0.01
mfcdetector = ModelFreeCollisionDetector(np.asarray(cloud_o3d.points), voxel_size=voxel_size)
collision_mask = mfcdetector.detect(gg, approach_dist=0.05, collision_thresh=collision_thresh)
gg = gg[~collision_mask]
# 6. NMS 去重 + 按照得分排序(降序)
gg.nms().sort_by_score()
# ===== 智能抓取方向选择 =====
# 根据物品位置(桌面 vs 货架)自动选择抓取方向
# 计算点云在世界坐标系中的平均位置
points_cam = np.asarray(cloud_o3d.points)
cloud_world_check = transform_cloud_to_world(points_cam, T_wc)
avg_pos = np.mean(cloud_world_check, axis=0)
avg_x, avg_y, avg_z = avg_pos
# 货架判断逻辑(与execute_grasp保持一致)
# 货架位置:X范围 [1.61, 1.97],Z高度接近货架层
# 根据scene.xml: 货架碰撞层中心X=1.79, 半宽=0.18
SHELF_X_MIN = 1.61 # 货架前沿 = 1.79 - 0.18
SHELF_X_MAX = 1.97 # 货架后沿 = 1.79 + 0.18
SHELF_LAYER_HEIGHTS = [0.09, 0.414, 0.738, 1.053, 1.377]
SHELF_LAYER_TOLERANCE = 0.15
is_shelf_object = False
if SHELF_X_MIN <= avg_x <= SHELF_X_MAX:
# 检查是否接近某个货架层
for layer_z in SHELF_LAYER_HEIGHTS:
if abs(avg_z - layer_z) < SHELF_LAYER_TOLERANCE:
is_shelf_object = True
break
if is_shelf_object:
print(f"\n[GRASP] 检测到货架物品 (位置: X={avg_x:.2f}, Y={avg_y:.2f}, Z={avg_z:.2f}),使用水平抓取过滤")
grasp_mode = "horizontal"
else:
print(f"\n[GRASP] 检测到桌面物品 (位置: X={avg_x:.2f}, Y={avg_y:.2f}, Z={avg_z:.2f}),使用垂直抓取过滤")
grasp_mode = "vertical"
# 计算参考方向
world_z_c = R_cw @ np.array([0, 0, 1]) # 垂直向上
# 将 gg 转换为普通列表
all_grasps = list(gg)
angle_threshold = np.deg2rad(30) # 30度的弧度值
filtered = []
if grasp_mode == "vertical":
# 垂直抓取:接近方向应该接近垂直向下
for grasp in all_grasps:
approach_dir_c = grasp.rotation_matrix[:, 0]
cos_angle = np.dot(approach_dir_c, world_down_c)
cos_angle = np.clip(cos_angle, -1.0, 1.0)
angle = np.arccos(cos_angle)
if angle < angle_threshold:
filtered.append(grasp)
if len(filtered) == 0:
print("\n[Warning] No grasp predictions within vertical angle threshold.")
print("[FIX] 构造垂直向下抓取姿态替代...")
# 世界坐标系中垂直向下旋转矩阵,转换到相机坐标系
R_down_world = np.array([[0, 0, -1],
[0, 1, 0],
[1, 0, 0]], dtype=np.float64)
R_down_cam = R_cw @ R_down_world
# 使用点云质心作为抓取位置(比 GraspNet 预测平均值更准确)
obj_center_cam = np.mean(points_cam, axis=0) if len(points_cam) > 0 \
else np.mean([g.translation for g in all_grasps], axis=0)
from graspnetAPI import Grasp
synth_grasp = Grasp()
synth_grasp.score = 0.9
synth_grasp.width = 0.05
synth_grasp.height = 0.02
synth_grasp.depth = 0.1
synth_grasp.rotation_matrix = R_down_cam
synth_grasp.translation = obj_center_cam
synth_grasp.object_id = -1
filtered = [synth_grasp]
print(f"[FIX] 已构造垂直向下抓取,相机坐标: {obj_center_cam}")
else:
print(f"\n[DEBUG] Filtered {len(filtered)} grasps within ±30° of vertical out of {len(all_grasps)} total predictions.")
else: # horizontal
# 水平抓取:接近方向应该与世界Z轴垂直(即在水平面内)
horizontal_threshold = np.deg2rad(30) # 允许±30度偏差
for grasp in all_grasps:
approach_dir_c = grasp.rotation_matrix[:, 0]
# 计算与垂直方向的夹角
cos_angle = np.clip(np.dot(approach_dir_c, world_z_c), -1.0, 1.0)
angle_from_vertical = np.arccos(np.abs(cos_angle))
# 水平抓取:角度应该接近90度(π/2)
deviation_from_horizontal = abs(angle_from_vertical - np.pi/2)
if deviation_from_horizontal < horizontal_threshold:
filtered.append(grasp)
if len(filtered) == 0:
print("\n[Warning] No grasp predictions within horizontal angle threshold. Using all predictions.")
filtered = all_grasps
else:
print(f"\n[DEBUG] Filtered {len(filtered)} grasps within ±30° of horizontal out of {len(all_grasps)} total predictions.")
# # ===== 新增:利用 SAM 生成的目标掩码过滤抓取预测(投影到图像坐标判断) =====
if sam_mask_path is not None:
# 加载 SAM 目标掩码
if isinstance(sam_mask_path, str):
sam_mask = np.array(Image.open(sam_mask_path))
elif isinstance(sam_mask_path, np.ndarray):
sam_mask = sam_mask_path
else:
raise TypeError("sam_mask_path 既不是字符串路径也不是 NumPy 数组!")
# 假定 SAM 掩码与颜色图尺寸一致(640x640)
height, width = sam_mask.shape[:2]
# 动态计算相机内参
focal = height / (2.0 * np.tan(fovy / 2.0)) # 焦距计算(像素单位)
cx = width / 2.0 # 光心 X 坐标(图像中心)
cy = height / 2.0 # 光心 Y 坐标(图像中心)
sam_filtered = []
for grasp in filtered:
# grasp.translation 为摄像头坐标系下的 3D 坐标 [X, Y, Z]
X, Y, Z = grasp.translation
if Z <= 0:
continue
u = focal * X / Z + cx
v = focal * Y / Z + cy
u_int = int(round(u))
v_int = int(round(v))
# 检查投影点是否在图像范围内(640x640)
if u_int < 0 or u_int >= 640 or v_int < 0 or v_int >= 640:
continue
# 若 SAM 掩码中该像素有效(非0),则保留
if sam_mask[v_int, u_int] > 0:
sam_filtered.append(grasp)
if len(sam_filtered) == 0:
print("\n[Warning] No grasp predictions fall inside the SAM mask. Using previous predictions.")
else:
print(f"\n[DEBUG] Filtered {len(sam_filtered)} grasps inside the SAM mask out of {len(filtered)} predictions.")
filtered = sam_filtered
# ===== 新增部分:计算物体中心点 =====
# 使用点云计算物体的中心点
points = np.asarray(cloud_o3d.points)
object_center = np.mean(points, axis=0) if len(points) > 0 else np.zeros(3)
# 计算每个抓取位姿中心点与物体中心点的距离
distances = []
for grasp in filtered:
grasp_center = grasp.translation
distance = np.linalg.norm(grasp_center - object_center)
distances.append(distance)
# 创建一个新的排序列表,包含距离和抓取对象
grasp_with_distances = [(g, d) for g, d in zip(filtered, distances)]
# 按距离升序排序(距离越小越好)
grasp_with_distances.sort(key=lambda x: x[1])
# 提取排序后的抓取列表
filtered = [g for g, d in grasp_with_distances]
# ===== 新增部分:综合得分和距离进行最终排序 =====
# 创建一个新的排序列表,包含综合得分和抓取对象
# 综合得分 = 抓取得分 * 0.7 + (1 - 距离/最大距离) * 0.3
max_distance = max(distances) if distances else 1.0
grasp_with_composite_scores = []
for g, d in grasp_with_distances:
# 归一化距离分数(距离越小分数越高)
distance_score = 1 - (d / max_distance)
# 综合得分 = 抓取得分 * 权重1 + 距离得分 * 权重2
composite_score = g.score * 0.1 + distance_score * 0.9
# print(f"\n g.score = {g.score}, distance_score = {distance_score}")
grasp_with_composite_scores.append((g, composite_score))
# 按综合得分降序排序
grasp_with_composite_scores.sort(key=lambda x: x[1], reverse=True)
# 提取排序后的抓取列表
filtered = [g for g, score in grasp_with_composite_scores]
# # 对过滤后的抓取根据 score 排序(降序)
# filtered.sort(key=lambda g: g.score, reverse=True)
# 取第1个抓取
top_grasps = filtered[:1]
# 可视化过滤后的抓取,手动转换为 Open3D 物体
grippers = [g.to_open3d_geometry() for g in top_grasps]
# 选择得分最高的抓取(filtered 列表已按得分降序排序)
best_grasp = top_grasps[0]
# ===== 调试信息:显示抓取位置 =====
grasp_pos_cam = best_grasp.translation
grasp_pos_world = transform_cloud_to_world(grasp_pos_cam.reshape(1, 3), T_wc)[0]
print(f"\n[DEBUG] 抓取位置:")
print(f" 相机坐标系: ({grasp_pos_cam[0]:.3f}, {grasp_pos_cam[1]:.3f}, {grasp_pos_cam[2]:.3f})")
print(f" 世界坐标系: ({grasp_pos_world[0]:.3f}, {grasp_pos_world[1]:.3f}, {grasp_pos_world[2]:.3f})")
print(f" 物体中心 (相机): ({object_center[0]:.3f}, {object_center[1]:.3f}, {object_center[2]:.3f})")
object_center_world = transform_cloud_to_world(object_center.reshape(1, 3), T_wc)[0]
print(f" 物体中心 (世界): ({object_center_world[0]:.3f}, {object_center_world[1]:.3f}, {object_center_world[2]:.3f})")
# ===== 货架物品:强制水平化抓取姿态 =====
if grasp_mode == "horizontal":
print("🔧 货架物品:强制调整为水平抓取姿态...")
# 获取当前抓取位置
grasp_pos_c = best_grasp.translation
# 计算从抓取点指向物体中心的方向(在相机坐标系中)
to_center = object_center - grasp_pos_c
to_center_norm = np.linalg.norm(to_center)
if to_center_norm > 1e-6:
# 将这个方向投影到水平面(去除Z分量)
# 首先转换到世界坐标系
to_center_world = R_wc @ to_center
to_center_world[2] = 0 # 去除Z分量,保持水平
# 归一化
to_center_world_norm = np.linalg.norm(to_center_world)
if to_center_world_norm > 1e-6:
to_center_world = to_center_world / to_center_world_norm
# 转回相机坐标系
approach_horizontal_c = R_cw @ to_center_world
else:
# 如果投影后长度为0,使用默认水平方向(+X)
approach_horizontal_c = R_cw @ np.array([1, 0, 0])
else:
# 如果抓取点就在中心,使用默认水平方向
approach_horizontal_c = R_cw @ np.array([1, 0, 0])
# 归一化接近方向
approach_horizontal_c = approach_horizontal_c / np.linalg.norm(approach_horizontal_c)
# 构建新的旋转矩阵
# x轴 = 水平接近方向
# y轴 = 垂直于接近方向和世界Z轴
# z轴 = x × y
a_c = approach_horizontal_c # 接近方向(水平)
# y轴应该垂直于接近方向和世界Z轴
# y = normalize(world_up_c × a_c)
y_c = np.cross(world_up_c, a_c)
y_norm = np.linalg.norm(y_c)
if y_norm > 1e-6:
y_c = y_c / y_norm
# z轴 = x × y
z_c = np.cross(a_c, y_c)
z_c = z_c / np.linalg.norm(z_c)
# 更新旋转矩阵
best_grasp.rotation_matrix = np.column_stack([a_c, y_c, z_c])
print("✅ 已强制调整为水平抓取姿态 (Horizontal Grasp Enforced)")
else:
print("⚠️ 无法构建水平抓取姿态,保持原姿态")
# ===== 桌面物品:抓取头自动调平 (Auto-leveling) =====
elif grasp_mode == "vertical":
# 目的:让夹爪的横梁(binormal)在世界坐标系下保持水平,避免倾斜撞击桌面
# 抓取坐标系定义: x=approach, y=binormal(手指连线)
a_c = best_grasp.rotation_matrix[:, 0] # 接近方向 (保持不变)
# 我们希望新的 binormal (y_c) 垂直于世界 Z 轴 (world_up_c) 和 接近方向 (a_c)
# y_c_new = normalize(cross(world_up_c, a_c))
y_c_new = np.cross(world_up_c, a_c)
norm = np.linalg.norm(y_c_new)
if norm > 1e-6:
y_c_new /= norm
z_c_new = np.cross(a_c, y_c_new)
z_c_new /= np.linalg.norm(z_c_new)
# 更新旋转矩阵,实现"调平"旋转
best_grasp.rotation_matrix = np.column_stack([a_c, y_c_new, z_c_new])
print("✅ 已自动执行抓取头调平优化 (Orientation Auto-leveled)")
best_translation = best_grasp.translation
best_rotation = best_grasp.rotation_matrix
best_width = best_grasp.width
# 创建一个新的 GraspGroup 并添加最佳抓取
new_gg = GraspGroup() # 初始化空的 GraspGroup
new_gg.add(best_grasp) # 添加最佳抓取
if not HEADLESS:
grippers = new_gg.to_open3d_geometry_list()
o3d.visualization.draw_geometries([cloud_o3d, *grippers])
return new_gg
#return best_translation, best_rotation, best_width
# ==================== 多相机点云融合抓取推理 ====================
def run_grasp_inference_fused(camera_data_list, T_wc_primary, fovy_primary, desktop_mode=False):
"""
多相机点云融合抓取推理。
参数:
camera_data_list: list of dict, 每个dict包含:
- 'color': np.ndarray, RGB图像
- 'depth': np.ndarray, 深度图
- 'mask': np.ndarray, SAM分割掩码
- 'T_wc': sm.SE3, 相机的世界到相机变换
- 'fovy': float, 垂直视场角(弧度)
T_wc_primary: sm.SE3, 主相机的变换(用于输出抓取姿态)
fovy_primary: float, 主相机的fovy
desktop_mode: bool, True=桌面三相机模式(30度倾斜+居中检查),False=货架模式(保持原逻辑)
返回:
gg: GraspGroup, 最佳抓取
"""
print("\n[FUSION] 开始多相机点云融合...")
clouds_world = []
colors_list = []
# 从每个相机生成点云并变换到世界坐标系
for i, cam_data in enumerate(camera_data_list):
color = cam_data['color']
depth = cam_data['depth']
mask = cam_data['mask']
T_wc = cam_data['T_wc']
fovy = cam_data['fovy']
# 确保color是float格式
if color.dtype == np.uint8:
color = color.astype(np.float32) / 255.0
# 计算相机内参
height, width = depth.shape[:2]
focal = height / (2.0 * np.tan(fovy / 2.0))
camera_info = CameraInfo(width, height, focal, focal, width/2, height/2, 1.0)
cloud = create_point_cloud_from_depth_image(depth, camera_info, organized=True)
# 应用mask过滤(深度上限需覆盖 cam_2 等高位相机,z≈2.95 看桌面深度约2.3m)
valid_mask = (mask > 0) & (depth < 3.5) & (depth > 0.1)
cloud_masked = cloud[valid_mask]
color_masked = color[valid_mask]
print(f" 相机 {i+1}: {len(cloud_masked)} 个点(mask过滤后)")
# 聚类过滤:只保留最大的点云簇(去除VLM分割的噪声)
cloud_masked, color_masked = filter_largest_cluster(
cloud_masked, color_masked, eps=0.02, min_points=10
)
# 变换到世界坐标系
cloud_world = transform_cloud_to_world(cloud_masked, T_wc)
clouds_world.append(cloud_world)
colors_list.append(color_masked)
print(f" 相机 {i+1}: {len(cloud_masked)} 个点(聚类过滤后)")
# 融合点云
voxel_size_fuse = 0.002 if desktop_mode else 0.005
cloud_fused, colors_fused, cloud_o3d = fuse_point_clouds(
clouds_world, colors_list, T_wc_primary, voxel_size=voxel_size_fuse
)
print(f" 融合后(原始): {len(cloud_fused)} 个点")
# 桌面模式:统计离群点移除
if desktop_mode and len(cloud_fused) > 50:
cl, inlier_idx = cloud_o3d.remove_statistical_outlier(nb_neighbors=20, std_ratio=1.5)
cloud_fused = cloud_fused[inlier_idx]
colors_fused = colors_fused[inlier_idx]
cloud_o3d = cl
print(f" 离群点移除后: {len(cloud_fused)} 个点")
print(f" 融合后: {len(cloud_fused)} 个点")
# 采样点云用于网络输入
NUM_POINT = 5000
if len(cloud_fused) >= NUM_POINT:
idxs = np.random.choice(len(cloud_fused), NUM_POINT, replace=False)
else:
idxs1 = np.arange(len(cloud_fused))
idxs2 = np.random.choice(len(cloud_fused), NUM_POINT - len(cloud_fused), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_fused[idxs]
color_sampled = colors_fused[idxs]
# 转换为网络输入格式
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
cloud_tensor = torch.from_numpy(cloud_sampled[np.newaxis].astype(np.float32)).to(device)
end_points = dict()
end_points['point_clouds'] = cloud_tensor
end_points['cloud_colors'] = color_sampled
# 加载网络并推理
net = get_net()
# 计算世界坐标系下的"向下"方向在主相机坐标系中的投影
R_wc = T_wc_primary.R
R_cw = R_wc.T
world_down_c = R_cw @ np.array([0, 0, -1])
# 前向推理
with torch.no_grad():
end_points = net(end_points)
grasp_preds = pred_decode(end_points)
gg = GraspGroup(grasp_preds[0].detach().cpu().numpy())
# 碰撞检测
if len(gg) > 0:
if desktop_mode:
mfcdetector = ModelFreeCollisionDetector(cloud_fused, voxel_size=0.005)
collision_mask, empty_mask = mfcdetector.detect(
gg, approach_dist=0.05, collision_thresh=0.01,
return_empty_grasp=True, empty_thresh=0.01
)
valid_mask = (~collision_mask) & (~empty_mask)
gg = gg[valid_mask]
print(f"[FUSION] 碰撞检测: 碰撞={collision_mask.sum()}, 空抓={empty_mask.sum()}, 保留={valid_mask.sum()}")
else:
mfcdetector = ModelFreeCollisionDetector(cloud_fused, voxel_size=0.01)
collision_mask = mfcdetector.detect(gg, approach_dist=0.05, collision_thresh=0.01)
gg = gg[~collision_mask]
# NMS
if len(gg) > 0:
gg.nms().sort_by_score()
# ===== 抓取方向选择与最佳抓取 =====
if desktop_mode:
# ===== 桌面模式:垂直角度过滤 + 30度倾斜固定姿态 =====
all_grasps = list(gg)
angle_threshold = np.deg2rad(30)
filtered = []
for grasp in all_grasps:
approach_dir_c = grasp.rotation_matrix[:, 0]
cos_angle = np.clip(np.dot(approach_dir_c, world_down_c), -1.0, 1.0)
angle = np.arccos(cos_angle)
if angle < angle_threshold:
filtered.append(grasp)
if len(filtered) > 0:
print(f"[FUSION] angle filter +-30 deg: {len(filtered)}/{len(all_grasps)} passed")
else:
print(f"[FUSION] 0/{len(all_grasps)} passed 30 deg -> 将强制垂直向下抓取")
filtered = all_grasps
# 选择最佳抓取:综合得分和距物体中心距离
if len(filtered) > 0:
# 计算物体中心(用 bounding box 中心)
if len(cloud_fused) > 0:
bbox_min = np.min(cloud_fused, axis=0)
bbox_max = np.max(cloud_fused, axis=0)
object_center = (bbox_min + bbox_max) / 2.0
else:
object_center = np.zeros(3)
# 按综合得分排序(距离中心越近越好)
distances = [np.linalg.norm(g.translation - object_center) for g in filtered]
max_dist = max(distances) if distances else 1.0
scored = []
for g, d in zip(filtered, distances):
dist_score = 1 - (d / max_dist) if max_dist > 0 else 1.0
composite = g.score * 0.4 + dist_score * 0.6
scored.append((g, composite))
scored.sort(key=lambda x: x[1], reverse=True)
filtered_sorted = [g for g, s in scored]
# 双侧居中性检查
bilateral_filtered = [g for g in filtered_sorted if check_grasp_bilateral(g, cloud_fused)]
if len(bilateral_filtered) > 0:
print(f"[FUSION] 双侧检查: {len(bilateral_filtered)}/{len(filtered_sorted)} 个抓取通过居中性检查")
best_grasp = bilateral_filtered[0]
else:
print("[FUSION Warning] 没有抓取通过双侧检查,使用最高综合得分")
best_grasp = filtered_sorted[0]
# ===== 固定抓取姿态(用配置区的参数) =====
R_wc_dt = T_wc_primary.R
R_cw_dt = R_wc_dt.T
world_up_c = R_cw_dt @ np.array([0, 0, 1])