File size: 14,975 Bytes
ddaab9d
 
69420c9
ddaab9d
 
69420c9
 
ddaab9d
 
 
 
b88e069
ddaab9d
69420c9
4975443
69420c9
ddaab9d
 
 
 
 
 
 
69420c9
 
 
 
 
 
 
ddaab9d
 
69420c9
 
 
 
ddaab9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69420c9
 
 
 
 
 
 
ddaab9d
69420c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddaab9d
 
c9b7234
ddaab9d
ee42a6b
ddaab9d
 
 
 
ee42a6b
 
ddaab9d
 
 
ee42a6b
ddaab9d
 
 
ee42a6b
 
ddaab9d
 
 
 
 
4c7dc89
 
 
 
 
 
 
435ddbc
65665c1
 
b88e069
4c7dc89
 
 
 
 
 
 
 
435ddbc
65665c1
 
b88e069
4c7dc89
 
 
 
 
 
 
b88e069
4c7dc89
 
 
 
 
 
 
 
 
 
ddaab9d
 
 
 
 
 
 
4c7dc89
 
ddaab9d
435ddbc
65665c1
ddaab9d
b88e069
ddaab9d
 
 
 
 
 
 
 
 
 
 
 
 
69420c9
ee42a6b
4c7dc89
 
 
 
 
 
 
 
ee42a6b
ddaab9d
ee42a6b
4c7dc89
 
ddaab9d
4c7dc89
 
ddaab9d
4c7dc89
ddaab9d
 
 
 
4c7dc89
65665c1
 
ddaab9d
69420c9
4c7dc89
 
69420c9
435ddbc
65665c1
 
4c7dc89
 
69420c9
 
 
 
4c7dc89
 
69420c9
435ddbc
65665c1
 
4c7dc89
 
69420c9
 
 
ddaab9d
 
 
 
 
69420c9
ddaab9d
 
 
 
 
 
 
 
 
 
 
 
 
b88e069
 
 
65665c1
b88e069
ddaab9d
 
 
4c7dc89
69420c9
 
 
 
 
 
ddaab9d
ee42a6b
 
 
ddaab9d
4c7dc89
 
 
 
 
 
 
ddaab9d
4c7dc89
ee42a6b
4c7dc89
ee42a6b
 
 
ddaab9d
4c7dc89
ddaab9d
4c7dc89
 
 
ee42a6b
 
 
 
 
 
4c7dc89
69420c9
4c7dc89
69420c9
 
435ddbc
65665c1
 
69420c9
 
 
 
 
 
435ddbc
65665c1
 
4c7dc89
69420c9
 
 
ee42a6b
 
 
 
 
 
 
 
 
 
 
 
b88e069
 
 
 
 
 
4c7dc89
ddaab9d
ee42a6b
 
ddaab9d
b88e069
 
 
 
 
 
ddaab9d
4c7dc89
 
 
 
 
435ddbc
 
4c7dc89
 
ddaab9d
 
 
 
 
 
 
 
 
ee42a6b
ddaab9d
 
 
 
 
 
 
 
 
 
 
ee42a6b
b88e069
 
ddaab9d
ee42a6b
 
ddaab9d
 
 
4c7dc89
b88e069
ee42a6b
ddaab9d
 
 
b88e069
 
ddaab9d
 
 
 
 
ee42a6b
 
 
 
 
b88e069
 
 
ddaab9d
 
 
 
 
 
4c7dc89
b88e069
ee42a6b
ddaab9d
 
 
b88e069
 
ddaab9d
50728a6
 
69420c9
 
50728a6
b88e069
 
ee42a6b
b88e069
 
 
ddaab9d
b88e069
 
ee42a6b
b88e069
 
 
ddaab9d
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# Code credit: [FastSAM Demo](https://huggingface.co/spaces/An-619/FastSAM).

import torch
import gradio as gr
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
from segment_anything.onnx import SamPredictorONNX
from PIL import ImageDraw
from utils.tools_gradio import fast_process
import copy
import argparse
from PIL import Image

# Use ONNX to speed up the inference.
ENABLE_ONNX = False

