HimankJ commited on
Commit
e0899e6
·
verified ·
1 Parent(s): bf0b5b3

Upload 14 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/sa_1309.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/sa_192.jpg filter=lfs diff=lfs merge=lfs -text
38
+ examples/sa_414.jpg filter=lfs diff=lfs merge=lfs -text
39
+ examples/sa_862.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import gradio as gr
3
+ import torch
4
+ from utils.tools_gradio import fast_process
5
+ from utils.tools import format_results, box_prompt, point_prompt, text_prompt
6
+ from PIL import ImageDraw
7
+ import numpy as np
8
+
9
+ model = YOLO('./weights/FastSAM-x.pt')
10
+
11
+ device = torch.device(
12
+ "cuda" if torch.cuda.is_available()
13
+ else "mps" if torch.backends.mps.is_available()
14
+ else "cpu"
15
+ )
16
+
17
+ def segment_everything(
18
+ input,
19
+ input_size=1024,
20
+ withContours=True,
21
+ iou_threshold=0.7,
22
+ conf_threshold=0.25,
23
+ better_quality=False,
24
+ use_retina=True,
25
+ text="",
26
+ wider=False,
27
+ mask_random_color=True,
28
+ ):
29
+ input_size = int(input_size)
30
+ w, h = input.size
31
+ scale = input_size / max(w, h)
32
+ new_w = int(w * scale)
33
+ new_h = int(h * scale)
34
+ input = input.resize((new_w, new_h))
35
+
36
+ results = model(input,
37
+ device=device,
38
+ retina_masks=True,
39
+ iou=iou_threshold,
40
+ conf=conf_threshold,
41
+ imgsz=input_size,)
42
+
43
+ if len(text) > 0:
44
+ results = format_results(results[0], 0)
45
+ annotations, _ = text_prompt(results, text, input, device=device, wider=wider)
46
+ annotations = np.array([annotations])
47
+ else:
48
+ annotations = results[0].masks.data
49
+
50
+ fig = fast_process(annotations=annotations,
51
+ image=input,
52
+ device=device,
53
+ scale=(1024 // input_size),
54
+ better_quality=better_quality,
55
+ mask_random_color=mask_random_color,
56
+ bbox=None,
57
+ use_retina=use_retina,
58
+ withContours=withContours,)
59
+ return fig
60
+
61
+ title = "<center><strong><font size='8'>🏃 Fast Segment Anything 🤗</font></strong></center>"
62
+ description = """ # 🎯 Instructions for points mode """
63
+ examples = [["examples/sa_8776.jpg"], ["examples/sa_414.jpg"], ["examples/sa_1309.jpg"], ["examples/sa_11025.jpg"],
64
+ ["examples/sa_561.jpg"], ["examples/sa_192.jpg"], ["examples/sa_10039.jpg"], ["examples/sa_862.jpg"]]
65
+ default_example = examples[0]
66
+
67
+ cond_img_e = gr.Image(label="Input", value=default_example[0], type='pil')
68
+ segm_img_e = gr.Image(label="Segmented Image", interactive=False, type='pil')
69
+
70
+ input_size_slider = gr.components.Slider(minimum=512,maximum=1024,value=1024,step=64,label='Input_size',info='Our model was trained on a size of 1024')
71
+
72
+ css = "h1 { text-align: center } .about { text-align: justify; padding-left: 10%; padding-right: 10%; }"
73
+
74
+ demo = gr.Interface(
75
+ segment_everything,
76
+ inputs = [
77
+ gr.Image(label="Input", value=default_example[0], type='pil'),
78
+ gr.components.Slider(minimum=512,maximum=1024,value=1024,step=64,label='Input_size',info='Our model was trained on a size of 1024'),
79
+ gr.Checkbox(value=True, label='withContours', info='draw the edges of the masks')
80
+ ],
81
+ outputs = [
82
+ gr.Image(label="Segmented Image", interactive=False, type='pil')
83
+ ],
84
+ title = title,
85
+ description = description,
86
+ examples = examples,
87
+ )
88
+ demo.launch()
examples/dogs.jpg ADDED
examples/sa_10039.jpg ADDED
examples/sa_11025.jpg ADDED
examples/sa_1309.jpg ADDED

Git LFS Details

  • SHA256: b1012cbfd3ffe4ee0da940dc45961fbd1ce7546bea566f650514ec56d72b0460
  • Pointer size: 132 Bytes
  • Size of remote file: 1.11 MB
examples/sa_192.jpg ADDED

Git LFS Details

  • SHA256: dcec4fce91382cbfeb2711fff3caeae183c23cb6d8a6c9e2ca0cd2e8eac39512
  • Pointer size: 132 Bytes
  • Size of remote file: 1.21 MB
examples/sa_414.jpg ADDED

Git LFS Details

  • SHA256: 69dbead40b43e54d3bb80fb372c2e241b0f3ff2159d32525433a75153e067c65
  • Pointer size: 132 Bytes
  • Size of remote file: 2.23 MB
examples/sa_561.jpg ADDED
examples/sa_862.jpg ADDED

Git LFS Details

  • SHA256: 06efc970f0d95faa6e8c69ee73f2032627569dde1c28bc783faebdaefa5eb2a8
  • Pointer size: 132 Bytes
  • Size of remote file: 1.56 MB
examples/sa_8776.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base-----------------------------------
2
+ matplotlib==3.2.2
3
+ numpy
4
+ opencv-python
5
+
6
+ git+https://github.com/openai/CLIP.git
7
+ # Pillow>=7.1.2
8
+ # PyYAML>=5.3.1
9
+ # requests>=2.23.0
10
+ # scipy>=1.4.1
11
+ # torch
12
+ # torchvision
13
+ # tqdm>=4.64.0
14
+
15
+ # pandas>=1.1.4
16
+ # seaborn>=0.11.0
17
+
18
+ # Ultralytics-----------------------------------
19
+ ultralytics==8.0.121
utils/__init__.py ADDED
File without changes
utils/tools.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+ import matplotlib.pyplot as plt
4
+ import cv2
5
+ import torch
6
+ import os
7
+ import sys
8
+
9
+
10
+ def convert_box_xywh_to_xyxy(box):
11
+ if len(box) == 4:
12
+ return [box[0], box[1], box[0] + box[2], box[1] + box[3]]
13
+ else:
14
+ result = []
15
+ for b in box:
16
+ b = convert_box_xywh_to_xyxy(b)
17
+ result.append(b)
18
+ return result
19
+
20
+
21
+ def segment_image(image, bbox):
22
+ image_array = np.array(image)
23
+ segmented_image_array = np.zeros_like(image_array)
24
+ x1, y1, x2, y2 = bbox
25
+ segmented_image_array[y1:y2, x1:x2] = image_array[y1:y2, x1:x2]
26
+ segmented_image = Image.fromarray(segmented_image_array)
27
+ black_image = Image.new("RGB", image.size, (255, 255, 255))
28
+ # transparency_mask = np.zeros_like((), dtype=np.uint8)
29
+ transparency_mask = np.zeros(
30
+ (image_array.shape[0], image_array.shape[1]), dtype=np.uint8
31
+ )
32
+ transparency_mask[y1:y2, x1:x2] = 255
33
+ transparency_mask_image = Image.fromarray(transparency_mask, mode="L")
34
+ black_image.paste(segmented_image, mask=transparency_mask_image)
35
+ return black_image
36
+
37
+
38
+ def format_results(result, filter=0):
39
+ annotations = []
40
+ n = len(result.masks.data)
41
+ for i in range(n):
42
+ annotation = {}
43
+ mask = result.masks.data[i] == 1.0
44
+
45
+ if torch.sum(mask) < filter:
46
+ continue
47
+ annotation["id"] = i
48
+ annotation["segmentation"] = mask.cpu().numpy()
49
+ annotation["bbox"] = result.boxes.data[i]
50
+ annotation["score"] = result.boxes.conf[i]
51
+ annotation["area"] = annotation["segmentation"].sum()
52
+ annotations.append(annotation)
53
+ return annotations
54
+
55
+
56
+ def filter_masks(annotations): # filter the overlap mask
57
+ annotations.sort(key=lambda x: x["area"], reverse=True)
58
+ to_remove = set()
59
+ for i in range(0, len(annotations)):
60
+ a = annotations[i]
61
+ for j in range(i + 1, len(annotations)):
62
+ b = annotations[j]
63
+ if i != j and j not in to_remove:
64
+ # check if
65
+ if b["area"] < a["area"]:
66
+ if (a["segmentation"] & b["segmentation"]).sum() / b[
67
+ "segmentation"
68
+ ].sum() > 0.8:
69
+ to_remove.add(j)
70
+
71
+ return [a for i, a in enumerate(annotations) if i not in to_remove], to_remove
72
+
73
+
74
+ def get_bbox_from_mask(mask):
75
+ mask = mask.astype(np.uint8)
76
+ contours, hierarchy = cv2.findContours(
77
+ mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
78
+ )
79
+ x1, y1, w, h = cv2.boundingRect(contours[0])
80
+ x2, y2 = x1 + w, y1 + h
81
+ if len(contours) > 1:
82
+ for b in contours:
83
+ x_t, y_t, w_t, h_t = cv2.boundingRect(b)
84
+ # 将多个bbox合并成一个
85
+ x1 = min(x1, x_t)
86
+ y1 = min(y1, y_t)
87
+ x2 = max(x2, x_t + w_t)
88
+ y2 = max(y2, y_t + h_t)
89
+ h = y2 - y1
90
+ w = x2 - x1
91
+ return [x1, y1, x2, y2]
92
+
93
+
94
+ def fast_process(
95
+ annotations, args, mask_random_color, bbox=None, points=None, edges=False
96
+ ):
97
+ if isinstance(annotations[0], dict):
98
+ annotations = [annotation["segmentation"] for annotation in annotations]
99
+ result_name = os.path.basename(args.img_path)
100
+ image = cv2.imread(args.img_path)
101
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
102
+ original_h = image.shape[0]
103
+ original_w = image.shape[1]
104
+ if sys.platform == "darwin":
105
+ plt.switch_backend("TkAgg")
106
+ plt.figure(figsize=(original_w/100, original_h/100))
107
+ # Add subplot with no margin.
108
+ plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
109
+ plt.margins(0, 0)
110
+ plt.gca().xaxis.set_major_locator(plt.NullLocator())
111
+ plt.gca().yaxis.set_major_locator(plt.NullLocator())
112
+ plt.imshow(image)
113
+ if args.better_quality == True:
114
+ if isinstance(annotations[0], torch.Tensor):
115
+ annotations = np.array(annotations.cpu())
116
+ for i, mask in enumerate(annotations):
117
+ mask = cv2.morphologyEx(
118
+ mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)
119
+ )
120
+ annotations[i] = cv2.morphologyEx(
121
+ mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8)
122
+ )
123
+ if args.device == "cpu":
124
+ annotations = np.array(annotations)
125
+ fast_show_mask(
126
+ annotations,
127
+ plt.gca(),
128
+ random_color=mask_random_color,
129
+ bbox=bbox,
130
+ points=points,
131
+ point_label=args.point_label,
132
+ retinamask=args.retina,
133
+ target_height=original_h,
134
+ target_width=original_w,
135
+ )
136
+ else:
137
+ if isinstance(annotations[0], np.ndarray):
138
+ annotations = torch.from_numpy(annotations)
139
+ fast_show_mask_gpu(
140
+ annotations,
141
+ plt.gca(),
142
+ random_color=args.randomcolor,
143
+ bbox=bbox,
144
+ points=points,
145
+ point_label=args.point_label,
146
+ retinamask=args.retina,
147
+ target_height=original_h,
148
+ target_width=original_w,
149
+ )
150
+ if isinstance(annotations, torch.Tensor):
151
+ annotations = annotations.cpu().numpy()
152
+ if args.withContours == True:
153
+ contour_all = []
154
+ temp = np.zeros((original_h, original_w, 1))
155
+ for i, mask in enumerate(annotations):
156
+ if type(mask) == dict:
157
+ mask = mask["segmentation"]
158
+ annotation = mask.astype(np.uint8)
159
+ if args.retina == False:
160
+ annotation = cv2.resize(
161
+ annotation,
162
+ (original_w, original_h),
163
+ interpolation=cv2.INTER_NEAREST,
164
+ )
165
+ contours, hierarchy = cv2.findContours(
166
+ annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
167
+ )
168
+ for contour in contours:
169
+ contour_all.append(contour)
170
+ cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2)
171
+ color = np.array([0 / 255, 0 / 255, 255 / 255, 0.8])
172
+ contour_mask = temp / 255 * color.reshape(1, 1, -1)
173
+ plt.imshow(contour_mask)
174
+
175
+ save_path = args.output
176
+ if not os.path.exists(save_path):
177
+ os.makedirs(save_path)
178
+ plt.axis("off")
179
+ fig = plt.gcf()
180
+ plt.draw()
181
+
182
+ try:
183
+ buf = fig.canvas.tostring_rgb()
184
+ except AttributeError:
185
+ fig.canvas.draw()
186
+ buf = fig.canvas.tostring_rgb()
187
+
188
+ cols, rows = fig.canvas.get_width_height()
189
+ img_array = np.fromstring(buf, dtype=np.uint8).reshape(rows, cols, 3)
190
+ cv2.imwrite(os.path.join(save_path, result_name), cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR))
191
+
192
+
193
+ # CPU post process
194
+ def fast_show_mask(
195
+ annotation,
196
+ ax,
197
+ random_color=False,
198
+ bbox=None,
199
+ points=None,
200
+ point_label=None,
201
+ retinamask=True,
202
+ target_height=960,
203
+ target_width=960,
204
+ ):
205
+ msak_sum = annotation.shape[0]
206
+ height = annotation.shape[1]
207
+ weight = annotation.shape[2]
208
+ # 将annotation 按照面积 排序
209
+ areas = np.sum(annotation, axis=(1, 2))
210
+ sorted_indices = np.argsort(areas)
211
+ annotation = annotation[sorted_indices]
212
+
213
+ index = (annotation != 0).argmax(axis=0)
214
+ if random_color == True:
215
+ color = np.random.random((msak_sum, 1, 1, 3))
216
+ else:
217
+ color = np.ones((msak_sum, 1, 1, 3)) * np.array(
218
+ [30 / 255, 144 / 255, 255 / 255]
219
+ )
220
+ transparency = np.ones((msak_sum, 1, 1, 1)) * 0.6
221
+ visual = np.concatenate([color, transparency], axis=-1)
222
+ mask_image = np.expand_dims(annotation, -1) * visual
223
+
224
+ show = np.zeros((height, weight, 4))
225
+ h_indices, w_indices = np.meshgrid(
226
+ np.arange(height), np.arange(weight), indexing="ij"
227
+ )
228
+ indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
229
+ # 使用向量化索引更新show的值
230
+ show[h_indices, w_indices, :] = mask_image[indices]
231
+ if bbox is not None:
232
+ x1, y1, x2, y2 = bbox
233
+ ax.add_patch(
234
+ plt.Rectangle(
235
+ (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1
236
+ )
237
+ )
238
+ # draw point
239
+ if points is not None:
240
+ plt.scatter(
241
+ [point[0] for i, point in enumerate(points) if point_label[i] == 1],
242
+ [point[1] for i, point in enumerate(points) if point_label[i] == 1],
243
+ s=20,
244
+ c="y",
245
+ )
246
+ plt.scatter(
247
+ [point[0] for i, point in enumerate(points) if point_label[i] == 0],
248
+ [point[1] for i, point in enumerate(points) if point_label[i] == 0],
249
+ s=20,
250
+ c="m",
251
+ )
252
+
253
+ if retinamask == False:
254
+ show = cv2.resize(
255
+ show, (target_width, target_height), interpolation=cv2.INTER_NEAREST
256
+ )
257
+ ax.imshow(show)
258
+
259
+
260
+ def fast_show_mask_gpu(
261
+ annotation,
262
+ ax,
263
+ random_color=False,
264
+ bbox=None,
265
+ points=None,
266
+ point_label=None,
267
+ retinamask=True,
268
+ target_height=960,
269
+ target_width=960,
270
+ ):
271
+ msak_sum = annotation.shape[0]
272
+ height = annotation.shape[1]
273
+ weight = annotation.shape[2]
274
+ areas = torch.sum(annotation, dim=(1, 2))
275
+ sorted_indices = torch.argsort(areas, descending=False)
276
+ annotation = annotation[sorted_indices]
277
+ # 找每个位置第一个非零值下标
278
+ index = (annotation != 0).to(torch.long).argmax(dim=0)
279
+ if random_color == True:
280
+ color = torch.rand((msak_sum, 1, 1, 3)).to(annotation.device)
281
+ else:
282
+ color = torch.ones((msak_sum, 1, 1, 3)).to(annotation.device) * torch.tensor(
283
+ [30 / 255, 144 / 255, 255 / 255]
284
+ ).to(annotation.device)
285
+ transparency = torch.ones((msak_sum, 1, 1, 1)).to(annotation.device) * 0.6
286
+ visual = torch.cat([color, transparency], dim=-1)
287
+ mask_image = torch.unsqueeze(annotation, -1) * visual
288
+ # 按index取数,index指每个位置选哪个batch的数,把mask_image转成一个batch的形式
289
+ show = torch.zeros((height, weight, 4)).to(annotation.device)
290
+ h_indices, w_indices = torch.meshgrid(
291
+ torch.arange(height), torch.arange(weight), indexing="ij"
292
+ )
293
+ indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
294
+ # 使用向量化索引更新show的值
295
+ show[h_indices, w_indices, :] = mask_image[indices]
296
+ show_cpu = show.cpu().numpy()
297
+ if bbox is not None:
298
+ x1, y1, x2, y2 = bbox
299
+ ax.add_patch(
300
+ plt.Rectangle(
301
+ (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1
302
+ )
303
+ )
304
+ # draw point
305
+ if points is not None:
306
+ plt.scatter(
307
+ [point[0] for i, point in enumerate(points) if point_label[i] == 1],
308
+ [point[1] for i, point in enumerate(points) if point_label[i] == 1],
309
+ s=20,
310
+ c="y",
311
+ )
312
+ plt.scatter(
313
+ [point[0] for i, point in enumerate(points) if point_label[i] == 0],
314
+ [point[1] for i, point in enumerate(points) if point_label[i] == 0],
315
+ s=20,
316
+ c="m",
317
+ )
318
+ if retinamask == False:
319
+ show_cpu = cv2.resize(
320
+ show_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST
321
+ )
322
+ ax.imshow(show_cpu)
323
+
324
+
325
+ # clip
326
+ @torch.no_grad()
327
+ def retriev(
328
+ model, preprocess, elements: [Image.Image], search_text: str, device
329
+ ):
330
+ preprocessed_images = [preprocess(image).to(device) for image in elements]
331
+ import clip
332
+ tokenized_text = clip.tokenize([search_text]).to(device)
333
+ stacked_images = torch.stack(preprocessed_images)
334
+ image_features = model.encode_image(stacked_images)
335
+ text_features = model.encode_text(tokenized_text)
336
+ image_features /= image_features.norm(dim=-1, keepdim=True)
337
+ text_features /= text_features.norm(dim=-1, keepdim=True)
338
+ probs = 100.0 * image_features @ text_features.T
339
+ return probs[:, 0].softmax(dim=0)
340
+
341
+
342
+ def crop_image(annotations, image_like):
343
+ if isinstance(image_like, str):
344
+ image = Image.open(image_like)
345
+ else:
346
+ image = image_like
347
+ ori_w, ori_h = image.size
348
+ mask_h, mask_w = annotations[0]["segmentation"].shape
349
+ if ori_w != mask_w or ori_h != mask_h:
350
+ image = image.resize((mask_w, mask_h))
351
+ cropped_boxes = []
352
+ cropped_images = []
353
+ not_crop = []
354
+ origin_id = []
355
+ for _, mask in enumerate(annotations):
356
+ if np.sum(mask["segmentation"]) <= 100:
357
+ continue
358
+ origin_id.append(_)
359
+ bbox = get_bbox_from_mask(mask["segmentation"]) # mask 的 bbox
360
+ cropped_boxes.append(segment_image(image, bbox)) # 保存裁剪的图片
361
+ # cropped_boxes.append(segment_image(image,mask["segmentation"]))
362
+ cropped_images.append(bbox) # 保存裁剪的图片的bbox
363
+ return cropped_boxes, cropped_images, not_crop, origin_id, annotations
364
+
365
+
366
+ def box_prompt(masks, bbox, target_height, target_width):
367
+ h = masks.shape[1]
368
+ w = masks.shape[2]
369
+ if h != target_height or w != target_width:
370
+ bbox = [
371
+ int(bbox[0] * w / target_width),
372
+ int(bbox[1] * h / target_height),
373
+ int(bbox[2] * w / target_width),
374
+ int(bbox[3] * h / target_height),
375
+ ]
376
+ bbox[0] = round(bbox[0]) if round(bbox[0]) > 0 else 0
377
+ bbox[1] = round(bbox[1]) if round(bbox[1]) > 0 else 0
378
+ bbox[2] = round(bbox[2]) if round(bbox[2]) < w else w
379
+ bbox[3] = round(bbox[3]) if round(bbox[3]) < h else h
380
+
381
+ # IoUs = torch.zeros(len(masks), dtype=torch.float32)
382
+ bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])
383
+
384
+ masks_area = torch.sum(masks[:, bbox[1] : bbox[3], bbox[0] : bbox[2]], dim=(1, 2))
385
+ orig_masks_area = torch.sum(masks, dim=(1, 2))
386
+
387
+ union = bbox_area + orig_masks_area - masks_area
388
+ IoUs = masks_area / union
389
+ max_iou_index = torch.argmax(IoUs)
390
+
391
+ return masks[max_iou_index].cpu().numpy(), max_iou_index
392
+
393
+
394
+ def point_prompt(masks, points, point_label, target_height, target_width): # numpy 处理
395
+ h = masks[0]["segmentation"].shape[0]
396
+ w = masks[0]["segmentation"].shape[1]
397
+ if h != target_height or w != target_width:
398
+ points = [
399
+ [int(point[0] * w / target_width), int(point[1] * h / target_height)]
400
+ for point in points
401
+ ]
402
+ onemask = np.zeros((h, w))
403
+ masks = sorted(masks, key=lambda x: x['area'], reverse=True)
404
+ for i, annotation in enumerate(masks):
405
+ if type(annotation) == dict:
406
+ mask = annotation['segmentation']
407
+ else:
408
+ mask = annotation
409
+ for i, point in enumerate(points):
410
+ if mask[point[1], point[0]] == 1 and point_label[i] == 1:
411
+ onemask[mask] = 1
412
+ if mask[point[1], point[0]] == 1 and point_label[i] == 0:
413
+ onemask[mask] = 0
414
+ onemask = onemask >= 1
415
+ return onemask, 0
416
+
417
+
418
+ def text_prompt(annotations, text, img_path, device, wider=False, threshold=0.9):
419
+ cropped_boxes, cropped_images, not_crop, origin_id, annotations_ = crop_image(
420
+ annotations, img_path
421
+ )
422
+
423
+ import clip
424
+ clip_model, preprocess = clip.load("ViT-B/32", device=device)
425
+ scores = retriev(
426
+ clip_model, preprocess, cropped_boxes, text, device=device
427
+ )
428
+ max_idx = scores.argsort()
429
+ max_idx = max_idx[-1]
430
+ max_idx = origin_id[int(max_idx)]
431
+
432
+ # find the biggest mask which contains the mask with max score
433
+ if wider:
434
+ mask0 = annotations_[max_idx]["segmentation"]
435
+ area0 = np.sum(mask0)
436
+ areas = [(i, np.sum(mask["segmentation"])) for i, mask in enumerate(annotations_) if i in origin_id]
437
+ areas = sorted(areas, key=lambda area: area[1], reverse=True)
438
+ indices = [area[0] for area in areas]
439
+ for index in indices:
440
+ if index == max_idx or np.sum(annotations_[index]["segmentation"] & mask0) / area0 > threshold:
441
+ max_idx = index
442
+ break
443
+
444
+ return annotations_[max_idx]["segmentation"], max_idx
utils/tools_gradio.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+ import matplotlib.pyplot as plt
4
+ import cv2
5
+ import torch
6
+
7
+
8
+ def fast_process(
9
+ annotations,
10
+ image,
11
+ device,
12
+ scale,
13
+ better_quality=False,
14
+ mask_random_color=True,
15
+ bbox=None,
16
+ use_retina=True,
17
+ withContours=True,
18
+ ):
19
+ if isinstance(annotations[0], dict):
20
+ annotations = [annotation['segmentation'] for annotation in annotations]
21
+
22
+ original_h = image.height
23
+ original_w = image.width
24
+ if better_quality:
25
+ if isinstance(annotations[0], torch.Tensor):
26
+ annotations = np.array(annotations.cpu())
27
+ for i, mask in enumerate(annotations):
28
+ mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
29
+ annotations[i] = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8))
30
+ if device == 'cpu':
31
+ annotations = np.array(annotations)
32
+ inner_mask = fast_show_mask(
33
+ annotations,
34
+ plt.gca(),
35
+ random_color=mask_random_color,
36
+ bbox=bbox,
37
+ retinamask=use_retina,
38
+ target_height=original_h,
39
+ target_width=original_w,
40
+ )
41
+ else:
42
+ if isinstance(annotations[0], np.ndarray):
43
+ annotations = torch.from_numpy(annotations)
44
+ inner_mask = fast_show_mask_gpu(
45
+ annotations,
46
+ plt.gca(),
47
+ random_color=mask_random_color,
48
+ bbox=bbox,
49
+ retinamask=use_retina,
50
+ target_height=original_h,
51
+ target_width=original_w,
52
+ )
53
+ if isinstance(annotations, torch.Tensor):
54
+ annotations = annotations.cpu().numpy()
55
+
56
+ if withContours:
57
+ contour_all = []
58
+ temp = np.zeros((original_h, original_w, 1))
59
+ for i, mask in enumerate(annotations):
60
+ if type(mask) == dict:
61
+ mask = mask['segmentation']
62
+ annotation = mask.astype(np.uint8)
63
+ if use_retina == False:
64
+ annotation = cv2.resize(
65
+ annotation,
66
+ (original_w, original_h),
67
+ interpolation=cv2.INTER_NEAREST,
68
+ )
69
+ contours, _ = cv2.findContours(annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
70
+ for contour in contours:
71
+ contour_all.append(contour)
72
+ cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2 // scale)
73
+ color = np.array([0 / 255, 0 / 255, 255 / 255, 0.9])
74
+ contour_mask = temp / 255 * color.reshape(1, 1, -1)
75
+
76
+ image = image.convert('RGBA')
77
+ overlay_inner = Image.fromarray((inner_mask * 255).astype(np.uint8), 'RGBA')
78
+ image.paste(overlay_inner, (0, 0), overlay_inner)
79
+
80
+ if withContours:
81
+ overlay_contour = Image.fromarray((contour_mask * 255).astype(np.uint8), 'RGBA')
82
+ image.paste(overlay_contour, (0, 0), overlay_contour)
83
+
84
+ return image
85
+
86
+
87
+ # CPU post process
88
+ def fast_show_mask(
89
+ annotation,
90
+ ax,
91
+ random_color=False,
92
+ bbox=None,
93
+ retinamask=True,
94
+ target_height=960,
95
+ target_width=960,
96
+ ):
97
+ mask_sum = annotation.shape[0]
98
+ height = annotation.shape[1]
99
+ weight = annotation.shape[2]
100
+ # 将annotation 按照面积 排序
101
+ areas = np.sum(annotation, axis=(1, 2))
102
+ sorted_indices = np.argsort(areas)[::1]
103
+ annotation = annotation[sorted_indices]
104
+
105
+ index = (annotation != 0).argmax(axis=0)
106
+ if random_color:
107
+ color = np.random.random((mask_sum, 1, 1, 3))
108
+ else:
109
+ color = np.ones((mask_sum, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 255 / 255])
110
+ transparency = np.ones((mask_sum, 1, 1, 1)) * 0.6
111
+ visual = np.concatenate([color, transparency], axis=-1)
112
+ mask_image = np.expand_dims(annotation, -1) * visual
113
+
114
+ mask = np.zeros((height, weight, 4))
115
+
116
+ h_indices, w_indices = np.meshgrid(np.arange(height), np.arange(weight), indexing='ij')
117
+ indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
118
+
119
+ mask[h_indices, w_indices, :] = mask_image[indices]
120
+ if bbox is not None:
121
+ x1, y1, x2, y2 = bbox
122
+ ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))
123
+
124
+ if not retinamask:
125
+ mask = cv2.resize(mask, (target_width, target_height), interpolation=cv2.INTER_NEAREST)
126
+
127
+ return mask
128
+
129
+
130
+ def fast_show_mask_gpu(
131
+ annotation,
132
+ ax,
133
+ random_color=False,
134
+ bbox=None,
135
+ retinamask=True,
136
+ target_height=960,
137
+ target_width=960,
138
+ ):
139
+ device = annotation.device
140
+ mask_sum = annotation.shape[0]
141
+ height = annotation.shape[1]
142
+ weight = annotation.shape[2]
143
+ areas = torch.sum(annotation, dim=(1, 2))
144
+ sorted_indices = torch.argsort(areas, descending=False)
145
+ annotation = annotation[sorted_indices]
146
+ # 找每个位置第一个非零值下标
147
+ index = (annotation != 0).to(torch.long).argmax(dim=0)
148
+ if random_color:
149
+ color = torch.rand((mask_sum, 1, 1, 3)).to(device)
150
+ else:
151
+ color = torch.ones((mask_sum, 1, 1, 3)).to(device) * torch.tensor(
152
+ [30 / 255, 144 / 255, 255 / 255]
153
+ ).to(device)
154
+ transparency = torch.ones((mask_sum, 1, 1, 1)).to(device) * 0.6
155
+ visual = torch.cat([color, transparency], dim=-1)
156
+ mask_image = torch.unsqueeze(annotation, -1) * visual
157
+ # 按index取数,index指每个位置选哪个batch的数,把mask_image转成一个batch的形式
158
+ mask = torch.zeros((height, weight, 4)).to(device)
159
+ h_indices, w_indices = torch.meshgrid(torch.arange(height), torch.arange(weight))
160
+ indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
161
+ # 使用向量化索引更新show的值
162
+ mask[h_indices, w_indices, :] = mask_image[indices]
163
+ mask_cpu = mask.cpu().numpy()
164
+ if bbox is not None:
165
+ x1, y1, x2, y2 = bbox
166
+ ax.add_patch(
167
+ plt.Rectangle(
168
+ (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1
169
+ )
170
+ )
171
+ if not retinamask:
172
+ mask_cpu = cv2.resize(
173
+ mask_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST
174
+ )
175
+ return mask_cpu