forked from aleemsidra/SaLIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsam_clip.py
366 lines (258 loc) · 13.7 KB
/
sam_clip.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
import cv2
import random
import json
import time
import torch
import numpy as np
import clip
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor
from segment_anything.utils.transforms import ResizeLongestSide
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import to_pil_image
import wandb
from IPython import embed
from tqdm import tqdm
from datetime import datetime
from utils.utils import log_images_to_wandb, log_images_to_wandb_batch, dice_coeff
def hyper_params_tuning(sam, dataset,prompt_mode,resize_transform, prompts,clip_model, preprocess, config, mode):
# ----- Hyper-params tuning -----
random.seed(time.time())
random_indices = random.sample(range(len(dataset)), 5)
print("Random Indices:", random_indices)
points_per_side_range = [4, 8, 16]
pred_iou_thresh_range = [0.2, 0.5, 0.8]
stability_score_thresh_range = [0.2, 0.5, 0.8]
crop_nms_thresh_range = [0.7, 0.8,0.9]
box_nms_thresh_range = [0.7, 0.8, 0.9]
best_score = -1
best_params = None
num_iterations = 5
area_list = [20000, 40000, 50000]
avg_dice = []
best_score = -1
best_params = None
for _ in tqdm(range(num_iterations), desc="Iteration: Hyper-params tuning", unit="iteration"):
random.shuffle(points_per_side_range)
random.shuffle(stability_score_thresh_range)
random.shuffle(pred_iou_thresh_range)
random.shuffle(area_list)
points_per_side = random.choice(points_per_side_range)
stability_score_thresh = random.choice(stability_score_thresh_range)
pred_iou_thresh = random.choice(pred_iou_thresh_range)
crop_nms_thresh = random.choice(crop_nms_thresh_range)
box_nms_thresh = random.choice(box_nms_thresh_range)
area = random.choice(area_list)
print(f"hyper-params: points_per_side: {points_per_side}, stability_score_thresh: {stability_score_thresh},pred_iou_thresh: {pred_iou_thresh} ")
avg_dice_coeff = 0
dice_scores =[]
for idx in random_indices:
mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side=points_per_side,
points_per_batch=256,
pred_iou_thresh=pred_iou_thresh,
stability_score_thresh=stability_score_thresh,
box_nms_thresh=box_nms_thresh,
crop_n_layers=1,
crop_n_points_downscale_factor=2,
crop_nms_thresh=crop_nms_thresh,
min_mask_region_area=5000,
)
image, gt, _, _, _ = dataset[idx]
masks = mask_generator.generate(image)
masks = [mask for mask in masks if mask["area"] < area] # area filtering
img_crops = get_crops(image, masks, prompt_mode)
max_indices, _ = retrieve_relevant_crop(img_crops, prompts, clip_model, preprocess, config)
bboxes, _ , _ = get_sam_prompts(image, masks,max_indices , img_crops)
preds = sam_predicton(sam, image, resize_transform, bboxes, config, mode)
dice_score, _ = dice_coeff(gt, preds)
print("dice:", dice_score)
dice_scores.append(dice_score)
avg_dice_coeff = np.mean(dice_scores)
if avg_dice_coeff > best_score:
best_score = avg_dice_coeff
print(f"best dice: {best_score}")
best_params = {
'points_per_side': points_per_side,
'pred_iou_thresh': pred_iou_thresh,
'stability_score_thresh': stability_score_thresh,
"box_nms_thresh": box_nms_thresh,
"crop_nms_thresh" : crop_nms_thresh,
"area": area
}
print("Best Parameters:", best_params)
mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side= best_params["points_per_side"],
points_per_batch= 128,
pred_iou_thresh= best_params["pred_iou_thresh"],
stability_score_thresh= best_params["stability_score_thresh"],
box_nms_thresh= best_params["box_nms_thresh"],
crop_n_layers=1,
crop_n_points_downscale_factor=2,
crop_nms_thresh=best_params["crop_nms_thresh"],
min_mask_region_area=200,
)
return mask_generator, best_params["area"]
def prepare_image(image, transform, device):
image = transform.apply_image(image)
image = torch.as_tensor(image)
return image.permute(2, 0, 1).contiguous()
def get_crops(image, masks, prompt_mode):
imgs_bboxes = []
indices_to_remove = []
for i, mask in enumerate(masks):
box = mask["bbox"]
x1 = box[0]
y1 = box[1]
x2 = box[0] + box[2]
y2 = box[1] + box[3]
if x2 > x1 and y2 > y1: # Check if the bounding box has non-zero dimensions
if prompt_mode == "crops":
# crops
seg_mask = np.array([mask["segmentation"], mask["segmentation"], mask["segmentation"]]).transpose(1,2,0)
cropped_image = np.multiply(image, seg_mask).astype("int")[int(y1):int(y2), int(x1):int(x2)]
imgs_bboxes.append(cropped_image)
elif prompt_mode == "crop_expand":
#crops
seg_mask = np.array([mask["segmentation"], mask["segmentation"], mask["segmentation"]]).transpose(1,2,0)
# Expand bounding box coordinates
x1_expanded = max(0, x1 - 10)
y1_expanded = max(0, y1 - 10)
x2_expanded = min(image.shape[1], x2 + 10)
y2_expanded = min(image.shape[0], y2 + 10)
if x2_expanded > x1_expanded and y2_expanded > y1_expanded:
cropped_image = image[y1_expanded:y2_expanded, x1_expanded:x2_expanded]
imgs_bboxes.append(cropped_image)
elif prompt_mode == "bbox":
# bbox on the image around crop area
img_bbox = cv2.rectangle(image.copy(), (int(x1), int(y1)), (int(x2), int(y2)), ( 255, 0, 0), 5)
imgs_bboxes.append(img_bbox)
elif prompt_mode == "reverse_box_mask":
# highlight roi and gray out the rest
res = image.copy()
box_mask = np.zeros(res.shape, dtype=np.uint8)
box_mask = cv2.rectangle(box_mask, (x1, y1), (x2, y2),
color=(255, 255, 255), thickness=-1)[:, :, 0]
overlay = res.copy()
overlay[box_mask == 0] = np.array((124, 116, 104))
alpha = 0.5 # Transparency factor.
res = cv2.addWeighted(overlay, alpha, res, 1 - alpha, 0.0)
imgs_bboxes.append(res)
elif prompt_mode == "contour":
#contour around the mask and overlay on the image
res = image.copy()
mask = mask["segmentation"]
contours, hierarchy = cv2.findContours(mask.astype(
np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
res = cv2.drawContours(res, contours, contourIdx=-1,
color=(255, 0, 0), thickness=3)#, gave 60.04
imgs_bboxes.append(res)
else:
print("Skipping zero-sized bounding box.")
indices_to_remove.append(i)
for index in sorted(indices_to_remove, reverse=True):
del masks[index]
return imgs_bboxes
def retrieve_relevant_crop(crops, class_names, model, preprocess, config):
crops_uint8 = [image.astype(np.uint8) for image in crops]
pil_images = []
for image in crops_uint8:
if image.shape[0] > 0 and image.shape[1] > 0:
pil_image = Image.fromarray(image)
pil_images.append(pil_image)
preprocessed_images = [preprocess(image).to("cuda") for image in pil_images]
stacked_images = torch.stack(preprocessed_images)
similarity_scores = {class_name: [] for class_name in class_names}
with torch.no_grad():
image_features = model.encode_image(stacked_images)
image_features /= image_features.norm(dim=-1, keepdim=True)
for class_name in class_names:
class_descriptions = class_names[class_name]
class_text_features = [model.encode_text(clip.tokenize(description).to("cuda")) for description in class_descriptions]
mean_text_feature = torch.mean(torch.stack(class_text_features), dim=0)
mean_text_feature /= mean_text_feature.norm(dim=-1, keepdim=True)
similarity_score = 100. * image_features @ mean_text_feature.T
similarity_scores[class_name] = similarity_score.squeeze().tolist()
if config.dataset == "cxr":
max_indices = {key: sorted(range(len(similarity_scores[key])), key=lambda i: similarity_scores[key][i], reverse=True)[:2] for key in similarity_scores} # 2 lungs so getting top 2
else:
max_indices = {key: similarity_scores[key].index(max(similarity_scores[key])) for key in similarity_scores}
return max_indices, similarity_scores
def get_sam_prompts(image, masks, max_indices, imgs_bboxes):
# ------ bbox prompts cordinates relevant to ROI for SAM------
bboxes = []
relevant_crop = []
img_with_bboxes = []
for key, indices in max_indices.items():
for index, value in enumerate(indices):
bbox = masks[value]["bbox"]
bbox = np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]])
if index == 0:
img = image.copy()
img_with_bboxes = cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (255, 0, 0), 5)
bboxes.append(bbox)
relevant_crop.append(imgs_bboxes[value])
bboxes = np.array(bboxes)
return bboxes, relevant_crop, img_with_bboxes
def sam_predicton(sam, image, resize_transform, bboxes, config, mode):
# ------ SAM format ------
batched_input = [{
'image': prepare_image(image, resize_transform, "cuda").to("cuda"),
'boxes': resize_transform.apply_boxes_torch(torch.from_numpy( np.array(bboxes)), image.shape[:2]).to("cuda"),
'original_size': image.shape[:2]
}]
preds = sam(batched_input, multimask_output=False)
binary_masks = torch.sigmoid(preds) > 0.5
binary_masks = binary_masks.squeeze().cpu().numpy()
if config.dataset == "cxr" and mode == "sam_clip" or mode == "sam_prompted":
binary_masks = np.bitwise_or(binary_masks[0], binary_masks[1])
return binary_masks
def get_eval(dataset, sam, config, suffix, wandb_mode, prompt_mode, mode):
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
wandb_run = wandb.init( project='SAM', entity='liumingsi915', name = config['model_name'] + "_" + suffix +"_"+ folder_time, mode = wandb_mode)
# ----- loading the models -----
clip_model, preprocess = clip.load("ViT-L/14", device="cuda")
sam_checkpoint = config.sam_ckpt
sam = sam_model_registry[config.model_type](checkpoint=sam_checkpoint)
sam.to("cuda")
resize_transform = ResizeLongestSide(sam.image_encoder.img_size)
# ----- CLIP Prompts -----
with open(config.clip_prompts, "r") as file:
prompts = json.load(file)
dice_scores = []
mask_generator, area = hyper_params_tuning(sam, dataset, prompt_mode,resize_transform, prompts,clip_model, preprocess, config, mode)
# ----- Inference -----
with torch.no_grad():
for idx in tqdm(range(len(dataset)), desc= f"Processing images", unit= "image"):
image, gt, _, bounding_boxes, file_name = dataset[idx]
if mode == "sam_clip":
masks = mask_generator.generate(image)
masks = [mask for mask in masks if mask["area"] < area] # area filtering based on area value from hyper-params tuning
img_crops = get_crops(image, masks, prompt_mode)
max_indices, scores = retrieve_relevant_crop(img_crops, prompts, clip_model, preprocess, config)
# ----- logging crops to wandb -----
#log_images_to_wandb_batch(scores, img_crops, file_name)
# ------ bbox cordinates relevant to crop ------
bboxes, relevant_crop, img_with_bboxes = get_sam_prompts(image, masks,max_indices , img_crops)
elif mode == "sam_prompted":
# bounding box prompt from ground truth
bboxes = bounding_boxes
preds = sam_predicton(sam, image, resize_transform, bboxes, config, mode)
dice_score, miou = dice_coeff(gt, preds)
print("dice:", dice_score, "miou:", miou)
dice_scores.append((dice_score, miou))
# with open(f"{config.dataset}_{mode}_dice_scores_.txt", "a") as file:
# file.write(f"File Name: {file_name}, Dice: {dice_score}, MIoU: {miou}\n")
# ----- logging images to wandb -----
if wandb_mode == "online":
if mode == "sam_clip":
log_images_to_wandb(image, gt, masks,preds, dice_score, file_name, relevant_crop, img_with_bboxes) # sam_clip
else:
log_images_to_wandb(image, gt, masks, preds, dice_score, file_name, None, None ) # prompted/unprompted SAM
dice_scores = np.array(dice_scores)
average_dice_score = np.mean(dice_scores[:, 0])
miou = np.mean(dice_scores[:, 1])
print("Average Dice Score:", average_dice_score, "mIoU:", miou)
return average_dice_score