parser = argparse.ArgumentParser(
    description="Host EdgeSAM as a local web service."
)
parser.add_argument(
    "--checkpoint",
    default="weights/edge_sam_3x.pth",
    type=str,
    help="The path to the PyTorch checkpoint of EdgeSAM."
)
parser.add_argument(
    "--encoder-onnx-path",
    default="weights/edge_sam_3x_encoder.onnx",
    type=str,
    help="The path to the ONNX model of EdgeSAM's encoder."
)
parser.add_argument(
    "--decoder-onnx-path",
    default="weights/edge_sam_3x_decoder.onnx",
    type=str,
    help="The path to the ONNX model of EdgeSAM's decoder."
)
parser.add_argument(
    "--server-name",
    default="0.0.0.0",
    type=str,
    help="The server address that this demo will be hosted on."
)
parser.add_argument(
    "--port",
    default=8080,
    type=int,
    help="The port that this demo will be hosted on."
)
args = parser.parse_args()

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if ENABLE_ONNX:
    predictor = SamPredictorONNX(args.encoder_onnx_path, args.decoder_onnx_path)
else:
    sam = sam_model_registry["edge_sam"](checkpoint=args.checkpoint, upsample_mode="bicubic")
    sam = sam.to(device=device)
    sam.eval()
    predictor = SamPredictor(sam)

examples = [
    ["assets/1.jpeg"],
    ["assets/2.jpeg"],
    ["assets/3.jpeg"],
    ["assets/4.jpeg"],
    ["assets/5.jpeg"],
    ["assets/6.jpeg"],
    ["assets/7.jpeg"],
    ["assets/8.jpeg"],
    ["assets/9.jpeg"],
    ["assets/10.jpeg"],
    ["assets/11.jpeg"],
    ["assets/12.jpeg"],
    ["assets/13.jpeg"],
    ["assets/14.jpeg"],
    ["assets/15.jpeg"],
    ["assets/16.jpeg"]
]

# Description
title = "<center><strong><font size='8'>EdgeSAM<font></strong> <a href='https://github.com/chongzhou96/EdgeSAM'><font size='6'>[GitHub]</font></a> </center>"

description_p = """ # Instructions for point mode

                1. Upload an image or click one of the provided examples.
                2. Select the point type.
                3. Click once or multiple times on the image to indicate the object of interest.
                4. The Clear button clears all the points.
                5. The Reset button resets both points and the image.

              """

description_b = """ # Instructions for box mode

                1. Upload an image or click one of the provided examples.
                2. Click twice on the image (diagonal points of the box).
                3. The Clear button clears the box.
                4. The Reset button resets both the box and the image.

              """

css = "h1 { text-align: center } .about { text-align: justify; padding-left: 10%; padding-right: 10%; }"


def reset(session_state):
    session_state['coord_list'] = []
    session_state['label_list'] = []
    session_state['box_list'] = []
    session_state['ori_image'] = None
    session_state['image_with_prompt'] = None
    session_state['feature'] = None
    session_state['input_size'] = None
    session_state['original_size'] = None
    return None, None, None, session_state


def reset_all(session_state):
    session_state['coord_list'] = []
    session_state['label_list'] = []
    session_state['box_list'] = []
    session_state['ori_image'] = None
    session_state['image_with_prompt'] = None
    session_state['feature'] = None
    session_state['input_size'] = None
    session_state['original_size'] = None
    return None, None, None, None, None, None, session_state


def clear(session_state):
    session_state['coord_list'] = []
    session_state['label_list'] = []
    session_state['box_list'] = []
    session_state['image_with_prompt'] = copy.deepcopy(session_state['ori_image'])
    return session_state['ori_image'], None, None, session_state


def on_image_upload(
    image,
    session_state,
    input_size=1024
):
    session_state['coord_list'] = []
    session_state['label_list'] = []
    session_state['box_list'] = []

    input_size = int(input_size)
    w, h = image.size
    scale = input_size / max(w, h)
    new_w = int(w * scale)
    new_h = int(h * scale)
    image = image.resize((new_w, new_h))
    session_state['ori_image'] = copy.deepcopy(image)
    session_state['image_with_prompt'] = copy.deepcopy(image)
    print("Image changed")
    nd_image = np.array(image)
    session_state['feature'], session_state['input_size'], session_state['original_size'] = predictor.set_image(nd_image)

    return image, None, None, session_state


def convert_box(xyxy):
    min_x = min(xyxy[0][0], xyxy[1][0])
    max_x = max(xyxy[0][0], xyxy[1][0])
    min_y = min(xyxy[0][1], xyxy[1][1])
    max_y = max(xyxy[0][1], xyxy[1][1])
    xyxy[0][0] = min_x
    xyxy[1][0] = max_x
    xyxy[0][1] = min_y
    xyxy[1][1] = max_y
    return xyxy


