-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmmdetection3d_changes.patch
3122 lines (3117 loc) · 126 KB
/
mmdetection3d_changes.patch
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
diff --git a/configs/fcos3d/fcos3d_r101_caffe_fpn_gn-head_dcn_2x8_1x_nus-mono3d-adv.py b/configs/fcos3d/fcos3d_r101_caffe_fpn_gn-head_dcn_2x8_1x_nus-mono3d-adv.py
new file mode 100644
index 00000000..ecad15d7
--- /dev/null
+++ b/configs/fcos3d/fcos3d_r101_caffe_fpn_gn-head_dcn_2x8_1x_nus-mono3d-adv.py
@@ -0,0 +1,99 @@
+_base_ = [
+ '../_base_/datasets/nus-mono3d.py', '../_base_/models/fcos3d.py',
+ '../_base_/schedules/mmdet_schedule_1x.py', '../_base_/default_runtime.py'
+]
+
+
+dataset_type = 'NuScenesMonoDatasetNoFliter'
+
+# model settings
+model = dict(
+ backbone=dict(
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
+ stage_with_dcn=(False, False, True, True)))
+
+class_names = [
+ 'car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle',
+ 'motorcycle', 'pedestrian', 'traffic_cone', 'barrier'
+]
+img_norm_cfg = dict(
+ mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
+train_pipeline = [
+ dict(type='LoadImageFromFileMono3DImgOrg'),
+ dict(
+ type='LoadAnnotations3D',
+ with_bbox=True,
+ with_label=True,
+ with_attr_label=True,
+ with_bbox_3d=True,
+ with_label_3d=True,
+ with_bbox_depth=True),
+ dict(type='Resize', img_scale=(1600, 900), keep_ratio=True),
+ dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5),
+ dict(type='Normalize', **img_norm_cfg),
+ dict(type='Pad', size_divisor=32),
+ dict(type='DefaultFormatBundle3D', class_names=class_names),
+ dict(
+ type='Collect3D',
+ keys=[
+ 'img', 'gt_bboxes', 'gt_labels', 'attr_labels', 'gt_bboxes_3d',
+ 'gt_labels_3d', 'centers2d', 'depths'
+ ]),
+]
+test_pipeline = [
+ dict(type='LoadImageFromFileMono3DImgOrg'),
+ dict(
+ type='LoadAnnotations3D',
+ with_bbox=True,
+ with_label=True,
+ with_attr_label=True,
+ with_bbox_3d=True,
+ with_label_3d=True,
+ with_bbox_depth=True),
+ dict(
+ type='MultiScaleFlipAug',
+ scale_factor=1.0,
+ flip=False,
+ transforms=[
+ dict(type='RandomFlip3D'),
+ dict(type='Normalize', **img_norm_cfg),
+ dict(type='Pad', size_divisor=32),
+ dict(
+ type='DefaultFormatBundle3D',
+ class_names=class_names,
+ with_label=False),
+ dict(type='Collect3D',
+ keys=[
+ 'img', 'gt_bboxes', 'gt_labels', 'attr_labels', 'gt_bboxes_3d',
+ 'gt_labels_3d', 'centers2d', 'depths'
+ ],
+ meta_keys=('filename', 'ori_shape', 'img_shape', 'lidar2img',
+ 'depth2img', 'cam2img', 'pad_shape',
+ 'scale_factor', 'flip', 'pcd_horizontal_flip',
+ 'pcd_vertical_flip', 'box_mode_3d', 'box_type_3d',
+ 'img_norm_cfg', 'pcd_trans', 'sample_idx',
+ 'pcd_scale_factor', 'pcd_rotation', 'pts_filename',
+ 'transformation_3d_flow', 'img_org')
+ ),
+ ])
+]
+data = dict(
+ samples_per_gpu=2,
+ workers_per_gpu=2,
+ train=dict(pipeline=train_pipeline),
+ val=dict(pipeline=test_pipeline, type=dataset_type, test_mode=False),
+ test=dict(pipeline=test_pipeline, type=dataset_type, test_mode=False))
+# optimizer
+optimizer = dict(
+ lr=0.002, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.))
+optimizer_config = dict(
+ _delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
+# learning policy
+lr_config = dict(
+ policy='step',
+ warmup='linear',
+ warmup_iters=500,
+ warmup_ratio=1.0 / 3,
+ step=[8, 11])
+total_epochs = 12
+evaluation = dict(interval=2)
diff --git a/extend/__init__.py b/extend/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/extend/custom_func.py b/extend/custom_func.py
new file mode 100644
index 00000000..75dc268e
--- /dev/null
+++ b/extend/custom_func.py
@@ -0,0 +1,109 @@
+# for fcos3d
+import torch
+import torchvision
+import torchvision.transforms as transforms
+import torch.nn.functional as F
+from torchvision.utils import save_image
+import math
+
+
+def custom_data_preprocess(data):
+ for _key in data:
+ data[_key] = data[_key][0]
+ return data
+
+def custom_data_postprocess_eval(data):
+ data.pop('gt_bboxes', None)
+ data.pop('gt_labels', None)
+
+ data.pop('gt_bboxes_3d', None)
+ data.pop('gt_labels_3d', None)
+
+ data.pop('attr_labels', None)
+ data.pop('centers2d', None)
+ data.pop('depths', None)
+
+ for _key in data:
+ data[_key] = [data[_key]]
+ return data
+
+def custom_data_work(data):
+ metas = data['img_metas']._data[0][0]
+ img_path_list = [metas['filename']]
+ img_org_np = metas['img_org'][...,None]
+ img_processed = data['img']._data[0].clone()
+ gt_labels_3d = data['gt_labels_3d']._data[0][0]
+ return metas, img_path_list, img_org_np, img_processed, gt_labels_3d
+
+
+def custom_result_postprocess(result):
+ return result
+
+
+# def custom_img_read_from_img_org(img_org_np, device):
+# img_org_np_255_rgb_hwcn_uint8 = img_org_np # mmcv 读取 BGR 转 numpy
+# img_org_tensor_rgb_255_hwcn = torch.from_numpy(img_org_np_255_rgb_hwcn_uint8).float()
+# img_org_tensor_rgb_255 = img_org_tensor_rgb_255_hwcn.permute(3,2,0,1)
+# img_org_tensor_rgb = (img_org_tensor_rgb_255/255.).to(device) # 1chw
+# img_tensor_rgb_6chw_0to1 = img_org_tensor_rgb /255.
+# return img_tensor_rgb_6chw_0to1
+
+
+def custom_img_read_from_img_org(img_org_np, device):
+ img_org_np_255_bgr_hwcn_uint8 = img_org_np # mmcv 读取 BGR 转 numpy
+ img_org_tensor_bgr_255_hwcn = torch.from_numpy(img_org_np_255_bgr_hwcn_uint8).float()
+ img_org_tensor_bgr_255 = img_org_tensor_bgr_255_hwcn.permute(3,2,0,1)
+ img_org_tensor_bgr = (img_org_tensor_bgr_255/255.).to(device) # 1chw
+ img_org_tensor_rgb = img_org_tensor_bgr[:,[2,1,0]]
+ img_tensor_rgb_6chw_0to1 = img_org_tensor_rgb
+ return img_tensor_rgb_6chw_0to1
+
+
+
+
+def custom_differentiable_transform(img_tensor_rgb_6chw_0to1, img_metas):
+ """Alternative Data Preparation for Original Model
+
+ Args:
+ img_tensor (torch.tensor): (6xCxHxW), tensors of original imgs
+ """
+ assert len(img_tensor_rgb_6chw_0to1.shape) == 4
+ assert img_tensor_rgb_6chw_0to1.shape[1] == 3
+ assert img_tensor_rgb_6chw_0to1.max() <= 1.
+ assert img_tensor_rgb_6chw_0to1.min() >= 0.
+ assert img_tensor_rgb_6chw_0to1.dtype == torch.float32
+ assert img_tensor_rgb_6chw_0to1.is_cuda
+ device = img_tensor_rgb_6chw_0to1.device
+ #[6,3,900,1600]
+ img_tensor_255 = img_tensor_rgb_6chw_0to1 * 255.0
+
+ # fcos3d
+ # img_norm_cfg = dict(
+ # mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
+
+ if img_metas['img_norm_cfg']['to_rgb']:
+ # 如果 to_rgb,因为现在已经是 rgb所以直接不管,
+ pass
+ else:
+ # 如果 False ,因为现在是 rgb 所以需要转bgr 参考 mmcv.imnormlize 代码 先调整RGB顺序,后进行norm
+ img_tensor_255 = img_tensor_255[:,[2,1,0]]
+
+ device = img_tensor_rgb_6chw_0to1.device
+ mean = torch.tensor(img_metas['img_norm_cfg']['mean']).to(device)[None,:,None, None]
+ std = torch.tensor(img_metas['img_norm_cfg']['std']).to(device)[None,:,None, None]
+
+ ############ norm pad
+ ######## norm
+ img_tensor_255_norm = (img_tensor_255 - mean)/std
+ N, C , H, W = img_tensor_255_norm.shape
+ ######## pad
+ img_h, img_w = img_metas['ori_shape'][:2]
+ pad_h, pad_w = img_metas['pad_shape'][:2]
+ assert (img_h==H) and (img_w==W)
+ image_norm_pad = torch.zeros(N,C,pad_h,pad_w, device=device)
+ image_norm_pad[:,:,:img_h, :img_w] = img_tensor_255_norm
+ return image_norm_pad
+
+def custom_image_data_give(data, image_ready):
+ data['img']._data[0] = image_ready
+ return data
diff --git a/extend_common b/extend_common
new file mode 120000
index 00000000..f54ca4f9
--- /dev/null
+++ b/extend_common
@@ -0,0 +1 @@
+../extend_common
\ No newline at end of file
diff --git a/mmdet3d/apis/test_patch_temporal_fcos3d.py b/mmdet3d/apis/test_patch_temporal_fcos3d.py
new file mode 100644
index 00000000..070ac61c
--- /dev/null
+++ b/mmdet3d/apis/test_patch_temporal_fcos3d.py
@@ -0,0 +1,338 @@
+import mmcv
+import torch
+import numpy as np
+import PIL.Image as Image
+import torchvision.transforms as transforms
+import torch.nn.functional as F
+import torchvision
+from torchvision.utils import save_image
+import cv2
+import time
+import os
+import pickle
+from extend.custom_func import *
+from extend_common.img_check import img_diff_print
+from extend_common.time_counter import time_counter
+from extend_common.patch_apply import apply_patches_by_info_4side
+from extend_common.path_string_split import split_path_string_to_multiname
+
+
+def single_gpu_test(model, data_loader,
+ scattered_result_prefix=None,
+ area_rate_str=None,
+ optim_lr=None,
+ optim_step=None,
+ index_min = None,
+ index_max = None,
+ ):
+
+ model.eval()
+ dataset = data_loader.dataset
+ device = model.src_device_obj
+
+ scattered_result_dir = scattered_result_prefix +'_area'+area_rate_str+'_lr'+optim_lr+'_step' + optim_step
+ os.makedirs(scattered_result_dir, exist_ok=True)
+
+ optim_lr = float(optim_lr)
+ optim_step = int(optim_step)
+
+
+
+ max_epoch_local = optim_step
+
+
+ patch_info_list_database = {}
+ time_test_flag = False
+
+ scene_name_old = 'xxxxaaa111'
+
+
+ results = []
+ prog_bar = mmcv.ProgressBar(len(dataset))
+ last_time = time.time()
+ for data_i, data_out in enumerate(data_loader):
+ if data_i < index_min:
+ prog_bar.update()
+ continue
+ if data_i > index_max:
+ break
+
+ #### 1. data processing(customed)
+ data_out = custom_data_preprocess(data_out)
+ _, img_path_list, _, _, _ = custom_data_work(data_out)
+ last_time = time_counter(last_time, 'data load', time_test_flag)
+ cam_num = len(img_path_list)
+
+
+ #### 2. read patch info from file/database
+ if not str(data_i) in patch_info_list_database:
+ patch_info_list = []
+ for cams_i in range(cam_num):
+ img_path = img_path_list[cams_i]
+ file_name_valid_list = split_path_string_to_multiname(img_path)[-3:]
+ file_name_valid_list.insert(0, '/data/zijian/mycode/BEV_Robust/TransFusion/patch_info_2d3d3dt_square_dir/all')
+ info_path = os.path.join(*file_name_valid_list)
+ info_path = info_path.replace('.jpg', '.pkl')
+ info_i = pickle.load(open(info_path, 'rb'))
+ patch_info_list.append(info_i)
+ patch_info_list_database[str(data_i)] = patch_info_list
+ else:
+ patch_info_list = patch_info_list_database[str(data_i)]
+ last_time = time_counter(last_time, 'read pkl', time_test_flag)
+
+
+ '''
+ 由于我们要一个场景(大概40帧左右),一起进行攻击
+ 所以我需要先遍历数据集,把这一个场景的数据先拿出来,统计里面instance的数量,构建一个 patch 库
+ 然后再在读取出的这一个场景的数据里做攻击
+
+ 如果是场景的第0帧
+ 则开始遍历当前场景,直到下一个第0帧的出现,这时候暂存下一个第0帧
+ 遍历场景时,存下所有的注释信息,
+ 并从之前存好的 patch info 中 获取 instance_token
+ '''
+
+
+ # scene_start_here_flag = (data_i in scene_start_idx_list) # 这个东西不能用了,因为场景顺序变了
+
+
+ # 重新判断场景开始
+ if type(info_i) == str:
+ # 没有gt,直接判断为,不切换场景
+ scene_start_here_flag = False
+ else:
+ scene_name = info_i['scene_info']['scene_name']
+ if scene_name != scene_name_old:
+ print('start here!')
+ scene_start_here_flag = True
+ else:
+ scene_start_here_flag = False
+
+
+ scene_name_old = scene_name
+
+ go_to_training_flag = False
+
+ if data_i == 0:
+ # 第0帧
+ # start new
+ data_in_scene_list = []
+ patch_info_in_scene_list = []
+ data_i_list = []
+ data_in_scene_list.append(data_out)
+ patch_info_in_scene_list.append(patch_info_list)
+ data_i_list.append(data_i)
+ elif scene_start_here_flag and data_i > 0:
+ # 之后的每一个首帧
+ # 存一个连续场景的全部 data 和 patch_info
+ # end old
+ try:
+ data_in_scene_list_full = data_in_scene_list
+ patch_info_in_scene_list_full = patch_info_in_scene_list
+ data_i_list_full = data_i_list
+ go_to_training_flag = True
+ except:
+ print('start from data_i:', data_i)
+ # start new
+ data_in_scene_list = []
+ patch_info_in_scene_list = []
+ data_i_list = []
+ data_in_scene_list.append(data_out)
+ patch_info_in_scene_list.append(patch_info_list)
+ data_i_list.append(data_i)
+ elif data_i == len(dataset)-1:
+ data_in_scene_list.append(data_out)
+ patch_info_in_scene_list.append(patch_info_list)
+ data_i_list.append(data_i)
+ # 最后一帧
+ # end old
+ data_in_scene_list_full = data_in_scene_list
+ patch_info_in_scene_list_full = patch_info_in_scene_list
+ data_i_list_full = data_i_list
+ go_to_training_flag = True
+ else:
+ data_in_scene_list.append(data_out)
+ patch_info_in_scene_list.append(patch_info_list)
+ data_i_list.append(data_i)
+ prog_bar.update()
+
+ if go_to_training_flag:
+ # local dataset: data_in_scene_list_full
+ # local dataset: patch_info_in_scene_list_full
+ # local dataset: data_i_list_full
+ scene_length = len(data_in_scene_list_full)
+
+ ###### 1.构建patch库 Establish local-scene patchbook
+ # 每个物体的4个面,都放patch,
+ # patchtensor的形状, 由实际的patchsize确定,兼容正方形patch
+ instance_token_list = []
+ patch_4side_book_list = []
+ for i_local in range(scene_length):
+ # 1.把数据拿出来,处理数据
+ data_local = data_in_scene_list_full[i_local]
+ patch_info_local = patch_info_in_scene_list_full[i_local]
+ _, _, _, _, gt_labels_3d = custom_data_work(data_local)
+ # 2.判断有没有gt
+ # 防止出现 no_gt
+ has_gt_flag = (gt_labels_3d.shape[0] != 0) and (type(patch_info_local[0]) != str)
+ if has_gt_flag:
+ scene_name = patch_info_local[0]['scene_info']['scene_name']
+ instance_tokens_i = patch_info_local[0]['objects_info']['instance_tokens']
+ for inst_tk_idx in range(len(instance_tokens_i)):
+ instance_token = instance_tokens_i[inst_tk_idx]
+ if not instance_token in instance_token_list:
+ # 添加patch
+ # 根据最先出现的patch,标注的信息,添加4个patch
+ for j_cam_1frame in range(cam_num):
+ if patch_info_local[j_cam_1frame]['patch_visible_bigger'][inst_tk_idx]:
+ # 如果可以被,当前的camera看到,则添加,否则不添加
+ patch_3d_wh = patch_info_local[j_cam_1frame]['patch_3d_temporal']['patch_3d_wh'][inst_tk_idx]
+ patch_3d_wh_use = patch_3d_wh[area_rate_str]
+
+ patch_4side_ = []
+ for j_side in range(4):
+ patch_w_real, patch_h_real = patch_3d_wh_use[j_side]
+ # 遵循每1m 100pix的密度
+ patch_w_tensor = int(patch_w_real*100)
+ patch_h_tensor = int(patch_h_real*100)
+ patch_jside_ = torch.rand(3, patch_h_tensor, patch_w_tensor).to(device)
+ patch_jside_.requires_grad_()
+ patch_4side_.append(patch_jside_)
+
+ instance_token_list.append(instance_token)
+ patch_4side_book_list.extend(patch_4side_)
+
+ # 为这些patch定义 优化器
+ optimizer = torch.optim.Adam(patch_4side_book_list, lr=optim_lr)
+
+ # 以后每一次取用,都需要,结合instance_token_list获取 token对应的index,再用
+
+
+ for epoch_local in range(max_epoch_local):
+ print('scene_name:', scene_name,'start epoch_local', epoch_local,'training')
+ for i_local in range(scene_length):
+
+ ############## 把数据拿出来,处理数据 Take out the data and process the data
+ data_local = data_in_scene_list_full[i_local]
+ patch_info_local = patch_info_in_scene_list_full[i_local]
+ img_metas, img_path_list, img_org_np, img_processed, gt_labels_3d = custom_data_work(data_local)
+ img_tensor_ncam = custom_img_read_from_img_org(img_org_np, device)
+ last_time = time_counter(last_time, 'data process', time_test_flag)
+
+ ############## apply patch
+ patched_img_tensor_ncam = img_tensor_ncam.clone()
+ # in case of no_gt
+ has_gt_flag = (gt_labels_3d.shape[0] != 0) and (type(patch_info_local[0]) != str)
+ if has_gt_flag:
+ # apply patch
+ for cams_i in range(cam_num):
+ patch_info_in_cami = patch_info_local[cams_i]
+ patched_img_tensor_ncam[cams_i] = apply_patches_by_info_4side(
+ info=patch_info_in_cami,
+ image=patched_img_tensor_ncam[cams_i],
+ instance_token_book=instance_token_list,
+ patch_book_4side=patch_4side_book_list,
+ area_str=area_rate_str,
+ )
+ # patched_img_tensor_ncam[cams_i] = (patched_img_tensor_ncam[cams_i] + patch_4side_book_list[0].mean()/1000).clamp(0,1)
+ else: # no gt,图像不做改变,也不必优化patch
+ continue
+
+ last_time = time_counter(last_time, 'apply patch', time_test_flag)
+
+ ############ resize norm pad
+ image_ready = custom_differentiable_transform(
+ img_tensor_rgb_6chw_0to1=patched_img_tensor_ncam,
+ img_metas=img_metas,
+ )
+ last_time = time_counter(last_time, 'img rsnmpd', time_test_flag)
+
+
+ if image_ready.isnan().sum()>0:
+ print('nan in input image please check!')
+
+ data_i_actual = data_i_list_full[i_local]
+ if data_i_actual < 100 and epoch_local < 3 and i_local < 3:
+ img_diff_print(img_processed, image_ready,'img_processed','image_ready')
+
+
+ data_local = custom_image_data_give(data_local, image_ready)
+ result = model(return_loss=True, **data_local) # 经过model, data中的img会被修改为[6,3,H,W]
+ last_time = time_counter(last_time, 'model forward', time_test_flag)
+ loss = 0
+ for key in result:
+ if 'loss' in key:
+ loss = loss + result[key]
+ advloss = - loss
+ optimizer.zero_grad()
+ advloss.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+
+ last_time = time_counter(last_time, 'model backward', time_test_flag)
+
+ for _patch_i in range(len(patch_4side_book_list)):
+ patch_4side_book_list[_patch_i].data = torch.clamp(patch_4side_book_list[_patch_i], 0, 1)
+ last_time = time_counter(last_time, 'patch clamp', time_test_flag)
+ print('attack step:', i_local,
+ 'model_loss:',round(float(loss),5),
+ )
+ #########################
+ ##### 攻击结束,最后再遍历一遍,粘贴patch,eval
+ print('scene_name:', scene_name,'start eval')
+ prog_bar_local_eval = mmcv.ProgressBar(scene_length)
+ with torch.no_grad():
+ for i_local in range(scene_length):
+
+ ################# 把数据拿出来,处理数据
+ data_local = data_in_scene_list_full[i_local]
+ patch_info_local = patch_info_in_scene_list_full[i_local]
+ img_metas, img_path_list, img_org_np, img_processed, gt_labels_3d = custom_data_work(data_local)
+ img_tensor_ncam = custom_img_read_from_img_org(img_org_np, device)
+
+ ################ 安装patch
+ patched_img_tensor_ncam = img_tensor_ncam.clone()
+ # 防止出现 no_gt
+ has_gt_flag = (gt_labels_3d.shape[0] != 0) and (type(patch_info_local[0]) != str)
+ if has_gt_flag:
+ # apply patch
+ for cams_i in range(cam_num):
+ patch_info_in_cami = patch_info_local[cams_i]
+ patched_img_tensor_ncam[cams_i] = apply_patches_by_info_4side(
+ info=patch_info_in_cami,
+ image=patched_img_tensor_ncam[cams_i],
+ instance_token_book=instance_token_list,
+ patch_book_4side=patch_4side_book_list,
+ area_str=area_rate_str,
+ )
+ else: # 没有gt,图像不做改变,直接eval
+ pass
+
+ ############ resize norm pad
+ image_ready = custom_differentiable_transform(
+ img_tensor_rgb_6chw_0to1=patched_img_tensor_ncam,
+ img_metas=img_metas,
+ )
+ last_time = time_counter(last_time, 'img rsnmpd', time_test_flag)
+ if image_ready.isnan().sum()>0:
+ print('nan in input image please check!')
+ if i_local < 3:
+ img_diff_print(img_processed, image_ready,'img_processed','image_ready')
+
+ data_local = custom_image_data_give(data_local, image_ready)
+ data_local = custom_data_postprocess_eval(data_local)
+ result = model(return_loss=False, rescale=True, **data_local)
+ result = custom_result_postprocess(result)
+ results.extend(result)
+
+ data_i_actual = data_i_list_full[i_local]
+ scattered_result_path = os.path.join(scattered_result_dir, str(data_i_actual)+'.pkl')
+ mmcv.dump(result, scattered_result_path)
+ if data_i_actual < 100:
+ save_image(patched_img_tensor_ncam, os.path.join(scattered_result_dir, str(data_i_actual)+'.png'))
+ prog_bar_local_eval.update()
+ print()
+ return results
+
+
+
diff --git a/mmdet3d/apis_common b/mmdet3d/apis_common
new file mode 120000
index 00000000..727a53aa
--- /dev/null
+++ b/mmdet3d/apis_common
@@ -0,0 +1 @@
+../../apis_common
\ No newline at end of file
diff --git a/mmdet3d/datasets/__init__.py b/mmdet3d/datasets/__init__.py
index cb64c89d..a065e666 100644
--- a/mmdet3d/datasets/__init__.py
+++ b/mmdet3d/datasets/__init__.py
@@ -26,6 +26,8 @@ from .sunrgbd_dataset import SUNRGBDDataset
from .utils import get_loading_pipeline
from .waymo_dataset import WaymoDataset
+from .nuscenes_mono_dataset_nofliter import NuScenesMonoDatasetNoFliter
+
__all__ = [
'KittiDataset', 'KittiMonoDataset', 'build_dataloader', 'DATASETS',
'build_dataset', 'NuScenesDataset', 'NuScenesMonoDataset', 'LyftDataset',
diff --git a/mmdet3d/datasets/nuscenes_mono_dataset_nofliter.py b/mmdet3d/datasets/nuscenes_mono_dataset_nofliter.py
new file mode 100644
index 00000000..f54662ac
--- /dev/null
+++ b/mmdet3d/datasets/nuscenes_mono_dataset_nofliter.py
@@ -0,0 +1,801 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import mmcv
+import numpy as np
+import pyquaternion
+import tempfile
+import torch
+import warnings
+from nuscenes.utils.data_classes import Box as NuScenesBox
+from os import path as osp
+
+from mmdet3d.core import bbox3d2result, box3d_multiclass_nms, xywhr2xyxyr
+from mmdet.datasets import DATASETS, CocoDataset
+from ..core import show_multi_modality_result
+from ..core.bbox import CameraInstance3DBoxes, get_box_type
+from .pipelines import Compose
+from .utils import extract_result_dict, get_loading_pipeline
+
+
[email protected]_module()
+class NuScenesMonoDatasetNoFliter(CocoDataset):
+ r"""Monocular 3D detection on NuScenes Dataset.
+
+ This class serves as the API for experiments on the NuScenes Dataset.
+
+ Please refer to `NuScenes Dataset <https://www.nuscenes.org/download>`_
+ for data downloading.
+
+ Args:
+ ann_file (str): Path of annotation file.
+ data_root (str): Path of dataset root.
+ load_interval (int, optional): Interval of loading the dataset. It is
+ used to uniformly sample the dataset. Defaults to 1.
+ with_velocity (bool, optional): Whether include velocity prediction
+ into the experiments. Defaults to True.
+ modality (dict, optional): Modality to specify the sensor data used
+ as input. Defaults to None.
+ box_type_3d (str, optional): Type of 3D box of this dataset.
+ Based on the `box_type_3d`, the dataset will encapsulate the box
+ to its original format then converted them to `box_type_3d`.
+ Defaults to 'Camera' in this class. Available options includes.
+ - 'LiDAR': Box in LiDAR coordinates.
+ - 'Depth': Box in depth coordinates, usually for indoor dataset.
+ - 'Camera': Box in camera coordinates.
+ eval_version (str, optional): Configuration version of evaluation.
+ Defaults to 'detection_cvpr_2019'.
+ use_valid_flag (bool): Whether to use `use_valid_flag` key in the info
+ file as mask to filter gt_boxes and gt_names. Defaults to False.
+ version (str, optional): Dataset version. Defaults to 'v1.0-trainval'.
+ """
+ CLASSES = ('car', 'truck', 'trailer', 'bus', 'construction_vehicle',
+ 'bicycle', 'motorcycle', 'pedestrian', 'traffic_cone',
+ 'barrier')
+ DefaultAttribute = {
+ 'car': 'vehicle.parked',
+ 'pedestrian': 'pedestrian.moving',
+ 'trailer': 'vehicle.parked',
+ 'truck': 'vehicle.parked',
+ 'bus': 'vehicle.moving',
+ 'motorcycle': 'cycle.without_rider',
+ 'construction_vehicle': 'vehicle.parked',
+ 'bicycle': 'cycle.without_rider',
+ 'barrier': '',
+ 'traffic_cone': '',
+ }
+ # https://github.com/nutonomy/nuscenes-devkit/blob/57889ff20678577025326cfc24e57424a829be0a/python-sdk/nuscenes/eval/detection/evaluate.py#L222 # noqa
+ ErrNameMapping = {
+ 'trans_err': 'mATE',
+ 'scale_err': 'mASE',
+ 'orient_err': 'mAOE',
+ 'vel_err': 'mAVE',
+ 'attr_err': 'mAAE'
+ }
+
+
+ def __repr__(self):
+ """str: Return a string that describes the module."""
+ return f'{self.__class__.__name__}(dataset)'
+
+ def __init__(self,
+ data_root,
+ load_interval=1,
+ with_velocity=True,
+ modality=None,
+ box_type_3d='Camera',
+ eval_version='detection_cvpr_2019',
+ use_valid_flag=False,
+ version='v1.0-trainval',
+ **kwargs):
+ kwargs['test_mode'] = True # test_mode change true to avoid img/gt filtering
+ super().__init__(**kwargs)
+ kwargs['test_mode'] = False # test_mode keep false to load anno
+ self.test_mode = False
+ self.data_root = data_root
+ self.load_interval = load_interval
+ self.with_velocity = with_velocity
+ self.modality = modality
+ self.box_type_3d, self.box_mode_3d = get_box_type(box_type_3d)
+ self.eval_version = eval_version
+ self.use_valid_flag = use_valid_flag
+ self.bbox_code_size = 9
+ self.version = version
+ if self.eval_version is not None:
+ from nuscenes.eval.detection.config import config_factory
+ self.eval_detection_configs = config_factory(self.eval_version)
+ if self.modality is None:
+ self.modality = dict(
+ use_camera=True,
+ use_lidar=False,
+ use_radar=False,
+ use_map=False,
+ use_external=False)
+
+ def pre_pipeline(self, results):
+ """Initialization before data preparation.
+
+ Args:
+ results (dict): Dict before data preprocessing.
+
+ - img_fields (list): Image fields.
+ - bbox3d_fields (list): 3D bounding boxes fields.
+ - pts_mask_fields (list): Mask fields of points.
+ - pts_seg_fields (list): Mask fields of point segments.
+ - bbox_fields (list): Fields of bounding boxes.
+ - mask_fields (list): Fields of masks.
+ - seg_fields (list): Segment fields.
+ - box_type_3d (str): 3D box type.
+ - box_mode_3d (str): 3D box mode.
+ """
+ results['img_prefix'] = self.img_prefix
+ results['seg_prefix'] = self.seg_prefix
+ results['proposal_file'] = self.proposal_file
+ results['img_fields'] = []
+ results['bbox3d_fields'] = []
+ results['pts_mask_fields'] = []
+ results['pts_seg_fields'] = []
+ results['bbox_fields'] = []
+ results['mask_fields'] = []
+ results['seg_fields'] = []
+ results['box_type_3d'] = self.box_type_3d
+ results['box_mode_3d'] = self.box_mode_3d
+
+ def _parse_ann_info(self, img_info, ann_info):
+ """Parse bbox annotation.
+
+ Args:
+ img_info (list[dict]): Image info.
+ ann_info (list[dict]): Annotation info of an image.
+
+ Returns:
+ dict: A dict containing the following keys: bboxes, labels, \
+ gt_bboxes_3d, gt_labels_3d, attr_labels, centers2d, \
+ depths, bboxes_ignore, masks, seg_map
+ """
+ gt_bboxes = []
+ gt_labels = []
+ attr_labels = []
+ gt_bboxes_ignore = []
+ gt_masks_ann = []
+ gt_bboxes_cam3d = []
+ centers2d = []
+ depths = []
+ for i, ann in enumerate(ann_info):
+ if ann.get('ignore', False):
+ continue
+ x1, y1, w, h = ann['bbox']
+ inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0))
+ inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0))
+ if inter_w * inter_h == 0:
+ continue
+ if ann['area'] <= 0 or w < 1 or h < 1:
+ continue
+ if ann['category_id'] not in self.cat_ids:
+ continue
+ bbox = [x1, y1, x1 + w, y1 + h]
+ if ann.get('iscrowd', False):
+ gt_bboxes_ignore.append(bbox)
+ else:
+ gt_bboxes.append(bbox)
+ gt_labels.append(self.cat2label[ann['category_id']])
+ attr_labels.append(ann['attribute_id'])
+ gt_masks_ann.append(ann.get('segmentation', None))
+ # 3D annotations in camera coordinates
+ bbox_cam3d = np.array(ann['bbox_cam3d']).reshape(1, -1)
+ velo_cam3d = np.array(ann['velo_cam3d']).reshape(1, 2)
+ nan_mask = np.isnan(velo_cam3d[:, 0])
+ velo_cam3d[nan_mask] = [0.0, 0.0]
+ bbox_cam3d = np.concatenate([bbox_cam3d, velo_cam3d], axis=-1)
+ gt_bboxes_cam3d.append(bbox_cam3d.squeeze())
+ # 2.5D annotations in camera coordinates
+ center2d = ann['center2d'][:2]
+ depth = ann['center2d'][2]
+ centers2d.append(center2d)
+ depths.append(depth)
+
+ if gt_bboxes:
+ gt_bboxes = np.array(gt_bboxes, dtype=np.float32)
+ gt_labels = np.array(gt_labels, dtype=np.int64)
+ attr_labels = np.array(attr_labels, dtype=np.int64)
+ else:
+ gt_bboxes = np.zeros((0, 4), dtype=np.float32)
+ gt_labels = np.array([], dtype=np.int64)
+ attr_labels = np.array([], dtype=np.int64)
+
+ if gt_bboxes_cam3d:
+ gt_bboxes_cam3d = np.array(gt_bboxes_cam3d, dtype=np.float32)
+ centers2d = np.array(centers2d, dtype=np.float32)
+ depths = np.array(depths, dtype=np.float32)
+ else:
+ gt_bboxes_cam3d = np.zeros((0, self.bbox_code_size),
+ dtype=np.float32)
+ centers2d = np.zeros((0, 2), dtype=np.float32)
+ depths = np.zeros((0), dtype=np.float32)
+
+ gt_bboxes_cam3d = CameraInstance3DBoxes(
+ gt_bboxes_cam3d,
+ box_dim=gt_bboxes_cam3d.shape[-1],
+ origin=(0.5, 0.5, 0.5))
+ gt_labels_3d = copy.deepcopy(gt_labels)
+
+ if gt_bboxes_ignore:
+ gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)
+ else:
+ gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)
+
+ seg_map = img_info['filename'].replace('jpg', 'png')
+
+ ann = dict(
+ bboxes=gt_bboxes,
+ labels=gt_labels,
+ gt_bboxes_3d=gt_bboxes_cam3d,
+ gt_labels_3d=gt_labels_3d,
+ attr_labels=attr_labels,
+ centers2d=centers2d,
+ depths=depths,
+ bboxes_ignore=gt_bboxes_ignore,
+ masks=gt_masks_ann,
+ seg_map=seg_map)
+
+ return ann
+
+ def get_attr_name(self, attr_idx, label_name):
+ """Get attribute from predicted index.
+
+ This is a workaround to predict attribute when the predicted velocity
+ is not reliable. We map the predicted attribute index to the one
+ in the attribute set. If it is consistent with the category, we will
+ keep it. Otherwise, we will use the default attribute.
+
+ Args:
+ attr_idx (int): Attribute index.
+ label_name (str): Predicted category name.
+
+ Returns:
+ str: Predicted attribute name.
+ """
+ # TODO: Simplify the variable name
+ AttrMapping_rev2 = [
+ 'cycle.with_rider', 'cycle.without_rider', 'pedestrian.moving',
+ 'pedestrian.standing', 'pedestrian.sitting_lying_down',
+ 'vehicle.moving', 'vehicle.parked', 'vehicle.stopped', 'None'
+ ]
+ if label_name == 'car' or label_name == 'bus' \
+ or label_name == 'truck' or label_name == 'trailer' \
+ or label_name == 'construction_vehicle':
+ if AttrMapping_rev2[attr_idx] == 'vehicle.moving' or \
+ AttrMapping_rev2[attr_idx] == 'vehicle.parked' or \
+ AttrMapping_rev2[attr_idx] == 'vehicle.stopped':
+ return AttrMapping_rev2[attr_idx]
+ else:
+ return NuScenesMonoDatasetNoFliter.DefaultAttribute[label_name]
+ elif label_name == 'pedestrian':
+ if AttrMapping_rev2[attr_idx] == 'pedestrian.moving' or \
+ AttrMapping_rev2[attr_idx] == 'pedestrian.standing' or \
+ AttrMapping_rev2[attr_idx] == \
+ 'pedestrian.sitting_lying_down':
+ return AttrMapping_rev2[attr_idx]
+ else:
+ return NuScenesMonoDatasetNoFliter.DefaultAttribute[label_name]
+ elif label_name == 'bicycle' or label_name == 'motorcycle':
+ if AttrMapping_rev2[attr_idx] == 'cycle.with_rider' or \
+ AttrMapping_rev2[attr_idx] == 'cycle.without_rider':
+ return AttrMapping_rev2[attr_idx]
+ else:
+ return NuScenesMonoDatasetNoFliter.DefaultAttribute[label_name]
+ else:
+ return NuScenesMonoDatasetNoFliter.DefaultAttribute[label_name]
+
+ def _format_bbox(self, results, jsonfile_prefix=None):
+ """Convert the results to the standard format.
+
+ Args:
+ results (list[dict]): Testing results of the dataset.
+ jsonfile_prefix (str): The prefix of the output jsonfile.
+ You can specify the output directory/filename by
+ modifying the jsonfile_prefix. Default: None.
+
+ Returns:
+ str: Path of the output json file.
+ """
+ nusc_annos = {}
+ mapped_class_names = self.CLASSES
+
+ print('Start to convert detection format...')
+
+ CAM_NUM = 6
+
+ for sample_id, det in enumerate(mmcv.track_iter_progress(results)):
+
+ if sample_id % CAM_NUM == 0:
+ boxes_per_frame = []
+ attrs_per_frame = []
+
+ # need to merge results from images of the same sample
+ annos = []
+ boxes, attrs = output_to_nusc_box(det)
+ sample_token = self.data_infos[sample_id]['token']
+ boxes, attrs = cam_nusc_box_to_global(self.data_infos[sample_id],
+ boxes, attrs,
+ mapped_class_names,
+ self.eval_detection_configs,
+ self.eval_version)
+
+ boxes_per_frame.extend(boxes)
+ attrs_per_frame.extend(attrs)
+ # Remove redundant predictions caused by overlap of images
+ if (sample_id + 1) % CAM_NUM != 0:
+ continue
+ boxes = global_nusc_box_to_cam(
+ self.data_infos[sample_id + 1 - CAM_NUM], boxes_per_frame,
+ mapped_class_names, self.eval_detection_configs,
+ self.eval_version)
+ cam_boxes3d, scores, labels = nusc_box_to_cam_box3d(boxes)
+ # box nms 3d over 6 images in a frame
+ # TODO: move this global setting into config
+ nms_cfg = dict(
+ use_rotate_nms=True,
+ nms_across_levels=False,
+ nms_pre=4096,
+ nms_thr=0.05,
+ score_thr=0.01,
+ min_bbox_size=0,
+ max_per_frame=500)
+ from mmcv import Config
+ nms_cfg = Config(nms_cfg)
+ cam_boxes3d_for_nms = xywhr2xyxyr(cam_boxes3d.bev)
+ boxes3d = cam_boxes3d.tensor
+ # generate attr scores from attr labels
+ attrs = labels.new_tensor([attr for attr in attrs_per_frame])
+ boxes3d, scores, labels, attrs = box3d_multiclass_nms(
+ boxes3d,
+ cam_boxes3d_for_nms,
+ scores,
+ nms_cfg.score_thr,
+ nms_cfg.max_per_frame,
+ nms_cfg,
+ mlvl_attr_scores=attrs)
+ cam_boxes3d = CameraInstance3DBoxes(boxes3d, box_dim=9)
+ det = bbox3d2result(cam_boxes3d, scores, labels, attrs)
+ boxes, attrs = output_to_nusc_box(det)
+ boxes, attrs = cam_nusc_box_to_global(
+ self.data_infos[sample_id + 1 - CAM_NUM], boxes, attrs,
+ mapped_class_names, self.eval_detection_configs,
+ self.eval_version)
+
+ for i, box in enumerate(boxes):
+ name = mapped_class_names[box.label]
+ attr = self.get_attr_name(attrs[i], name)
+ nusc_anno = dict(
+ sample_token=sample_token,
+ translation=box.center.tolist(),
+ size=box.wlh.tolist(),
+ rotation=box.orientation.elements.tolist(),
+ velocity=box.velocity[:2].tolist(),
+ detection_name=name,
+ detection_score=box.score,
+ attribute_name=attr)
+ annos.append(nusc_anno)
+ # other views results of the same frame should be concatenated
+ if sample_token in nusc_annos:
+ nusc_annos[sample_token].extend(annos)
+ else:
+ nusc_annos[sample_token] = annos
+
+ nusc_submissions = {
+ 'meta': self.modality,
+ 'results': nusc_annos,
+ }
+
+ mmcv.mkdir_or_exist(jsonfile_prefix)
+ res_path = osp.join(jsonfile_prefix, 'results_nusc.json')
+ print('Results writes to', res_path)
+ mmcv.dump(nusc_submissions, res_path)
+ return res_path
+
+ def _evaluate_single(self,
+ result_path,
+ logger=None,