-
Notifications
You must be signed in to change notification settings - Fork 0
/
object_memory.py
1880 lines (1500 loc) · 72.5 KB
/
object_memory.py
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, sys, time
print("Starting imports")
start_time = time.time()
sys.path.append(os.path.join(os.getcwd(), "Grounded-Segment-Anything"))
sys.path.append(os.path.join(os.getcwd(), "Grounded-Segment-Anything", "GroundingDINO"))
sys.path.append(os.path.join(os.getcwd(), "Grounded-Segment-Anything", "segment_anything"))
sys.path.append(os.path.join(os.getcwd(), "GroundingDINO"))
sys.path.append(os.path.join(os.getcwd(), "recognize-anything"))
sys.path.append(os.path.join(os.getcwd(), "Objectron"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "config"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "datasets"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "loss"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "model"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "processor"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "solver"))
sys.path.append(os.path.join(os.getcwd(), "FourDNet-wrapper", "utils"))
import os, sys, time
import tyro
import argparse
import copy
from IPython.display import display
from PIL import Image, ImageDraw, ImageFont
from torchvision.ops import box_convert
from ram.models import ram
from ram import inference_ram
from ram import get_transform as get_transform_ram
import GroundingDINO.groundingdino.datasets.transforms as T
from GroundingDINO.groundingdino.models import build_model
from GroundingDINO.groundingdino.util import box_ops
from GroundingDINO.groundingdino.util.slconfig import SLConfig
from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
from GroundingDINO.groundingdino.util.inference import annotate, load_image, predict
import supervision as sv
from segment_anything import build_sam, SamPredictor
import cv2
import numpy as np
import matplotlib.pyplot as plt
import PIL
import requests
import torch
from io import BytesIO
from diffusers import StableDiffusionInpaintPipeline
import open3d as o3d
from huggingface_hub import hf_hub_download
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from torchvision.transforms import (
CenterCrop,
Compose,
Normalize,
RandomHorizontalFlip,
RandomResizedCrop,
Resize,
ToTensor,
ToPILImage
)
from tqdm import tqdm
from transformers import ViTConfig, ViTModel, ViTForImageClassification
from transformers import AutoImageProcessor, CLIPVisionModel
from peft import LoraConfig, get_peft_model
from GroundingDINO.groundingdino.util.inference import annotate as gd_annotate
from GroundingDINO.groundingdino.util.inference import load_image as gd_load_image
from GroundingDINO.groundingdino.util.inference import predict as gd_predict
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation
from numpy import arctan2
import torch.nn.functional as F
import json
from dataclasses import dataclass, field
from jcbb import JCBB
from fpfh.fpfh_register import register_point_clouds, evaluate_transform
from similarity_volume import *
from simple_semantic_icp import semantic_icp
from objectron.dataset import box, iou
# copy pasted from test_heatmap
import os
import torch
from config import cfg
import argparse
# from datasets import make_dataloader
from model import make_model
# from processor import do_inference
# from utils.logger import setup_logger
import matplotlib.pyplot as plt
import PIL
from PIL import Image
import torchvision.transforms as T
import numpy as np
import cv2
import os
import shutil
import os.path as osp
from tqdm import tqdm
import torch.nn.functional as F
import pickle
from dataclasses import dataclass
import tyro
end_time = time.time()
print(f"Imports completed in {end_time - start_time} seconds")
"""
#################
Object Detection Classes
#################
"""
class LoraRevolver:
"""
Loads a base ViT and a set of LoRa configs, allows loading and swapping between them.
"""
def __init__(self, device, model_checkpoint="google/vit-base-patch16-224-in21k"):
"""
Initializes the LoraRevolver object.
Parameters:
- device (str): Device to be used for compute.
- model_checkpoint (str): Checkpoint for the base ViT model.
"""
self.device = device
# self.base_model will be augmented with a saved set of lora_weights
# self.lora_model is the augmented model (NOTE)
self.base_model = ViTModel.from_pretrained(
model_checkpoint,
ignore_mismatched_sizes=True,
).to(self.device)
self.lora_model = self.base_model
# image preprocessors the ViT needs
self.image_processor = AutoImageProcessor.from_pretrained(model_checkpoint, use_fast=True)
self.normalize = Normalize(mean=self.image_processor.image_mean, std=self.image_processor.image_std)
self.train_transforms = Compose(
[
RandomResizedCrop(self.image_processor.size["height"]),
RandomHorizontalFlip(),
ToTensor(),
self.normalize,
]
)
self.test_transforms = Compose(
[
Resize(self.image_processor.size["height"]),
CenterCrop(self.image_processor.size["height"]),
ToTensor(),
self.normalize,
]
)
# stored lora_configs, ready to be swapped in
# only expects store lora_checkpoints.pt objects created by this class
self.ckpt_library = {}
def load_lora_ckpt_from_file(self, config_path, name):
"""
Load a LoRa config from a saved file.
Parameters:
- config_path (str): Path to the LoRa config file.
- name (str): Name to associate with the loaded config.
"""
ckpt = torch.load(config_path)
try:
self.ckpt_library[str(name)] = ckpt
del self.lora_model
self.lora_model = get_peft_model(self.base_model,
ckpt["lora_config"]).to(self.device)
self.lora_model.load_state_dict(ckpt["lora_state_dict"], strict=False)
except:
print("Lora checkpoint invalid")
raise IndexError
def encode_image(self, imgs):
"""
Use the current LoRa model to encode a batch of images.
Parameters:
- imgs (list): List of images to encode.
Returns:
- emb (torch.Tensor): Encoded embeddings for the input images.
"""
with torch.no_grad():
if isinstance(imgs[0], np.ndarray):
img_batch = torch.stack([Compose([ToPILImage(),
self.test_transforms])(i) for i in imgs])
else:
img_batch = torch.stack([self.test_transforms(i) for i in imgs])
# if len(img.shape) == 3:
# img = img.unsqueeze(0) # if the image is unbatched, batch it
emb = self.lora_model(img_batch.to(self.device), output_hidden_states=True).last_hidden_state[:,0,:]
return emb
def train_current_lora_model(self):
"""
Train the current LoRa model.
"""
pass
def save_lora_ckpt(self):
"""
Save the current LoRa model checkpoint.
"""
pass
class ObjectFinder:
"""
Class that detects objects through segmentation.
"""
def __init__(self, device, box_threshold=0.35, text_threshold=0.55):
"""
Initializes the ObjectFinder object.
Parameters:
- device (str): Device to be used for compute.
- box_threshold (float): Threshold for bounding box detection.
- text_threshold (float): Threshold for text detection.
"""
self.device = device
self.box_threshold = box_threshold
self.text_threshold = text_threshold
def _load_models(self, ram_pretrained_path):
"""
Load RAM and Grounding Dino models.
Parameters:
- ram_pretrained_path (str): Path to the pretrained RAM model.
"""
# ram
self.ram_model = ram(pretrained=ram_pretrained_path, image_size=384, vit='swin_l')
self.ram_model.eval()
self.ram_model.to(self.device)
self.ram_transform = get_transform_ram(image_size=384)
# grounding dino
ckpt_repo_id = "ShilongLiu/GroundingDINO"
ckpt_filenmae = "groundingdino_swinb_cogcoor.pth"
ckpt_config_filename = "GroundingDINO_SwinB.cfg.py"
cache_config_file = hf_hub_download(repo_id=ckpt_repo_id, filename=ckpt_config_filename)
args = SLConfig.fromfile(cache_config_file)
args.device = self.device
self.groundingdino_model = build_model(args)
cache_file = hf_hub_download(repo_id=ckpt_repo_id, filename=ckpt_filenmae)
checkpoint = torch.load(cache_file, map_location=self.device)
log = self.groundingdino_model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
print("Model loaded from {} \n => {}".format(cache_file, log))
self.groundingdino_model.eval()
def _load_sam(self, sam_checkpoint_path):
"""
Load SAM model from checkpoint.
Parameters:
- sam_checkpoint_path (str): Path to the SAM model checkpoint.
"""
self.sam_predictor = SamPredictor(build_sam(checkpoint=sam_checkpoint_path).to(self.device).eval())
# self.sam_predictor.to(self.device)
# self.sam_predictor.eval()
print("SAM loaded")
def _getIoU(self, rect1, rect2):
"""
Calculate the intersection over union (IoU) between two rectangles.
Parameters:
- rect1 (tuple): Coordinates of the first rectangle (x, y, width, height).
- rect2 (tuple): Coordinates of the second rectangle (x, y, width, height).
Returns:
- percent_overlap (float): Percentage of overlap between the rectangles.
"""
area_rect1 = rect1[2]*rect1[3]
area_rect2 = rect2[2]*rect2[3]
overlap_top_left = (max(rect1[0], rect2[0]), max(rect1[1], rect2[1]))
overlap_bottom_right = (min(rect1[0] + rect1[2], rect2[0] + rect2[2]), min(rect1[1] + rect1[3], rect2[1] + rect2[3]))
if (overlap_bottom_right[0] <= overlap_top_left[0]) or (overlap_bottom_right[1] <= overlap_top_left[1]):
return 0.0 # No overlap, return 0% overlap
# Calculate the area of the overlap rectangle
overlap_area = abs((overlap_bottom_right[0] - overlap_top_left[0]) * (overlap_bottom_right[1] - overlap_top_left[1]))
percent_overlap = (overlap_area / min(area_rect1, area_rect2))
return percent_overlap
def _compSize(self, rect1, rect2):
"""
Compare the sizes of two rectangles.
Parameters:
- rect1 (tuple): Coordinates of the first rectangle (x, y, width, height).
- rect2 (tuple): Coordinates of the second rectangle (x, y, width, height).
Returns:
- diff (float): Size difference between the rectangles.
"""
area_rect1 = rect1[2]*rect1[3]
area_rect2 = rect2[2]*rect2[3]
diff = min(area_rect1, area_rect2)/max(area_rect1, area_rect2)
return diff
def getBoxes(self, image, text_prompt, show=False, intersection_threshold=0.7, size_threshold=0.75):
"""
Given a phrase, filter and get all boxes and phrases.
Parameters:
- image (np.ndarray): Input image.
- text_prompt (str): Phrase for object detection.
- show (bool): Whether to display intermediate results.
- intersection_threshold (float): Threshold for box intersection.
- size_threshold (float): Threshold for box size difference.
Returns:
- boxes (torch.Tensor): Detected bounding boxes.
- phrases (list): List of detected phrases.
"""
keywords = [k.strip() for k in text_prompt.split('.')]
with torch.no_grad():
boxes = []
phrases = []
unique_boxes_num = 0
for i, word in enumerate(keywords):
# af, detected, detected_phrases = self._detect(image, image_source=image_source, text_prompt=str(word))
detected, _, detected_phrases = gd_predict(
model=self.groundingdino_model,
image=image,
caption=str(word),
box_threshold=self.box_threshold,
text_threshold=self.text_threshold
)
# print("FIND: ", word, detected_phrases, detected)
if show:
print(i)
unique_enough = True
if detected != None and len(detected) != 0:
if unique_boxes_num == 0:
for box in detected:
boxes.append(box)
phrases.append(word)
unique_boxes_num += 1
else:
# print("boxes: ", boxes)
for box in detected:
unique_enough = True
# if show:
# print("detected: ", detected)
for prev in boxes[:unique_boxes_num]:
iou = self._getIoU(box, prev)
diff = self._compSize(box, prev)
if (iou > intersection_threshold and diff > size_threshold):
# bounding box is not unique enough to be added
unique_enough = False
# if show:
# print("failed")
# break
if unique_enough:
boxes.append(box)
phrases.append(word)
unique_boxes_num += 1
try:
return torch.stack(boxes), phrases
except:
return None, None
def segment(self, image, boxes):
"""
Segment objects in the image based on provided bounding boxes.
Parameters:
- image (np.ndarray): Input image.
- boxes (torch.Tensor): Bounding boxes for object segmentation.
Returns:
- boxes_xyxy (torch.Tensor): Transformed bounding boxes.
- masks (torch.Tensor): Segmentation masks.
"""
with torch.no_grad():
self.sam_predictor.set_image(image)
H, W, _ = image.shape
boxes_xyxy = box_ops.box_cxcywh_to_xyxy(boxes) * torch.Tensor([W, H, W, H])
transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_xyxy.to(self.device), image.shape[:2])
masks, _, _ = self.sam_predictor.predict_torch(
point_coords = None,
point_labels = None,
boxes = transformed_boxes,
multimask_output = False,
)
return boxes_xyxy, masks
def find(self, image_path=None, caption=None, consider_floor=False):
"""
Find and ground objects in the given image.
Parameters:
- image_path (str): Path to the input image.
- caption (str): Caption for object detection.
- consider_floor: search for the floor as an object
Returns:
- grounded_objects (list): List of grounded object images.
- boxes (torch.Tensor): Detected bounding boxes.
- masks (torch.Tensor): Segmentation masks.
- phrases (list): List of detected phrases.
"""
if type(image_path) == None:
raise NotImplementedError
else:
image_source, image = gd_load_image(image_path)
# get object names
if caption == None:
img_ram = self.ram_transform(PIL.Image.fromarray(image_source)).unsqueeze(0).to(self.device)
caption = inference_ram(img_ram, self.ram_model)[0].split("|")
words_to_ignore = [
"living room",
"ceiling",
"room",
"curtain",
"den",
"window",
"floor",
"wall",
"red",
"yellow",
"white",
"blue",
"green",
"brown", # new additions start in the next line
"corridor",
"image",
"picture frame",
"mat",
"wood floor",
"shadow",
"hardwood",
"plywood",
"waiting room",
"lead to",
"belly",
"person",
"chest",
"black",
"accident",
"act",
"doorway",
"illustration",
"animal",
"mountain",
"table top", # since we don't want a flat object as an instance
"pen",
"pencil",
"corner",
"notepad",
"flower",
"man",
"pad",
"lead",
"ramp",
"plank",
"scale",
"beam",
"pink",
"tie",
"crack",
"mirror",
"square",
"rectangle",
"woman",
"tree",
"umbrella",
"hat",
"salon",
"beach",
"open",
"closet",
"blanket",
"circle",
"furniture",
"balustrade",
"cube",
"dress",
"ladder",
"briefcase",
"marble",
"pillar",
"dark",
"sea",
"door"
]
sub_phrases_to_ignore = [
"room",
"floor",
"wall",
"frame",
"image",
"building",
"ceiling"
"lead",
"paint",
"shade",
"snow",
"rain",
"cloud",
"frost",
"fog",
"sky",
"carpet",
"view",
"scene",
"mat",
"window",
"vase",
"bureau",
"door",
"tile",
"blind"
]
def check_whether_in_sub_phrases(text):
for sub_phrase in sub_phrases_to_ignore:
if sub_phrase in text:
return True
return False
filtered_caption = ""
if consider_floor:
filtered_caption += "floor . "
print("caption before filtering: ", caption)
for c in caption:
if c.strip() in words_to_ignore:
continue
if check_whether_in_sub_phrases(c.strip()):
continue
else:
filtered_caption += c
filtered_caption += " . "
filtered_caption = filtered_caption[:-2]
print("caption post ram and filtering: ", filtered_caption)
# ground them, get associated phrases
cxcy_boxes, phrases = self.getBoxes(image, filtered_caption)
# no objects considered
if cxcy_boxes is None:
return None, None, None, None
boxes, masks = self.segment(image_source, cxcy_boxes)
# ground objects
grounded_objects = [image_source[int(bb[1]):int(bb[3]),
int(bb[0]):int(bb[2]), :] for bb in boxes]
return grounded_objects, boxes, masks, phrases
def _show_detections(self, image_path=None, caption=None):
"""
Display object detections on the given image.
Parameters:
- image_path (str): Path to the input image.
- caption (str): Caption for object detection.
"""
if type(image_path) == None:
raise NotImplementedError
else:
image_source, image = gd_load_image(image_path)
## TODO implement RAM
if caption==None:
caption = "sofa . chair . table"
Image.fromarray(image_source)
b, l, p = gd_predict(model=self.groundingdino_model,
image=image, caption=caption,
box_threshold=0.35,
text_threshold=0.55)
af = gd_annotate(image_source=image_source, boxes=b, logits=l, phrases=p)[...,::-1]
Image.fromarray(af)
plt.imshow(af)
# TODO determine whether outliers need to be filtered here
def getDepth(self, depth_image_path, masks, f=300):
"""
Returns a 3D point cloud corresponding to each object based on depth information.
Parameters:
- depth_image_path (str): Path to the depth image file.
- masks (torch.Tensor): Binary segmentation masks for each object.
- f (float): Focal length for depth-to-distance conversion.
Returns:
- all_pointclouds (list): List of 3D point clouds for each segmented object.
"""
if depth_image_path is None:
raise NotImplementedError
else:
depth_image = np.load(depth_image_path)
w, h = depth_image.shape
num_objs = masks.shape[0]
stacked_depth = np.tile(depth_image, (num_objs, 1, 1)) # Get all centroids/point clouds together
stacked_depth[masks.squeeze(dim=1).cpu() == False] = 0 # Remove the depth channel from the masks
horizontal_distance = np.tile(np.linspace(-h/2, h/2, h, dtype=np.float32), (num_objs, w, 1))
vertical_distance = np.tile(np.linspace(w/2, -w/2, w, dtype=np.float32).reshape(-1, 1), (num_objs, 1, h))
X = horizontal_distance * stacked_depth / f
Y = vertical_distance * stacked_depth / f
Z = stacked_depth
# Combine calculated X, Y, Z points
all_pointclouds = np.stack([X, Y, Z], 1).reshape((num_objs, 3, -1))
# Filter out [0,0,0]
all_pointclouds = [pcd[:, pcd[2, :] != 0] for pcd in all_pointclouds]
return all_pointclouds
"""
#################
Utility Functions
#################
"""
class QuaternionOps:
@staticmethod
def quaternion_multiply(q1, q2):
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2
z = w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2
return np.array([w, x, y, z])
@staticmethod
def quaternion_conjugate(q):
w, x, y, z = q
return np.array([w, -x, -y, -z])
# https://math.stackexchange.com/a/3573308
@staticmethod
def quaternion_error(q1, q2): # returns orientation angle between the two
q_del = QuaternionOps.quaternion_multiply(QuaternionOps.quaternion_conjugate(q1), q2)
q_del_other_way = QuaternionOps.quaternion_multiply(QuaternionOps.quaternion_conjugate(q1), -q2)
return min(np.abs(arctan2(np.linalg.norm(q_del[1:]), q_del[0])),
np.abs(arctan2(np.linalg.norm(q_del_other_way[1:]), q_del_other_way[0])))
def transform_pcd_to_global_frame(pcd, pose):
"""
Transforms a point cloud into the global frame based on a given pose.
Parameters:
- pcd (numpy.ndarray): 3D point cloud represented as a 3xN array.
- pose (numpy.ndarray): Pose of the camera frame with respect to the world frame
represented as [x, y, z, qw, qx, qy, qz].
Returns:
- transformed_pcd (numpy.ndarray): Transformed point cloud in the global frame.
"""
t = pose[:3]
q = pose[3:]
q /= np.linalg.norm(q)
R = Rotation.from_quat(q).as_matrix()
transformed_pcd = R @ pcd
transformed_pcd += t.reshape(3, 1)
return transformed_pcd
def calculate_3d_IoU(pcd1, pcd2):
"""
Calculates the 3D Intersection over Union (IoU) between two 3D point clouds.
Parameters:
- pcd1 (numpy.ndarray): First 3D point cloud represented as a 3xN array.
- pcd2 (numpy.ndarray): Second 3D point cloud represented as a 3xN array.
Returns:
- IoU (float): 3D Intersection over Union between the two point clouds.
"""
try:
bb1_min = pcd1.min(axis=-1)
bb1_max = pcd1.max(axis=-1)
bb2_min = pcd2.min(axis=-1)
bb2_max = pcd2.max(axis=-1)
overlap_min_corner = np.stack([bb1_min, bb2_min], axis=0).max(axis=0)
overlap_max_corner = np.stack([bb1_max, bb2_max], axis=0).min(axis=0)
except:
return 0
if (overlap_min_corner > overlap_max_corner).any():
return 0
else:
v = overlap_max_corner - overlap_min_corner
overlap_volume = v[0] * v[1] * v[2]
bb1 = bb1_max - bb1_min
bb2 = bb2_max - bb2_min
v1 = bb1[0] * bb1[1] * bb1[2]
v2 = bb2[0] * bb2[1] * bb2[2]
IoU = overlap_volume / (v1 + v2 - overlap_volume)
return IoU
def calculate_strict_overlap(pcd1, pcd2):
"""
Calculates the strict overlap between two 3D point clouds.
Parameters:
- pcd1 (numpy.ndarray): First 3D point cloud represented as a 3xN array.
- pcd2 (numpy.ndarray): Second 3D point cloud represented as a 3xN array.
Returns:
- overlap (float): Strict overlap between the two point clouds.
"""
try:
bb1_min = pcd1.min(axis=-1)
bb1_max = pcd1.max(axis=-1)
bb2_min = pcd2.min(axis=-1)
bb2_max = pcd2.max(axis=-1)
overlap_min_corner = np.stack([bb1_min, bb2_min], axis=0).max(axis=0)
overlap_max_corner = np.stack([bb1_max, bb2_max], axis=0).min(axis=0)
except:
return 0
if (overlap_min_corner > overlap_max_corner).any():
return 0
else:
v = overlap_max_corner - overlap_min_corner
overlap_volume = v[0] * v[1] * v[2]
bb1 = bb1_max - bb1_min
bb2 = bb2_max - bb2_min
v1 = bb1[0] * bb1[1] * bb1[2]
v2 = bb2[0] * bb2[1] * bb2[2]
overlap = overlap_volume / min(v1, v2)
return overlap
def calculate_obj_aligned_3d_IoU(pcd1, pcd2):
"""
Calculates the 3D Intersection over Union (IoU) between two 3D point clouds. Using Objectrons algorithm
Uses object aligned bounding boxes isntead of axis aligned
Parameters:
- pcd1 (numpy.ndarray): First 3D point cloud represented as a 3xN array.
- pcd2 (numpy.ndarray): Second 3D point cloud represented as a 3xN array.
Returns:
- IoU (float): 3D Intersection over Union between the two point clouds.
"""
def conv_to_objectron_ordering(v):
v = sorted(v, key=lambda v: v[2])
v = sorted(v, key=lambda v: v[1])
v = sorted(v, key=lambda v: v[0])
return v
try:
bb1 = o3d.geometry.OrientedBoundingBox.create_from_points(
points=o3d.utility.Vector3dVector(pcd1.T) #, robust=True
)
bb2 = o3d.geometry.OrientedBoundingBox.create_from_points(
points=o3d.utility.Vector3dVector(pcd2.T) #, robust=True
)
except:
return 0
bb1_vertices = np.zeros((9,3), dtype=np.float32)
bb1_vertices[0, :] = bb1.get_center()
bb1c = np.array(bb1.get_box_points())
bb1_vertices[1:,:] = conv_to_objectron_ordering(bb1c)
bb2_vertices = np.zeros((9,3), dtype=np.float32)
bb2_vertices[0, :] = bb2.get_center()
bb2c = np.array(bb2.get_box_points())
bb2_vertices[1:,:] = conv_to_objectron_ordering(bb2c)
w1 = box.Box(vertices=bb1_vertices)
w2 = box.Box(vertices=bb2_vertices)
loss = iou.IoU(w1, w2)
try:
iou3d = loss.iou()
except:
iou3d = 0.
return iou3d
"""
#################
Object Memory Classes
#################
"""
class ObjectInfo:
"""
Bundles together object information for distinct objects.
Attributes:
- id (int): Object ID.
- names (list): List of object names.
- embeddings (list): List of embeddings associated with the object.
- pcd (numpy.ndarray): Point cloud data for the object.
- mean_emb (numpy.ndarray): Mean embedding of the object.
- centroid (numpy.ndarray): Centroid of the object in 3D space.
Methods:
- addInfo(name, embedding, pcd): Adds information for the object, including name, embedding, and point cloud data.
- computeMeans(): Computes the mean embedding and centroid for the object.
- __repr__(): Returns a string representation of the object information.
"""
def __init__(self, id, name, emb, pcd):
"""
Initializes ObjectInfo with the given ID, name, embedding, and point cloud data.
Parameters:
- id (int): Object ID.
- name (str): Object name.
- emb (numpy.ndarray): Object embedding.
- pcd (numpy.ndarray): Object point cloud data.
"""
self.id = id
self.names = [name]
self.embeddings = [emb]
self.pcd = pcd
self.mean_emb = None
self.centroid = None
def downsample(self, voxel_size, use_external_mesh):
temp_pc = o3d.geometry.PointCloud()
temp_pc.points = o3d.utility.Vector3dVector(self.pcd.T)
if use_external_mesh:
alpha = 0.03
mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_alpha_shape(temp_pc.points, alpha)
mesh.compute_vertex_normals()
o3d.visualization.draw_geometries([mesh])
temp_pc.points = mesh.sample_points_uniformly(number_of_points=50000)
temp_pc = temp_pc.voxel_down_sample(voxel_size=voxel_size)
self.pcd = np.asarray(temp_pc.points).T
def __add__(self, info):
self.names += info.names
self.embeddings += info.embeddings
self.pcd = np.concatenate([self.pcd, info.pcd], axis=-1)
return self
def addInfo(self, name, embedding, pcd, align=True, max_iteration=30, max_correspondence_distance=0.01):
"""
Adds information for the object, including name, embedding, and point cloud data.
Added point cloud data is aligned with a fine-grained point-to-point ICP if the align flag is true
Added point cloud data is aligned with a fine-grained point-to-point ICP if the align flag is true
Parameters:
- name (str): Object name to be added.
- embedding (numpy.ndarray): Object embedding to be added.
- pcd (numpy.ndarray): Object point cloud data to be added
- align (bool): Should the new point information be ailgned to the existing points.
- pcd (numpy.ndarray): Object point cloud data to be added
- align (bool): Should the new point information be ailgned to the existing points.
"""
if name not in self.names:
self.names.append(name)
self.embeddings.append(embedding)
if not align:
self.pcd = np.concatenate([self.pcd, pcd], axis=-1)
else:
memPcd = o3d.geometry.PointCloud()
newPcd = o3d.geometry.PointCloud()
memPcd.points = o3d.utility.Vector3dVector(self.pcd.T)
newPcd.points = o3d.utility.Vector3dVector(pcd.T)
# Perform ICP registration
reg_p2p = o3d.pipelines.registration.registration_icp(
source=newPcd,
target=memPcd,
max_correspondence_distance=max_correspondence_distance, # Adjust as needed based on your data
estimation_method=o3d.pipelines.registration.TransformationEstimationPointToPoint(),
criteria=o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration=30)
)
raise NotImplementedError
def computeMeans(self):
"""
Computes the mean embedding and centroid for the object.
"""
# TODO messy, clean this up
# self.mean_emb = np.mean(np.asarray(
# [e.cpu() for e in self.embeddings]), axis=0)
self.mean_emb = np.mean(np.array(self.embeddings), axis=0)
self.centroid = np.mean(self.pcd, axis=-1)
def __repr__(self):
"""
Returns a string representation of the object information.
"""
return(f"ID: %d | Names: [%s] | Num embs: %d | Pcd size: " % \
(self.id, " ,".join(self.names), len(self.embeddings)) + str(self.pcd.shape))
class ObjectMemory:
def __init__(self, device, ram_pretrained_path, sam_checkpoint_path, lora_path=None):
"""
Initializes the ObjectMemory instance.
Parameters:
- device (str): Device to be used for computation (e.g., 'cuda' or 'cpu').
- ram_pretrained_path (str): Path to the pre-trained RAM model checkpoint.
- sam_checkpoint_path (str): Path to the SAM model checkpoint.
- lora_path (str, optional): Path to the LoRA checkpoint file. Default is None.
"""
self.device = device
self.objectFinder = ObjectFinder(self.device)
self.loraModule = LoraRevolver(self.device)
self.objectFinder._load_models(ram_pretrained_path)
self.objectFinder._load_sam(sam_checkpoint_path)
if lora_path != None:
self.loraModule.load_lora_ckpt_from_file(lora_path, "5x40")
self.num_objects_stored = 0
self.memory = [] # store ObjectInfo classes here
def view_memory(self):
"""
Prints information about the objects stored in memory.
"""
print("Objects stored in memory:")