-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
68 lines (53 loc) · 1.64 KB
/
main.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
import os
import numpy as np
import torch
from mobile_sam import SamAutomaticMaskGenerator, SamPredictor, sam_model_registry
from PIL import Image
from tools import box_prompt, format_results, point_prompt, fast_process
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
sam_checkpoint = "./mobile_sam.pt"
model_type = "vit_t"
mobile_sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
mobile_sam = mobile_sam.to(device=device)
mobile_sam.eval()
mask_generator = SamAutomaticMaskGenerator(mobile_sam)
predictor = SamPredictor(mobile_sam)
@torch.no_grad()
def segment_everything(
image,
input_size=1024,
better_quality=False,
withContours=True,
use_retina=True,
mask_random_color=True,
):
global mask_generator
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))
nd_image = np.array(image)
annotations = mask_generator.generate(nd_image)
fig = 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,
)
return fig
if __name__ == "__main__":
input_path = "resources/dog.jpg"
output_path = "generated/output.png"
os.makedirs(os.path.dirname(output_path), exist_ok=True)
image = Image.open(input_path).convert("RGB")
fig = segment_everything(
image=image
)
fig.save(output_path)