-
Notifications
You must be signed in to change notification settings - Fork 53
/
mask_predictor.py
199 lines (157 loc) · 6.81 KB
/
mask_predictor.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
from typing import Any, Dict, List, Optional
import cv2
import numpy as np
import torch
from tqdm import tqdm
from metaseg import SamAutomaticMaskGenerator, SamPredictor, sam_model_registry
from metaseg.utils import download_model, load_image, load_video
class SegAutoMaskPredictor:
def __init__(self):
self.model = None
self.device = "cuda" if torch.cuda.is_available() else "cpu"
def load_model(self, model_type):
if self.model is None:
self.model_path = download_model(model_type)
self.model = sam_model_registry[model_type](checkpoint=self.model_path)
self.model.to(device=self.device)
return self.model
def predict(self, frame, points_per_side, points_per_batch, min_area):
frame = load_image(frame)
mask_generator = SamAutomaticMaskGenerator(
self.model, points_per_side=points_per_side, points_per_batch=points_per_batch, min_mask_region_area=min_area
)
masks = mask_generator.generate(frame)
return frame, masks
def save_image(self, source, model_type, points_per_side, points_per_batch, min_area):
read_image = load_image(source)
image, anns = self.predict(read_image, model_type, points_per_side, points_per_batch, min_area)
if len(anns) == 0:
return
sorted_anns = sorted(anns, key=(lambda x: x["area"]), reverse=True)
mask_image = np.zeros((anns[0]["segmentation"].shape[0], anns[0]["segmentation"].shape[1], 3), dtype=np.uint8)
colors = np.random.randint(0, 255, size=(256, 3), dtype=np.uint8)
for i, ann in enumerate(sorted_anns):
m = ann["segmentation"]
img = np.ones((m.shape[0], m.shape[1], 3), dtype=np.uint8)
color = colors[i % 256]
for i in range(3):
img[:, :, 0] = color[0]
img[:, :, 1] = color[1]
img[:, :, 2] = color[2]
img = cv2.bitwise_and(img, img, mask=m.astype(np.uint8))
img = cv2.addWeighted(img, 0.35, np.zeros_like(img), 0.65, 0)
mask_image = cv2.add(mask_image, img)
combined_mask = cv2.add(image, mask_image)
cv2.imwrite("output.jpg", combined_mask)
return "output.jpg"
def save_video(self, source, model_type, points_per_side, points_per_batch, min_area):
cap, out = load_video(source)
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
colors = np.random.randint(0, 255, size=(256, 3), dtype=np.uint8)
for _ in tqdm(range(length)):
ret, frame = cap.read()
if not ret:
break
image, anns = self.predict(frame, model_type, points_per_side, points_per_batch, min_area)
if len(anns) == 0:
continue
sorted_anns = sorted(anns, key=(lambda x: x["area"]), reverse=True)
mask_image = np.zeros(
(anns[0]["segmentation"].shape[0], anns[0]["segmentation"].shape[1], 3), dtype=np.uint8
)
for i, ann in enumerate(sorted_anns):
m = ann["segmentation"]
color = colors[i % 256] # Her nesne için farklı bir renk kullan
img = np.zeros((m.shape[0], m.shape[1], 3), dtype=np.uint8)
img[:, :, 0] = color[0]
img[:, :, 1] = color[1]
img[:, :, 2] = color[2]
img = cv2.bitwise_and(img, img, mask=m.astype(np.uint8))
img = cv2.addWeighted(img, 0.35, np.zeros_like(img), 0.65, 0)
mask_image = cv2.add(mask_image, img)
combined_mask = cv2.add(frame, mask_image)
out.write(combined_mask)
out.release()
cap.release()
cv2.destroyAllWindows()
return "output.mp4"
class SegManualMaskPredictor:
def __init__(self):
self.model = None
self.device = "cuda" if torch.cuda.is_available() else "cpu"
def load_model(self, model_type):
if self.model is None:
self.model_path = download_model(model_type)
self.model = sam_model_registry[model_type](checkpoint=self.model_path)
self.model.to(device=self.device)
return self.model
def load_mask(self, mask, random_color):
if random_color:
color = np.random.rand(3) * 255
else:
color = np.array([100, 50, 0])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
mask_image = mask_image.astype(np.uint8)
return mask_image
def load_box(self, box, image):
x, y, w, h = int(box[0]), int(box[1]), int(box[2]), int(box[3])
cv2.rectangle(image, (x, y), (w, h), (0, 255, 0), 2)
return image
def multi_boxes(self, boxes, predictor, image):
input_boxes = torch.tensor(boxes, device=predictor.device)
transformed_boxes = predictor.transform.apply_boxes_torch(input_boxes, image.shape[:2])
return input_boxes, transformed_boxes
def predict(
self,
frame,
input_box=None,
input_point=None,
input_label=None,
multimask_output=False,
):
frame = load_image(frame)
predictor = SamPredictor(self.model)
predictor.set_image(frame)
if type(input_box[0]) == list:
input_boxes, new_boxes = self.multi_boxes(input_box, predictor, frame)
masks, _, _ = predictor.predict_torch(
point_coords=None,
point_labels=None,
boxes=new_boxes,
multimask_output=False,
)
elif type(input_box[0]) == int:
input_boxes = np.array(input_box)[None, :]
masks, _, _ = predictor.predict(
point_coords=input_point,
point_labels=input_label,
box=input_boxes,
multimask_output=multimask_output,
)
return frame, masks, input_boxes
def save_image(
self,
source,
model_type,
input_box=None,
input_point=None,
input_label=None,
multimask_output=False,
output_path="v0.jpg",
):
read_image = load_image(source)
image, anns, boxes = self.predict(read_image, model_type, input_box, input_point, input_label, multimask_output)
if len(anns) == 0:
return
if type(input_box[0]) == list:
for mask in anns:
mask_image = self.load_mask(mask.cpu().numpy(), False)
for box in boxes:
image = self.load_box(box.cpu().numpy(), image)
elif type(input_box[0]) == int:
mask_image = self.load_mask(anns, True)
image = self.load_box(input_box, image)
combined_mask = cv2.add(image, mask_image)
cv2.imwrite(output_path, combined_mask)
return output_path