-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathevaluator.py
executable file
·146 lines (117 loc) · 4.96 KB
/
evaluator.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
"""
Copyright (c) 2024-present Naver Cloud Corp.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
from torch import nn
from typing import List
import numpy as np
from torch.nn.parallel import DistributedDataParallel as DDP
from zim_anything.build_model import build_zim_model
from zim_anything.predictor import ZimPredictor
from segment_anything import SamPredictor, sam_model_registry
def load_sam_evaluator(config, device):
sam = sam_model_registry[config.network.encoder](checkpoint=config.eval.sam_weights).cuda(device)
sam_evaluator = SamEvaluator(sam, config.eval.prompt_type)
if config.use_ddp:
sam_evaluator = DDP(
sam_evaluator,
device_ids=[config.local_rank],
output_device=config.local_rank,
)
sam_evaluator.eval()
return sam_evaluator
def load_zim_evaluator(config, device):
zim = build_zim_model(config.eval.zim_weights).cuda(device)
zim_evaluator = ZimEvaluator(zim, config.eval.prompt_type)
return zim_evaluator
class SamEvaluator(SamPredictor, nn.Module):
def __init__(
self,
sam_model,
prompt_type: List[str] = None
):
super().__init__(sam_model=sam_model)
self.prompt_type = prompt_type
def forward(self, batched_input, multimask_output: bool = False):
input_images = batched_input["images"]
outputs = {
prompt: {
"masks": [],
} for prompt in self.prompt_type
}
with torch.inference_mode():
for idx, input_image in enumerate(input_images):
input_image = input_image.cpu().numpy().astype(np.uint8)
self.set_image(image=input_image)
for prompt in self.prompt_type:
point_coords = None
point_labels = None
bbox = None
if prompt == "point":
points = batched_input["points"][idx]
points = points[points[:, 2] >= 0] # remove points whose label=-1
point_coords = points[:, :2].cpu().numpy()
point_labels = points[:, 2].cpu().numpy()
elif prompt == "bbox":
bbox = batched_input["bboxes"][idx]
bbox = bbox.unsqueeze(0).cpu().numpy()
masks, _, _ = self.predict(
point_coords=point_coords,
point_labels=point_labels,
box=bbox,
multimask_output=False,
)
masks = torch.from_numpy(masks).float().unsqueeze(0).to(self.device)
outputs[prompt]["masks"].append(masks)
# Concat through batch dimension
for prompt in self.prompt_type:
for k, v in outputs[prompt].items():
if len(v) > 0:
outputs[prompt][k] = torch.cat(v, dim=0)
return outputs
class ZimEvaluator(ZimPredictor, nn.Module):
def __init__(
self,
model,
prompt_type: List[str] = None
) -> None:
super().__init__(model=model)
self.prompt_type = prompt_type
def forward(self, batched_input, multimask_output: bool = False):
input_images = batched_input["images"]
outputs = {
prompt: {
"masks": [],
} for prompt in self.prompt_type
}
with torch.inference_mode():
for idx, input_image in enumerate(input_images):
input_image = input_image.cpu().numpy().astype(np.uint8)
self.set_image(image=input_image)
for prompt in self.prompt_type:
point_coords = None
point_labels = None
bbox = None
if prompt == "point":
points = batched_input["points"][idx]
points = points[points[:, 2] >= 0] # remove points whose label=-1
point_coords = points[:, :2].cpu().numpy()
point_labels = points[:, 2].cpu().numpy()
elif prompt == "bbox":
bbox = batched_input["bboxes"][idx]
bbox = bbox.cpu().numpy()
masks, _, _ = self.predict(
point_coords=point_coords,
point_labels=point_labels,
box=bbox,
multimask_output=False,
)
masks = torch.from_numpy(masks).float().unsqueeze(0).to(self.device)
outputs[prompt]["masks"].append(masks)
for prompt in self.prompt_type:
for k, v in outputs[prompt].items():
if len(v) > 0:
outputs[prompt][k] = torch.cat(v, dim=0)
return outputs