-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredictor.py
More file actions
138 lines (125 loc) · 3.98 KB
/
Copy pathpredictor.py
File metadata and controls
138 lines (125 loc) · 3.98 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
from segment_anything import sam_model_registry, SamPredictor
from .preprocessing import *
from .bbox import *
import torch
def sample_slices(
mask,
num_slices = 10,
seed = 1337
):
np.random.seed(seed)
# Filter out slices w/o segmentation
slice_sum = mask.reshape(-1, mask.shape[-1]).sum(axis=0)
idx = np.where(slice_sum > 0)[0]
# Weigh slices by occurence of segmentation
proba = slice_sum[idx]/slice_sum[idx].sum()
# Randomly select slices
if idx.shape[0] < num_slices:
try:
slices = np.random.choice(idx, idx.shape[0], p=proba, replace=False)
except:
slices = np.random.choice(idx, idx.shape[0], replace=False)
else:
try:
slices = np.random.choice(idx, num_slices, p=proba, replace=False)
except:
slices = np.random.choice(idx, num_slices, replace=False)
return slices
# TODO: Too many points affect performance, use Kmeans to cluster groups of annotations into fewer (for curatation at scale!)
def sample_points(
mask,
num_points = 10,
seed = 1337
):
np.random.seed(seed)
# Determine points corresponding to mask
points = np.array(np.where(mask > 0)).transpose()[:,[1,0]]
# Randomly select points
if points.shape[0] < num_points:
points = points[np.random.randint(0, points.shape[0], points.shape[0])]
else:
points = points[np.random.randint(0, points.shape[0], num_points)]
return points
class Predictor:
def __init__(self, model='MedSAM', device='cuda'):
if model == 'SAM-vit_h' or model == 'SAM':
model = sam_model_registry['vit_h'](checkpoint='checkpoints/sam_vit_h_4b8939.pth')
elif model == 'SAM-vit_b':
model = sam_model_registry['vit_b'](checkpoint='checkpoints/sam_vit_b_01ec64.pth')
elif model == 'SAM-vit_l':
model = sam_model_registry['vit_l'](checkpoint='checkpoints/sam_vit_l_0b3195.pth')
elif model == 'MedSAM-vit_b' or model == 'MedSAM':
model = sam_model_registry['vit_b'](checkpoint='checkpoints/medsam_vit_b.pth')
else:
raise ValueError('Whoops!')
model.to(device=device)
self.predictor = SamPredictor(model)
def set_image(self, img):
self.predictor.set_image(img)
def set_torch_image(self, img):
self.predictor.set_torch_image(img)
def predict(self, *args, **kwargs):
return self.predictor.predict(*args, **kwargs)
def predict_torch(self, *args, **kwargs):
return self.predictor.predict_torch(*args, **kwargs)
def get_image_embdding(self):
return self.predictor.get_image_embedding()
@property
def device(self):
return self.predictor.device
def reset_image(self):
self.predictor.reset_image()
def generate_mask_from_points(
self,
points,
targets
):
masks, scores, _ = self.predictor.predict(
points,
targets,
multimask_output = True
)
return masks[np.argmax(scores)]
def generate_mask_from_bbox(
self,
bbox
):
# Prepare bounding boxes
batched_bbox = preprocess_bbox(bbox)
# Determine number of batches by number of bboxes
n_steps = batched_bbox.shape[0]
masks = []
for i in range(n_steps):
box = batched_bbox[i]
mask_i, scores_i, _ = self.predictor.predict(
box = box,
multimask_output = True
)
masks += [mask_i[np.argmax(scores_i)]]
masks = np.sum(masks, axis=0)
masks[masks > 1] = 1
return masks.astype(bool)
def generate_mask_from_points_bbox(
self,
points,
targets,
bbox
):
# Prepare bounding boxes
batched_bbox = preprocess_bbox(bbox)
# Determine number of batches by number of bboxes
n_steps = batched_bbox.shape[0]
masks = []
for i in range(n_steps):
box = batched_bbox[i]
points_in_box, targets_in_box = points_inside_bbox(points, targets, box)
mask_i, scores_i, _ = self.predictor.predict(
points_in_box,
targets_in_box,
box = box,
multimask_output = True
)
masks += [mask_i[np.argmax(scores_i)]]
masks = np.sum(masks, axis=0)
masks[masks > 1] = 1
return masks.astype(bool)