def segment_with_points(
    label,
    session_state,
    evt: gr.SelectData,
    input_size=1024,
    better_quality=False,
    withContours=True,
    use_retina=True,
    mask_random_color=False,
):
    x, y = evt.index[0], evt.index[1]
    point_radius, point_color = 5, (97, 217, 54) if label == "Positive" else (237, 34, 13)
    session_state['coord_list'].append([x, y])
    session_state['label_list'].append(1 if label == "Positive" else 0)

    print(f"coord_list: {session_state['coord_list']}")
    print(f"label_list: {session_state['label_list']}")

    draw = ImageDraw.Draw(session_state['image_with_prompt'])
    draw.ellipse(
        [(x - point_radius, y - point_radius), (x + point_radius, y + point_radius)],
        fill=point_color,
    )
    image = session_state['image_with_prompt']
    print(f"image: {image.size}")
    nd_image = np.array(session_state['ori_image'])

    if ENABLE_ONNX:
        coord_np = np.array(session_state['coord_list'])[None]
        label_np = np.array(session_state['label_list'])[None]
        masks, scores, _ = predictor.predict(
            features=session_state['feature'],
            input_size=session_state['input_size'],
            original_size=session_state['original_size'],
            point_coords=coord_np,
            point_labels=label_np,
        )
        masks = masks.squeeze(0)
        scores = scores.squeeze(0)
    else:
        coord_np = np.array(session_state['coord_list'])
        label_np = np.array(session_state['label_list'])
        masks, scores, logits = predictor.predict(
            features=session_state['feature'],
            input_size=session_state['input_size'],
            original_size=session_state['original_size'],
            point_coords=coord_np,
            point_labels=label_np,
            num_multimask_outputs=4,
            use_stability_score=True
        )

    print(f'scores: {scores}')
    area = masks.sum(axis=(1, 2))
    print(f'area: {area}')

    annotations = np.expand_dims(masks[scores.argmax()], axis=0)

    seg = fast_process(
        annotations=annotations,
        image=image,
        device=device,
        scale=(1024 // input_size),
        better_quality=better_quality,
        mask_random_color=mask_random_color,
        bbox=None,
        use_retina=use_retina,
        withContours=withContours,
    )

    binary_mask = np.where(annotations[0] > 0.5, 255, 0).astype(np.uint8)
    mask = Image.fromarray(binary_mask)
    binary_mask = np.expand_dims(binary_mask, axis=2)
    crop = Image.fromarray(np.concatenate((nd_image, binary_mask), axis=2), "RGBA")
    return seg, mask, crop, session_state


def segment_with_box(
        session_state,
        evt: gr.SelectData,
        input_size=1024,
        better_quality=False,
        withContours=True,
        use_retina=True,
        mask_random_color=False,
):
    x, y = evt.index[0], evt.index[1]
    point_radius, point_color, box_outline = 5, (97, 217, 54), 5
    box_color = (0, 255, 0)

    if len(session_state['box_list']) == 0:
        session_state['box_list'].append([x, y])
    elif len(session_state['box_list']) == 1:
        session_state['box_list'].append([x, y])
    elif len(session_state['box_list']) == 2:
        session_state['image_with_prompt'] = copy.deepcopy(session_state['ori_image'])
        session_state['box_list'] = [[x, y]]

    print(f"box_list: {session_state['box_list']}")

    draw = ImageDraw.Draw(session_state['image_with_prompt'])
    draw.ellipse(
        [(x - point_radius, y - point_radius), (x + point_radius, y + point_radius)],
        fill=point_color,
    )
    image = session_state['image_with_prompt']

    if len(session_state['box_list']) == 2:
        box = convert_box(session_state['box_list'])
        xy = (box[0][0], box[0][1], box[1][0], box[1][1])
        draw.rectangle(
            xy,
            outline=box_color,
            width=box_outline
        )

        box_np = np.array(box)
        if ENABLE_ONNX:
            point_coords = box_np.reshape(2, 2)[None]
            point_labels = np.array([2, 3])[None]
            masks, _, _ = predictor.predict(
                features=session_state['feature'],
                input_size=session_state['input_size'],
                original_size=session_state['original_size'],
                point_coords=point_coords,
                point_labels=point_labels,
            )
            annotations = masks[:, 0, :, :]
        else:
            masks, scores, _ = predictor.predict(
                features=session_state['feature'],
                input_size=session_state['input_size'],
                original_size=session_state['original_size'],
                box=box_np,
                num_multimask_outputs=1,
            )
            annotations = masks

        seg = fast_process(
            annotations=annotations,
            image=image,
            device=device,
            scale=(1024 // input_size),
            better_quality=better_quality,
            mask_random_color=mask_random_color,
            bbox=None,
            use_retina=use_retina,
            withContours=withContours,
        )
        binary_mask = np.where(annotations[0] > 0.5, 255, 0).astype(np.uint8)
        mask = Image.fromarray(binary_mask)
        binary_mask = np.expand_dims(binary_mask, axis=2)
        crop = Image.fromarray(np.concatenate((session_state['ori_image'], binary_mask), axis=2), "RGBA")
        return seg, mask, crop, session_state
    return image, None, None, session_state


img_p = gr.Image(label="Input with points", type="pil")
img_b = gr.Image(label="Input with box", type="pil")

mask_p = gr.Image(label="Mask", type="pil", interactive=False)
crop_p = gr.Image(label="Cropped image", type="pil", interactive=False)

mask_b = gr.Image(label="Mask", type="pil", interactive=False)
crop_b = gr.Image(label="Cropped image", type="pil", interactive=False)

with gr.Blocks(css=css, title="EdgeSAM") as demo:
    session_state = gr.State({
        'coord_list': [],
        'label_list': [],
        'box_list': [],
        'ori_image': None,
        'image_with_prompt': None,
        'feature': None
    })

    with gr.Row():
        with gr.Column(scale=1):
            # Title
            gr.Markdown(title)

    with gr.Tab("Point mode") as tab_p:
        # Images
        with gr.Row(variant="panel"):
            with gr.Column(scale=1):
                img_p.render()
            with gr.Column(scale=1):
                with gr.Row():
                    add_or_remove = gr.Radio(
                        ["Positive", "Negative"],
                        value="Positive",
                        label="Point Type"
                    )

                    with gr.Column():
                        clear_btn_p = gr.Button("Clear", variant="secondary")
                        reset_btn_p = gr.Button("Reset", variant="secondary")
                with gr.Row():
                    mask_p.render()
                    crop_p.render()

        with gr.Row():
            with gr.Column():
                gr.Markdown("Try some of the examples below ⬇️")
                gr.Examples(
                    examples=examples,
                    inputs=[img_p, session_state],
                    outputs=[img_p, mask_p, crop_p, session_state],
                    examples_per_page=8,
                    fn=on_image_upload,
                    run_on_click=True
                )
            with gr.Column():
                gr.Markdown(description_p)

    with gr.Tab("Box mode") as tab_b:
        # Images
        with gr.Row(variant="panel"):
            with gr.Column(scale=1):
                img_b.render()
            with gr.Row():
                with gr.Column():
                    clear_btn_b = gr.Button("Clear", variant="secondary")
                    reset_btn_b = gr.Button("Reset", variant="secondary")
                    with gr.Row():
                        mask_b.render()
                        crop_b.render()

        with gr.Row():
            with gr.Column():
                gr.Markdown("Try some of the examples below ⬇️")
                gr.Examples(
                    examples=examples,
                    inputs=[img_b, session_state],
                    outputs=[img_b, mask_b, crop_b, session_state],
                    examples_per_page=8,
                    fn=on_image_upload,
                    run_on_click=True
                )
            with gr.Column():
                gr.Markdown(description_b)

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown(
                "<center><img src='https://visitor-badge.laobi.icu/badge?page_id=chongzhou/edgesam' alt='visitors'></center>")

    img_p.upload(on_image_upload, [img_p, session_state], [img_p, mask_p, crop_p, session_state])
    img_p.select(segment_with_points, [add_or_remove, session_state], [img_p, mask_p, crop_p, session_state])

    clear_btn_p.click(clear, [session_state], [img_p, mask_p, crop_p, session_state])
    reset_btn_p.click(reset, [session_state], [img_p, mask_p, crop_p, session_state])
    tab_p.select(fn=reset_all, inputs=[session_state], outputs=[img_p, mask_p, crop_p, img_b, mask_b, crop_b, session_state])

    img_b.upload(on_image_upload, [img_b, session_state], [img_b, mask_b, crop_b, session_state])
    img_b.select(segment_with_box, [session_state], [img_b, mask_b, crop_b, session_state])

    clear_btn_b.click(clear, [session_state], [img_b, mask_b, crop_b, session_state])
    reset_btn_b.click(reset, [session_state], [img_b, mask_b, crop_b, session_state])
    tab_b.select(fn=reset_all, inputs=[session_state], outputs=[img_p, mask_p, crop_p, img_b, mask_b, crop_b, session_state])

demo.queue()
# demo.launch(server_name=args.server_name, server_port=args.port)
demo.launch()