-
Notifications
You must be signed in to change notification settings - Fork 1
/
sam_4_bbox.py
245 lines (212 loc) · 10.8 KB
/
sam_4_bbox.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
import argparse
import sys
import monai
import numpy as np
from torch import optim
from segment_anything import sam_model_registry
from segment_anything.utils.transforms import ResizeLongestSide
from utils.prostate import Prostate
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
import os
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from torchvision.utils import save_image
import pdb
from utils.utils import dice_score
from models.models import CorruptionEncoder, ImageDecoder
import random
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def test(args, validLoader, sam_model):
sam_trans = ResizeLongestSide(args.input_size)
alldice = []
dataid = 0
for i in range(5):
if dataid == args.domain:
dataid+=1
test_dice = []
tqdmtest = tqdm(validLoader[i])
sam_model.eval()
for iteration, (image, mask, bbox, id) in enumerate(tqdmtest):
box = sam_trans.apply_boxes(bbox, (512, 512))
box_tensor = torch.as_tensor(box, dtype=torch.float).cuda()
bz, channels, height, width = image.shape
row_num = 1024 // height
col_num = 1024 // width
patch_num = row_num * col_num
mbz = bz // patch_num
merged_images = torch.zeros(mbz, channels, 1024, 1024)
merged_masks = torch.zeros(mbz, 1, 1024, 1024)
for idx in range(mbz):
for i in range(row_num):
for j in range(col_num):
bz_idx = idx * patch_num + i * col_num + j
merged_images[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = image[bz_idx, :, :, :]
merged_masks[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = mask[bz_idx, :, :, :]
box_tensor[bz_idx][0] += height * i
box_tensor[bz_idx][1] += width * j
box_tensor[bz_idx][2] += height * i
box_tensor[bz_idx][3] += width * j
merged_images = merged_images.cuda()
merged_masks = merged_masks.cuda()
with torch.no_grad():
image_embeddings = sam_model.image_encoder(merged_images) # (B,256,64,64)
predicted_masks = torch.zeros_like(merged_masks)
for idx in range(mbz):
cur_embedding = image_embeddings[idx]
cur_boxes = box_tensor[idx*patch_num:(idx+1)*patch_num]
with torch.no_grad():
sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(
points=None,
boxes=cur_boxes,
masks=None,
)
low_res_predictions, _ = sam_model.mask_decoder(
image_embeddings=cur_embedding.unsqueeze(0), # (B, 256, 64, 64)
image_pe=sam_model.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64)
sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256)
dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64)
multimask_output=False,
)
mask_predictions= sam_model.postprocess_masks(
low_res_predictions,
input_size=[1024,1024],
original_size=[1024,1024],
)
for i in range(row_num):
for j in range(col_num):
predicted_masks[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = mask_predictions[i * col_num + j, :, i*height:(i+1)*height, j*width:(j+1)*width]
predicted_masks = torch.sigmoid(predicted_masks) > args.thresh
dice = dice_score(predicted_masks, merged_masks)
test_dice.append(dice.detach().item())
# Update the progress bar
tqdmtest.set_description(f"Testing on domain{dataid}")
tqdmtest.set_postfix(eval_dice=np.mean(test_dice))
tqdmtest.update()
dataid+=1
alldice.append(np.mean(test_dice))
print('Average Dice:', np.mean(alldice))
print(np.mean(alldice), alldice)
return np.mean(alldice), alldice
def main():
parser = argparse.ArgumentParser(description='SAM4Med')
parser.add_argument('--input_size', type=int, default=512, help='the image size')
parser.add_argument('--vit_name', type=str, default='vit_b', help='vit model of sam')
parser.add_argument('--sam_ckpt', type=str, default='SAM/sam_vit_b_01ec64.pth',
help='Pretrained checkpoint of SAM')
parser.add_argument('--batch_size', type=int, default=16, help='batch_size per gpu')
parser.add_argument('--gpu', type=str, default='0', help='gpu device')
parser.add_argument('--lr', type=float, default=0.0001, help='learning rate')
parser.add_argument('--epoch', type=int, default=200, help='training epoch')
parser.add_argument('--data_path', type=str, default='data/prostate', help='path to dataset')
parser.add_argument('--domain', type=int, default=5, help='domain id')
parser.add_argument('--thresh', type=float, default=0.5)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu # device = torch.device('cuda:' + args.gpu)
trainset = Prostate(base_dir=args.data_path, split='train', domain_idx=args.domain)
trainLoader = DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True,drop_last=True)
testsets = []
testLoaders = []
for i in range(6):
if i!= args.domain:
testsets.append(Prostate(base_dir=args.data_path, split='train', domain_idx=i))
testLoaders.append(DataLoader(testsets[-1], batch_size=4, shuffle=False, num_workers=4, pin_memory=True,drop_last = True))
sam_model = sam_model_registry[args.vit_name](checkpoint=args.sam_ckpt).cuda()
seg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction="mean")
sam_trans = ResizeLongestSide(args.input_size)
optimizer = optim.Adam(sam_model.parameters(), lr=args.lr, weight_decay=0.001)
#scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", patience=3, factor=0.01, verbose=True)
writer = SummaryWriter()
sam_model.train()
# test(args, testLoaders, sam_model)
maxdice, maxalldice = 0 , None
max_epoch = 0
for epoch in range(args.epoch):
epoch_loss = []
epoch_dice = []
tqdmbar = tqdm(trainLoader)
for iteration, (image, mask, bbox, id) in enumerate(tqdmbar):
box = sam_trans.apply_boxes(bbox, (512, 512))
box_tensor = torch.as_tensor(box, dtype=torch.float).cuda()
bz, channels, height, width = image.shape
row_num = 1024 // height
col_num = 1024 // width
patch_num = row_num * col_num
mbz = bz // patch_num
merged_images = torch.zeros(mbz, channels, 1024, 1024)
merged_masks = torch.zeros(mbz, 1, 1024, 1024)
for idx in range(mbz):
for i in range(row_num):
for j in range(col_num):
bz_idx = idx * patch_num + i * col_num + j
merged_images[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = image[bz_idx, :, :, :]
merged_masks[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = mask[bz_idx, :, :, :]
box_tensor[bz_idx][0] += height * i
box_tensor[bz_idx][1] += width * j
box_tensor[bz_idx][2] += height * i
box_tensor[bz_idx][3] += width * j
merged_images = merged_images.cuda()
merged_masks = merged_masks.cuda()
with torch.no_grad():
image_embeddings = sam_model.image_encoder(merged_images) # (B,256,64,64)
predicted_masks = torch.zeros_like(merged_masks)
for idx in range(mbz):
cur_embedding = image_embeddings[idx]
cur_boxes = box_tensor[idx*patch_num:(idx+1)*patch_num]
with torch.no_grad():
sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(
points=None,
boxes=cur_boxes,
masks=None,
)
low_res_predictions, _ = sam_model.mask_decoder(
image_embeddings=cur_embedding.unsqueeze(0), # (B, 256, 64, 64)
image_pe=sam_model.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64)
sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256)
dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64)
multimask_output=False,
)
mask_predictions= sam_model.postprocess_masks(
low_res_predictions,
input_size=[1024,1024],
original_size=[1024,1024],
)
for i in range(row_num):
for j in range(col_num):
predicted_masks[idx, :, i*height:(i+1)*height, j*width:(j+1)*width] = mask_predictions[i * col_num + j, :, i*height:(i+1)*height, j*width:(j+1)*width]
loss_seg = seg_loss(predicted_masks, merged_masks)
predicted_masks = torch.sigmoid(predicted_masks) > args.thresh
dice = dice_score(predicted_masks, merged_masks)
loss = loss_seg
epoch_loss.append(loss.detach().item())
epoch_dice.append(dice.detach().item())
# start optimizing the model
optimizer.zero_grad()
loss.backward()
optimizer.step()
tqdmbar.set_description(f"Epoch:{epoch + 1}/{args.epoch}")
tqdmbar.set_postfix(loss=np.mean(epoch_loss), dice=np.mean(epoch_dice), seg=loss_seg.detach().item())
tqdmbar.update()
if (epoch + 1) % 10 == 0:
val_dice, alldice = test(args, testLoaders, sam_model)
if val_dice > maxdice:
maxdice = val_dice
maxalldice = alldice
max_epoch = epoch + 1
writer.add_scalars("loss",{"train": round(np.mean(epoch_loss), 4),},epoch,)
writer.add_scalars("dice",{"train": round(np.mean(epoch_dice), 4),"val": round(val_dice, 4),},epoch,)
print('Final result. Best Dice:', maxdice, maxalldice)
with open(f'4_bbox_results.txt','a') as f:
f.write(f'full bbox trained on domain {args.domain}\n')
f.write(f'max dice {str(maxdice)}, epoch {max_epoch}\n')
f.write(str(maxalldice) + '\n\n')
if __name__ == '__main__':
main()