-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheval_ref.py
More file actions
247 lines (204 loc) · 10.2 KB
/
Copy patheval_ref.py
File metadata and controls
247 lines (204 loc) · 10.2 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
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
import os
import re
import json
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
from uni_med.common.config import Config
from uni_med.common.eval_utils import prepare_texts, init_model, eval_parser, computeIoU
from uni_med.conversation.conversation import Conversation
from uni_med.datasets.datasets.slake_dataset import ReferSlakeDataset_Eval
from uni_med.datasets.datasets.sa_med_dataset import ReferSAMedDataset_Eval
def list_of_str(arg):
return list(map(str, arg.split(',')))
parser = eval_parser()
parser.add_argument("--dataset", type=list_of_str, default='ref_slake', help="dataset to evaluate")
parser.add_argument("--res", type=float, default=100.0, help="resolution used in refcoco")
args = parser.parse_args()
cfg = Config(args)
model, vis_processor, text_processor = init_model(args)
bos_token = model.llm_tokenizer.bos_token
conv_temp = Conversation(
system="",
roles=(f"{bos_token}[INST] ", " [/INST]"),
messages=[],
sep="",
offset=2,
).copy()
model.eval()
cfg_save_path = cfg.run_cfg.save_path
save_path = os.path.join(cfg_save_path, str(args.dataset[0]))
res=args.res
if 'ref_slake' in args.dataset:
data_dir = cfg.evaluation_datasets_cfg["ref_slake"]["data_dir"]
batch_size = cfg.evaluation_datasets_cfg["ref_slake"]["batch_size"]
max_new_tokens = cfg.evaluation_datasets_cfg["ref_slake"]["max_new_tokens"]
data = ReferSlakeDataset_Eval(vis_processor, text_processor, data_dir)
eval_dataloader = DataLoader(data, batch_size=batch_size, shuffle=False)
uni_med_predict = []
iou_scores = []
for images, questions, img_ids, bboxes, image_sizes in tqdm(eval_dataloader):
texts = prepare_texts(questions, conv_temp) # warp the texts with conversation template
answers = model.generate(images, texts, max_new_tokens=max_new_tokens, do_sample=False, task='refer')
for answer, question, img_id, bbox, image_size in zip(answers, questions, img_ids, bboxes, image_sizes):
result = dict()
gt_bbox = [0,0,0,0]
bbox = bbox.tolist()
gt_bbox[0] = bbox[0]
gt_bbox[1] = bbox[1]
gt_bbox[2] = bbox[0] + bbox[2]
gt_bbox[3] = bbox[1] + bbox[3]
answer = answer.replace("<unk>","").replace(" ","").strip()
pattern = r'\{<\d{1,3}><\d{1,3}><\d{1,3}><\d{1,3}>\}'
if re.match(pattern, answer):
integers = re.findall(r'\d+', answer)
pred_bbox = [int(num) for num in integers][:4]
width = image_size.tolist()[0]
height = image_size.tolist()[1]
pred_bbox[0] = pred_bbox[0] / res * width
pred_bbox[1] = pred_bbox[1] / res * height
pred_bbox[2] = pred_bbox[2] / res * width
pred_bbox[3] = pred_bbox[3] / res * height
iou_score = computeIoU(pred_bbox, gt_bbox)
iou_scores.append(iou_score)
result['pred_bbox'] = pred_bbox
result['iou_score'] = iou_score
else:
iou_scores.append(0)
result['pred_bbox'] = f'Unable to match: {answer}'
result['iou_score'] = 0
result['image_id'] = img_id
result['item'] = question.replace('[refer] give me the location of','').strip()
result['gt_bbox'] = gt_bbox
# print(result)
uni_med_predict.append(result)
# save the result
if not os.path.exists(save_path):
os.makedirs(save_path, exist_ok=True)
file_save_path= os.path.join(save_path, "ref_slake.json")
with open(file_save_path,'w') as f:
json.dump(uni_med_predict, f)
print("save the result to {}".format(file_save_path))
iou_scores = np.array(iou_scores)
metrics = {'miou': iou_scores.mean(), 'acc': (iou_scores>0.5).mean()}
metric_save_path = os.path.join(save_path, "metric.json")
with open(metric_save_path, 'w') as f:
json.dump(metrics, f, sort_keys=True)
print("save the metrics to {}".format(metric_save_path))
print("metrics: {}".format(metrics))
if 'ref_sa_med' in args.dataset:
image_dir = cfg.evaluation_datasets_cfg["ref_sa_med"]["image_dir"]
region_dir = cfg.evaluation_datasets_cfg["ref_sa_med"]["region_dir"]
batch_size = cfg.evaluation_datasets_cfg["ref_sa_med"]["batch_size"]
max_new_tokens = cfg.evaluation_datasets_cfg["ref_sa_med"]["max_new_tokens"]
data = ReferSAMedDataset_Eval(vis_processor, text_processor, image_dir, region_dir)
eval_dataloader = DataLoader(data, batch_size=batch_size, shuffle=False)
uni_med_predict = []
iou_scores = []
for images, questions, img_ids, bboxes, image_sizes in tqdm(eval_dataloader):
texts = prepare_texts(questions, conv_temp) # warp the texts with conversation template
answers = model.generate(images, texts, max_new_tokens=max_new_tokens, do_sample=False, task='refer')
for answer, question, img_id, bbox, image_size in zip(answers, questions, img_ids, bboxes, image_sizes):
result = dict()
gt_bbox = [0,0,0,0]
bbox = bbox.tolist()
gt_bbox[0] = bbox[0]
gt_bbox[1] = bbox[1]
gt_bbox[2] = bbox[0] + bbox[2]
gt_bbox[3] = bbox[1] + bbox[3]
answer = answer.replace("<unk>","").replace(" ","").strip()
pattern = r'\{<\d{1,3}><\d{1,3}><\d{1,3}><\d{1,3}>\}'
if re.match(pattern, answer):
integers = re.findall(r'\d+', answer)
pred_bbox = [int(num) for num in integers][:4]
width = image_size.tolist()[0]
height = image_size.tolist()[1]
pred_bbox[0] = pred_bbox[0] / res * width
pred_bbox[1] = pred_bbox[1] / res * height
pred_bbox[2] = pred_bbox[2] / res * width
pred_bbox[3] = pred_bbox[3] / res * height
iou_score = computeIoU(pred_bbox, gt_bbox)
iou_scores.append(iou_score)
result['pred_bbox'] = pred_bbox
result['iou_score'] = iou_score
else:
iou_scores.append(0)
result['pred_bbox'] = f'Unable to match: {answer}'
result['iou_score'] = 0
result['image_id'] = img_id
result['item'] = question.replace('[refer] give me the location of','').strip()
result['gt_bbox'] = gt_bbox
# print(result)
uni_med_predict.append(result)
# save the result
if not os.path.exists(save_path):
os.makedirs(save_path, exist_ok=True)
file_save_path= os.path.join(save_path, "ref_sa_med.json")
with open(file_save_path,'w') as f:
json.dump(uni_med_predict, f)
print("save the result to {}".format(file_save_path))
iou_scores = np.array(iou_scores)
metrics = {'miou': iou_scores.mean(), 'acc': (iou_scores>0.5).mean()}
metric_save_path = os.path.join(save_path, "metric.json")
with open(metric_save_path, 'w') as f:
json.dump(metrics, f, sort_keys=True)
print("save the metrics to {}".format(metric_save_path))
print("metrics: {}".format(metrics))
if 'ref_sa_med' in args.dataset:
image_dir = cfg.evaluation_datasets_cfg["ref_sa_med"]["image_dir"]
region_dir = cfg.evaluation_datasets_cfg["ref_sa_med"]["region_dir"]
batch_size = cfg.evaluation_datasets_cfg["ref_sa_med"]["batch_size"]
max_new_tokens = cfg.evaluation_datasets_cfg["ref_sa_med"]["max_new_tokens"]
data = ReferSAMedDataset_Eval(vis_processor, text_processor, image_dir, region_dir)
eval_dataloader = DataLoader(data, batch_size=batch_size, shuffle=False)
uni_med_predict = []
iou_scores = []
for images, questions, img_ids, bboxes, image_sizes in tqdm(eval_dataloader):
texts = prepare_texts(questions, conv_temp) # warp the texts with conversation template
answers = model.generate(images, texts, max_new_tokens=max_new_tokens, do_sample=False, task='refer')
for answer, question, img_id, bbox, image_size in zip(answers, questions, img_ids, bboxes, image_sizes):
result = dict()
gt_bbox = [0,0,0,0]
bbox = bbox.tolist()
gt_bbox[0] = bbox[0]
gt_bbox[1] = bbox[1]
gt_bbox[2] = bbox[0] + bbox[2]
gt_bbox[3] = bbox[1] + bbox[3]
answer = answer.replace("<unk>","").replace(" ","").strip()
pattern = r'\{<\d{1,3}><\d{1,3}><\d{1,3}><\d{1,3}>\}'
if re.match(pattern, answer):
integers = re.findall(r'\d+', answer)
pred_bbox = [int(num) for num in integers][:4]
width = image_size.tolist()[0]
height = image_size.tolist()[1]
pred_bbox[0] = pred_bbox[0] / res * width
pred_bbox[1] = pred_bbox[1] / res * height
pred_bbox[2] = pred_bbox[2] / res * width
pred_bbox[3] = pred_bbox[3] / res * height
iou_score = computeIoU(pred_bbox, gt_bbox)
iou_scores.append(iou_score)
result['pred_bbox'] = pred_bbox
result['iou_score'] = iou_score
else:
iou_scores.append(0)
result['pred_bbox'] = f'Unable to match: {answer}'
result['iou_score'] = 0
result['image_id'] = img_id
result['item'] = question.replace('[refer] give me the location of','').strip()
result['gt_bbox'] = gt_bbox
# print(result)
uni_med_predict.append(result)
# save the result
if not os.path.exists(save_path):
os.makedirs(save_path, exist_ok=True)
file_save_path= os.path.join(save_path, "ref_sa_med.json")
with open(file_save_path,'w') as f:
json.dump(uni_med_predict, f)
print("save the result to {}".format(file_save_path))
iou_scores = np.array(iou_scores)
metrics = {'miou': iou_scores.mean(), 'acc': (iou_scores>0.5).mean()}
metric_save_path = os.path.join(save_path, "metric.json")
with open(metric_save_path, 'w') as f:
json.dump(metrics, f, sort_keys=True)
print("save the metrics to {}".format(metric_save_path))
print("metrics: {}".format(metrics))