Jose Benitez Matias Ponchon commited on
Commit
2e64de9
·
unverified ·
1 Parent(s): 2b083e6

Streamlit app (#4)

Browse files

* add streamlit app

* update space

* add edgeSAM

* Add default issue templates

---------

Co-authored-by: Matias Ponchon <matias@ponchon.com.ar>

.gitattributes CHANGED
@@ -1,2 +1,12 @@
1
  efficient_sam_s_gpu.jit filter=lfs diff=lfs merge=lfs -text
2
  efficient_sam_s_cpu.jit filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
1
  efficient_sam_s_gpu.jit filter=lfs diff=lfs merge=lfs -text
2
  efficient_sam_s_cpu.jit filter=lfs diff=lfs merge=lfs -text
3
+ weights/edge_sam_3x_encoder.mlpackage.zip filter=lfs diff=lfs merge=lfs -text
4
+ weights/edge_sam_decoder.mlpackage.zip filter=lfs diff=lfs merge=lfs -text
5
+ weights/edge_sam_3x_encoder.onnx filter=lfs diff=lfs merge=lfs -text
6
+ weights/edge_sam_encoder.onnx filter=lfs diff=lfs merge=lfs -text
7
+ weights/edge_sam.pth filter=lfs diff=lfs merge=lfs -text
8
+ weights/edge_sam_3x.pth filter=lfs diff=lfs merge=lfs -text
9
+ weights/edge_sam_3x_decoder.mlpackage.zip filter=lfs diff=lfs merge=lfs -text
10
+ weights/edge_sam_encoder.mlpackage.zip filter=lfs diff=lfs merge=lfs -text
11
+ weights/edge_sam_3x_decoder.onnx filter=lfs diff=lfs merge=lfs -text
12
+ weights/edge_sam_decoder.onnx filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -3,8 +3,8 @@ title: SAM Arena
3
  emoji: ⚔️
4
  colorFrom: red
5
  colorTo: green
6
- sdk: gradio
7
- sdk_version: 4.9.0
8
  app_file: app.py
9
  pinned: false
10
  ---
 
3
  emoji: ⚔️
4
  colorFrom: red
5
  colorTo: green
6
+ sdk: streamlit
7
+ sdk_version: 1.25.0
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py CHANGED
@@ -1,251 +1,119 @@
1
- # Thanks to the following repos:
2
- # https://huggingface.co/spaces/An-619/FastSAM/blob/main/app_gradio.py
3
- # https://huggingface.co/spaces/SkalskiP/EfficientSAM
4
- from typing import Tuple
5
 
6
- from ultralytics import YOLO
7
- from PIL import ImageDraw
8
  from PIL import Image
9
- import gradio as gr
10
  import numpy as np
11
  import torch
12
 
13
- from transformers import SamModel, SamProcessor
14
-
15
- import supervision as sv
16
- from utils.tools_gradio import fast_process
17
- from utils.tools import format_results, point_prompt
18
- from utils.draw import draw_circle, calculate_dynamic_circle_radius
19
- from utils.efficient_sam import load, inference_with_box, inference_with_point
20
-
21
- DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
- # Load the pre-trained models
23
- FASTSAM_MODEL = YOLO('FastSAM-s.pt')
24
- SAM_MODEL = SamModel.from_pretrained("facebook/sam-vit-huge").to(DEVICE)
25
- SAM_PROCESSOR = SamProcessor.from_pretrained("facebook/sam-vit-huge")
26
- EFFICIENT_SAM_MODEL = load(device=DEVICE)
27
-
28
- MASK_COLOR = sv.Color.from_hex("#FF0000")
29
- PROMPT_COLOR = sv.Color.from_hex("#D3D3D3")
30
- MASK_ANNOTATOR = sv.MaskAnnotator(
31
- color=MASK_COLOR,
32
- color_lookup=sv.ColorLookup.INDEX)
33
-
34
- title = "<center><strong><font size='8'>🤗 Segment Anything Model Arena ⚔️</font></strong></center>"
35
-
36
- description = "<center><font size='4'>This is a demo of the <strong>Segment Anything Model Arena</strong>, a collection of models for segmenting anything. "
37
-
38
- css = "h1 { text-align: center } .about { text-align: justify; padding-left: 10%; padding-right: 10%; }"
39
-
40
- #examples = [["examples/retail01.png"], ["examples/vend01.png"], ["examples/vend02.png"]]
41
-
42
- POINT_EXAMPLES = [
43
- ['https://media.roboflow.com/efficient-sam/corgi.jpg', 1291, 751],
44
- ['https://media.roboflow.com/efficient-sam/horses.jpg', 1168, 939],
45
- ['https://media.roboflow.com/efficient-sam/bears.jpg', 913, 1051]
46
- ]
47
-
48
- #default_example = examples[0]
49
-
50
- def annotate_image_with_point_prompt_result(
51
- image: np.ndarray,
52
- detections: sv.Detections,
53
- x: int,
54
- y: int
55
- ) -> np.ndarray:
56
- h, w, _ = image.shape
57
- bgr_image = image[:, :, ::-1]
58
- annotated_bgr_image = MASK_ANNOTATOR.annotate(
59
- scene=bgr_image, detections=detections)
60
- annotated_bgr_image = draw_circle(
61
- scene=annotated_bgr_image,
62
- center=sv.Point(x=x, y=y),
63
- radius=calculate_dynamic_circle_radius(resolution_wh=(w, h)),
64
- color=PROMPT_COLOR)
65
- return annotated_bgr_image[:, :, ::-1]
66
-
67
- def SAM_points_inference(image: np.ndarray) -> np.ndarray:
68
- global global_points
69
- input_points = [[[float(num) for num in sublist]] for sublist in global_points]
70
- print(input_points)
71
- #input_points = [[[773.0, 167.0]]]
72
- x = int(input_points[0][0][0])
73
- y = int(input_points[0][0][1])
74
-
75
- inputs = SAM_PROCESSOR(
76
- Image.fromarray(image),
77
- input_points=[input_points],
78
- return_tensors="pt"
79
- ).to(DEVICE)
80
-
81
- with torch.no_grad():
82
- outputs = SAM_MODEL(**inputs)
83
-
84
- mask = SAM_PROCESSOR.image_processor.post_process_masks(
85
- outputs.pred_masks.cpu(),
86
- inputs["original_sizes"].cpu(),
87
- inputs["reshaped_input_sizes"].cpu()
88
- )[0][0][0].numpy()
89
- mask = mask[np.newaxis, ...]
90
- detections = sv.Detections(xyxy=sv.mask_to_xyxy(masks=mask), mask=mask)
91
-
92
- return annotate_image_with_point_prompt_result(
93
- image=image, detections=detections, x=x, y=y)
94
-
95
- def FastSAM_points_inference(
96
- input,
97
- input_size=1024,
98
- iou_threshold=0.7,
99
- conf_threshold=0.25,
100
- better_quality=False,
101
- withContours=True,
102
- use_retina=True,
103
- mask_random_color=True,
104
- ):
105
- global global_points
106
- global global_point_label
107
- input = Image.fromarray(input)
108
- input_size = int(input_size) # 确保 imgsz 是整数
109
- # Thanks for the suggestion by hysts in HuggingFace.
110
- w, h = input.size
111
- scale = input_size / max(w, h)
112
- new_w = int(w * scale)
113
- new_h = int(h * scale)
114
- input = input.resize((new_w, new_h))
115
-
116
- scaled_points = [[int(x * scale) for x in point] for point in global_points]
117
-
118
- results = FASTSAM_MODEL(input,
119
- device=DEVICE,
120
- retina_masks=True,
121
- iou=iou_threshold,
122
- conf=conf_threshold,
123
- imgsz=input_size,)
124
-
125
- results = format_results(results[0], 0)
126
- annotations, _ = point_prompt(results, scaled_points, global_point_label, new_h, new_w)
127
- annotations = np.array([annotations])
128
-
129
- fig = fast_process(annotations=annotations,
130
- image=input,
131
- device=DEVICE,
132
- scale=(1024 // input_size),
133
- better_quality=better_quality,
134
- mask_random_color=mask_random_color,
135
- bbox=None,
136
- use_retina=use_retina,
137
- withContours=withContours,)
138
-
139
- global_points = []
140
- global_point_label = []
141
-
142
- return fig
143
-
144
- def EfficientSAM_points_inference(image: np.ndarray):
145
- x, y = int(global_points[0][0]), int(global_points[0][1])
146
- point = np.array([[int(x), int(y)]])
147
- mask = inference_with_point(image, point, EFFICIENT_SAM_MODEL, DEVICE)
148
- mask = mask[np.newaxis, ...]
149
- detections = sv.Detections(xyxy=sv.mask_to_xyxy(masks=mask), mask=mask)
150
-
151
- return annotate_image_with_point_prompt_result(image=image, detections=detections, x=x, y=y)
152
-
153
- def get_points_with_draw(image, label, evt: gr.SelectData):
154
- global global_points
155
- global global_point_label
156
-
157
- x, y = evt.index[0], evt.index[1]
158
- point_radius, point_color = 15, (255, 0, 0) if label == 'Add Mask' else (255, 0, 255)
159
- global_points.append([x, y])
160
- global_point_label.append(1 if label == 'Add Mask' else 0)
161
-
162
- print(x, y, label == 'Add Mask')
163
- image = Image.fromarray(image)
164
- draw = ImageDraw.Draw(image)
165
- draw.ellipse([(x - point_radius, y - point_radius), (x + point_radius, y + point_radius)], fill=point_color)
166
- return image
167
-
168
- def clear(_: np.ndarray) -> Tuple[None, None, None, None]:
169
- return None, None, None, None
170
-
171
- gr_input_image = gr.Image(label="Input", value='examples/fruits.jpg')
172
-
173
- fast_sam_segmented_image = gr.Image(label="Fast SAM", interactive=False, type='pil')
174
-
175
- edge_sam_segmented_imaged = gr.Image(label="Edge SAM", interactive=False, type='pil')
176
-
177
-
178
- global_points = []
179
- global_point_label = []
180
-
181
- with gr.Blocks() as demo:
182
- with gr.Tab("Points prompt"):
183
- # Input Image
184
- with gr.Row(variant="panel"):
185
- with gr.Column(scale=1, min_width="320", variant="compact"):
186
- gr_input_image.render()
187
 
188
- # Submit & Clear
189
- with gr.Row():
190
- with gr.Column():
191
- with gr.Row():
192
- add_or_remove = gr.Radio(["Add Mask", "Remove Area"], value="Add Mask", label="Point label (foreground/background)")
193
- with gr.Column():
194
- inference_point_button = gr.Button("Segment", variant='primary')
195
- clear_button = gr.Button("Clear points", variant='secondary')
196
 
197
- # Segment Results Grid
198
- with gr.Row(variant="panel"):
199
- with gr.Column(scale=1):
200
- sam_segmented_image = gr.Image(label="SAM")
201
- with gr.Column(scale=1):
202
- efficient_sam_segmented_image = gr.Image(label="Efficient SAM")
203
 
204
- with gr.Row(variant="panel"):
205
- with gr.Column(scale=1):
206
- fast_sam_segmented_image.render()
207
- with gr.Column(scale=1):
208
- edge_sam_segmented_imaged.render()
209
-
210
- gr.Markdown("AI Generated Examples")
211
- # gr.Examples(examples=examples,
212
- # inputs=[gr_input_image],
213
- # # outputs=sam_segmented_image,
214
- # # fn=segment_with_points,
215
- # # cache_examples=True,
216
- # examples_per_page=3)
217
-
218
- gr_input_image.select(get_points_with_draw, [gr_input_image, add_or_remove], gr_input_image)
219
-
220
- inference_point_button.click(
221
- SAM_points_inference,
222
- inputs=[gr_input_image],
223
- outputs=[sam_segmented_image]
224
- )
225
-
226
- inference_point_button.click(
227
- EfficientSAM_points_inference,
228
- inputs=[gr_input_image],
229
- outputs=[efficient_sam_segmented_image])
230
-
231
- inference_point_button.click(
232
- FastSAM_points_inference,
233
- inputs=[gr_input_image],
234
- outputs=[fast_sam_segmented_image])
 
 
 
 
 
 
 
235
 
236
- # inference_point_button.click(
237
- # EdgeSAM_points_inference,
238
- # inputs=[gr_input_image],
239
- # outputs=[fast_sam_segmented_image, gr_input_image])
 
240
 
241
- gr_input_image.change(
242
- clear,
243
- inputs=gr_input_image,
244
- outputs=[efficient_sam_segmented_image, sam_segmented_image, fast_sam_segmented_image]
245
- )
246
-
247
- clear_button.click(clear, outputs=[gr_input_image, efficient_sam_segmented_image, sam_segmented_image, fast_sam_segmented_image])
248
-
249
-
250
- demo.queue()
251
- demo.launch(debug=True, show_error=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_drawable_canvas import st_canvas
 
 
3
 
 
 
4
  from PIL import Image
5
+ import pandas as pd
6
  import numpy as np
7
  import torch
8
 
9
+ from utils.SAM import SAM_points_inference, FastSAM_points_inference, EfficientSAM_points_inference, EdgeSAM_points_inference
10
+ from utils.draw import draw_SAM_mask_point, draw_FastSAM_point, draw_EdgeSAM_point
11
+ from utils.tools import pil_to_bytes
12
+
13
+ def click(container_width,height,scale,radius_width,show_mask,im):
14
+ for each in ['color_change_point_box','input_masks_color_box']:
15
+ if each in st.session_state:st.session_state.pop(each)
16
+ canvas_result = st_canvas(
17
+ fill_color="rgba(255, 255, 0, 0.8)",
18
+ background_image = st.session_state['im'],
19
+ drawing_mode='point',
20
+ width = container_width,
21
+ height = height * scale,
22
+ point_display_radius = radius_width,
23
+ stroke_width=2,
24
+ update_streamlit=True,
25
+ key="click",)
26
+ if not show_mask:
27
+ im = Image.fromarray(im).convert("RGB")
28
+ rerun = False
29
+ if im != st.session_state['im']:
30
+ rerun = True
31
+ st.session_state['im'] = im
32
+ if rerun:
33
+ st.rerun()
34
+ elif canvas_result.json_data is not None:
35
+ df = pd.json_normalize(canvas_result.json_data["objects"])
36
+ if len(df) == 0:
37
+ st.session_state.clear()
38
+ if 'canvas_result' not in st.session_state:
39
+ st.session_state['canvas_result'] = len(df)
40
+ st.rerun()
41
+ elif len(df) != st.session_state['canvas_result']:
42
+ st.session_state['canvas_result'] = len(df)
43
+ st.rerun()
44
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ df["center_x"] = df["left"]
47
+ df["center_y"] = df["top"]
 
 
 
 
 
 
48
 
49
+ input_points = []
50
+ input_labels = []
 
 
 
 
51
 
52
+ for _, row in df.iterrows():
53
+ x, y = row["center_x"] + 5, row["center_y"]
54
+ x = int(x/scale)
55
+ y = int(y/scale)
56
+ input_points.append([x, y])
57
+ if row['fill'] == "rgba(0, 255, 0, 0.8)":
58
+ input_labels.append(1)
59
+ else:
60
+ input_labels.append(0)
61
+
62
+ col1, col2 = st.columns(2)
63
+
64
+ with col1:
65
+ # SAM inference
66
+ SAM_masks = SAM_points_inference(im, [input_points])
67
+ st.image(draw_SAM_mask_point(im, SAM_masks, input_points[0][0], input_points[0][1]))
68
+ st.success('SAM Inference completed!', icon="✅")
69
+
70
+ # EfficientSAM inference
71
+ EfficientSAM_masks = EfficientSAM_points_inference(im, input_points)
72
+ st.image(draw_SAM_mask_point(im, EfficientSAM_masks, input_points[0][0], input_points[0][1]))
73
+ st.success('EfficientSAM Inference completed!', icon="✅")
74
+
75
+ with col2:
76
+ # FastSAM inference
77
+ FastSAM_masks = FastSAM_points_inference(im, input_points, input_labels)
78
+ st.image(draw_FastSAM_point(FastSAM_masks))
79
+ st.success('FastSAM Inference completed!', icon="✅")
80
+
81
+ # EdgeSAM inference
82
+ EdgeSAM_masks = EdgeSAM_points_inference(im, input_points, [1])
83
+ st.image(draw_EdgeSAM_point(im, EdgeSAM_masks))
84
+ st.success('EdgeSAM Inference completed!', icon="✅")
85
+
86
+
87
+ def main():
88
+ print('init')
89
+ torch.cuda.empty_cache()
90
 
91
+ with st.sidebar:
92
+ im = st.file_uploader(label='Upload image',type=['png','jpg','tif'])
93
+ option = st.selectbox(
94
+ 'Segmentation mode',
95
+ ('Click', 'Box', 'Everything'))
96
 
97
+ show_mask = st.checkbox('Show mask',value = True)
98
+ radius_width = st.slider('Radius/Width for Click/Box',0,20,5,1)
99
+
100
+ if im:
101
+ im = Image.open(im).convert("RGB")
102
+ if 'im' not in st.session_state:
103
+ st.session_state['im'] = im
104
+ width, height = im.size[:2]
105
+ im = np.array(im)
106
+ container_width = 700
107
+ scale = container_width/width
108
+ if option == 'Click':
109
+ click(container_width,
110
+ height,
111
+ scale,
112
+ radius_width,
113
+ show_mask,
114
+ im)
115
+ else:
116
+ st.session_state.clear()
117
+
118
+ if __name__ == '__main__':
119
+ main()
requirements.txt CHANGED
@@ -2,9 +2,13 @@ torch
2
  torchvision
3
 
4
  pillow
5
- gradio==3.44.0
6
  transformers
7
  supervision
8
  ultralytics
9
  clip
10
  opencv-python
 
 
 
 
 
 
2
  torchvision
3
 
4
  pillow
 
5
  transformers
6
  supervision
7
  ultralytics
8
  clip
9
  opencv-python
10
+ scikit-image
11
+ streamlit-drawable-canvas
12
+
13
+ timm
14
+ onnxruntime
utils/SAM.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+ import streamlit as st
6
+ import supervision as sv
7
+
8
+ from ultralytics import YOLO
9
+ from ultralytics import FastSAM
10
+ from ultralytics.models.fastsam import FastSAMPrompt
11
+
12
+ from transformers import SamModel, SamProcessor
13
+
14
+ from utils.efficient_sam import load, inference_with_point
15
+ import sys
16
+ sys.path.insert(1, './utils')
17
+ from edge_sam import sam_model_registry, SamPredictor
18
+ from edge_sam.onnx import SamPredictorONNX
19
+
20
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+
22
+ # Use ONNX to speed up the inference.
23
+ ENABLE_ONNX = False
24
+
25
+ ENCODER_ONNX_PATH = 'weights/edge_sam_3x_encoder.onnx'
26
+ DECODER_ONNX_PATH = 'weights/edge_sam_3x_decoder.onnx'
27
+ EDGESAM_CHECKPOINT = 'weights/edge_sam_3x.pth'
28
+
29
+ SAM_MODEL = SamModel.from_pretrained("facebook/sam-vit-huge").to(DEVICE)
30
+ SAM_PROCESSOR = SamProcessor.from_pretrained("facebook/sam-vit-huge")
31
+ FASTSAM_MODEL = FastSAM('FastSAM-x.pt')
32
+ EFFICIENT_SAM_MODEL = load(device=DEVICE)
33
+
34
+ if ENABLE_ONNX:
35
+ predictor = SamPredictorONNX(ENCODER_ONNX_PATH, DECODER_ONNX_PATH)
36
+ else:
37
+ sam = sam_model_registry["edge_sam"](EDGESAM_CHECKPOINT, upsample_mode="bicubic")
38
+ sam = sam.to(device=DEVICE)
39
+ sam.eval()
40
+ predictor = SamPredictor(sam)
41
+
42
+ @st.cache_data
43
+ def SAM_points_inference(image: np.ndarray, input_points) -> np.ndarray:
44
+ print('Processing SAM... 📊')
45
+ #input_points = [[[float(num) for num in sublist]] for sublist in global_points]
46
+ #print(input_points)
47
+ #input_points = [[[773.0, 167.0]]]
48
+ x = int(input_points[0][0][0])
49
+ y = int(input_points[0][0][1])
50
+
51
+ inputs = SAM_PROCESSOR(
52
+ Image.fromarray(image),
53
+ input_points=[input_points],
54
+ return_tensors="pt"
55
+ ).to(DEVICE)
56
+
57
+ with torch.no_grad():
58
+ outputs = SAM_MODEL(**inputs)
59
+
60
+ mask = SAM_PROCESSOR.image_processor.post_process_masks(
61
+ outputs.pred_masks.cpu(),
62
+ inputs["original_sizes"].cpu(),
63
+ inputs["reshaped_input_sizes"].cpu()
64
+ )[0][0][0].numpy()
65
+ mask = mask[np.newaxis, ...]
66
+ detections = sv.Detections(xyxy=sv.mask_to_xyxy(masks=mask), mask=mask)
67
+ return detections
68
+
69
+ @st.cache_data
70
+ def FastSAM_points_inference(
71
+ input,
72
+ input_points,
73
+ input_labels,
74
+ input_size=1024,
75
+ iou_threshold=0.7,
76
+ conf_threshold=0.25
77
+ ):
78
+ # scaled input points
79
+ #input_points = [[[float(num) for num in sublist]] for sublist in input_points]
80
+ print('Processing FastSAM... 📊')
81
+ results = FASTSAM_MODEL(input,
82
+ device=DEVICE,
83
+ retina_masks=True,
84
+ iou=iou_threshold,
85
+ conf=conf_threshold,
86
+ imgsz=input_size)
87
+
88
+ prompt_process = FastSAMPrompt(input, results, device=DEVICE)
89
+
90
+ # Point prompt
91
+ detections = prompt_process.point_prompt(points=input_points, pointlabel=[1])
92
+ return detections
93
+
94
+ @st.cache_data
95
+ def EfficientSAM_points_inference(image: np.ndarray, input_points):
96
+ x, y = int(input_points[0][0]), int(input_points[0][1])
97
+ point = np.array([[int(x), int(y)]])
98
+ mask = inference_with_point(image, point, EFFICIENT_SAM_MODEL, DEVICE)
99
+ mask = mask[np.newaxis, ...]
100
+ detections = sv.Detections(xyxy=sv.mask_to_xyxy(masks=mask), mask=mask)
101
+
102
+ return detections
103
+
104
+ @st.cache_data
105
+ def EdgeSAM_points_inference(
106
+ image_input,
107
+ input_points,
108
+ input_labels,
109
+ input_size=1024,
110
+ better_quality=False,
111
+ withContours=True,
112
+ use_retina=True,
113
+ mask_random_color=False,
114
+ ):
115
+ # convert the numpy image from BGR to RGB
116
+ features = predictor.set_image(image_input)
117
+ print(type(predictor))
118
+ print(type(image_input))
119
+ print(image_input.shape)
120
+ print(image_input.dtype)
121
+ if ENABLE_ONNX:
122
+ input_points_np = np.array(input_points)[None]
123
+ input_labels_np = np.array(input_labels)[None]
124
+
125
+ masks, scores, _ = predictor.predict(
126
+ features=features,
127
+ point_coords=input_points_np,
128
+ point_labels=input_labels_np,
129
+ )
130
+ masks = masks.squeeze(0)
131
+ scores = scores.squeeze(0)
132
+ else:
133
+ input_points_np = np.array(input_points)
134
+ input_labels_np = np.array(input_labels)
135
+ masks, scores, logits = predictor.predict(
136
+ features=features,
137
+ point_coords=input_points_np,
138
+ point_labels=input_labels_np,
139
+ num_multimask_outputs=4,
140
+ use_stability_score=True
141
+ )
142
+
143
+ print(f'scores: {scores}')
144
+ area = masks.sum(axis=(1, 2))
145
+ print(f'area: {area}')
146
+
147
+ annotations = np.expand_dims(masks[scores.argmax()], axis=0)
148
+
149
+ return annotations
utils/draw.py CHANGED
@@ -1,10 +1,36 @@
1
- #https://huggingface.co/spaces/SkalskiP/EfficientSAM
 
2
  from typing import Tuple
3
 
4
  import cv2
5
  import numpy as np
 
6
  import supervision as sv
 
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def draw_circle(
10
  scene: np.ndarray, center: sv.Point, color: sv.Color, radius: int = 2
@@ -30,4 +56,84 @@ def calculate_dynamic_circle_radius(resolution_wh: Tuple[int, int]) -> int:
30
  if min_dimension < 2160:
31
  return 16
32
  else:
33
- return 16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # code kudos https://huggingface.co/spaces/SkalskiP/EfficientSAM
2
+ # fastSAM ultralytics
3
  from typing import Tuple
4
 
5
  import cv2
6
  import numpy as np
7
+ import torch
8
  import supervision as sv
9
+ import streamlit as st
10
 
11
+ MASK_COLOR = sv.Color.from_hex("#FF0000")
12
+ PROMPT_COLOR = sv.Color.from_hex("#D3D3D3")
13
+ MASK_ANNOTATOR = sv.MaskAnnotator(
14
+ color=MASK_COLOR,
15
+ color_lookup=sv.ColorLookup.INDEX)
16
+
17
+ @st.cache_data
18
+ def draw_SAM_mask_point(
19
+ image: np.ndarray,
20
+ detections: sv.Detections,
21
+ x: int,
22
+ y: int
23
+ ) -> np.ndarray:
24
+ h, w, _ = image.shape
25
+ bgr_image = image[:, :, ::-1]
26
+ annotated_bgr_image = MASK_ANNOTATOR.annotate(
27
+ scene=bgr_image, detections=detections)
28
+ annotated_bgr_image = draw_circle(
29
+ scene=annotated_bgr_image,
30
+ center=sv.Point(x=x, y=y),
31
+ radius=calculate_dynamic_circle_radius(resolution_wh=(w, h)),
32
+ color=PROMPT_COLOR)
33
+ return annotated_bgr_image[:, :, ::-1]
34
 
35
  def draw_circle(
36
  scene: np.ndarray, center: sv.Point, color: sv.Color, radius: int = 2
 
56
  if min_dimension < 2160:
57
  return 16
58
  else:
59
+ return 16
60
+
61
+ def apply_masks_and_draw(image, masks, random_color=False, retinamask=True, original_h=None, original_w=None):
62
+ """
63
+ Applies mask annotations to the image and returns the result.
64
+
65
+ Args:
66
+ image (numpy.ndarray): Original image in RGB format.
67
+ masks (numpy.ndarray): Array of mask annotations.
68
+ random_color (bool, optional): Whether to use random color for masks. Defaults to False.
69
+ retinamask (bool, optional): Whether to use retina mask for resizing. Defaults to True.
70
+ original_h (int, optional): Original height of the image.
71
+ original_w (int, optional): Original width of the image.
72
+
73
+ Returns:
74
+ numpy.ndarray: Image with masks applied.
75
+ """
76
+ if original_h is None:
77
+ original_h = image.shape[0]
78
+ if original_w is None:
79
+ original_w = image.shape[1]
80
+
81
+ n, h, w = masks.shape # number of masks, height, width
82
+
83
+ # Sort masks by area
84
+ areas = np.sum(masks, axis=(1, 2))
85
+ masks = masks[np.argsort(areas)]
86
+
87
+ # Create mask image
88
+ index = (masks != 0).argmax(axis=0)
89
+ if random_color:
90
+ color = np.random.random((n, 1, 1, 3))
91
+ else:
92
+ color = np.ones((n, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 1.0])
93
+ transparency = np.ones((n, 1, 1, 1)) * 0.6
94
+ visual = np.concatenate([color, transparency], axis=-1)
95
+ mask_image = np.expand_dims(masks, -1) * visual
96
+
97
+ # Prepare the final image
98
+ show = np.zeros((h, w, 4))
99
+ h_indices, w_indices = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
100
+ indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
101
+ show[h_indices, w_indices, :] = mask_image[indices]
102
+
103
+ if not retinamask:
104
+ show = cv2.resize(show, (original_w, original_h), interpolation=cv2.INTER_NEAREST)
105
+
106
+ # Add masks to the original image
107
+ output_image = image.copy()
108
+ for i in range(show.shape[2] - 1): # Exclude the alpha channel
109
+ output_image[:, :, i] = output_image[:, :, i] * (1 - show[:, :, 3]) + show[:, :, i] * show[:, :, 3]
110
+
111
+ return output_image.astype(np.uint8)
112
+
113
+ def draw_FastSAM_point(detections):
114
+ for ann in detections:
115
+ image = ann.orig_img[..., ::-1] # Convert BGR to RGB
116
+ original_h, original_w = ann.orig_shape
117
+
118
+ if ann.masks is not None:
119
+ masks = ann.masks.data
120
+ if isinstance(masks[0], torch.Tensor):
121
+ masks = np.array(masks.cpu())
122
+
123
+ output_image = apply_masks_and_draw(image, masks, random_color=True, retinamask=False, original_h=original_h, original_w=original_w)
124
+ cv2.imwrite('output.png', output_image)
125
+ return cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
126
+
127
+ def draw_EdgeSAM_point(image, masks):
128
+ # convert BGR to RGB numpy image
129
+ image = image[..., ::-1] # Convert BGR to RGB
130
+ # shapes
131
+ original_h, original_w = image.shape[:2]
132
+
133
+ if masks is not None:
134
+ if isinstance(masks[0], torch.Tensor):
135
+ masks = np.array(masks.cpu())
136
+
137
+ output_image = apply_masks_and_draw(image, masks, random_color=True, retinamask=False, original_h=original_h, original_w=original_w)
138
+ cv2.imwrite('output.png', output_image)
139
+ return cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
utils/edge_sam/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .build_sam import (
8
+ build_sam,
9
+ build_sam_vit_h,
10
+ build_sam_vit_l,
11
+ build_sam_vit_b,
12
+ sam_model_registry,
13
+ )
14
+ from .predictor import SamPredictor
15
+ from .automatic_mask_generator import SamAutomaticMaskGenerator
utils/edge_sam/automatic_mask_generator.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torchvision.ops.boxes import batched_nms, box_area # type: ignore
10
+
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+
13
+ from .modeling import Sam
14
+ from .predictor import SamPredictor
15
+ from .utils.amg import (
16
+ MaskData,
17
+ area_from_rle,
18
+ batch_iterator,
19
+ batched_mask_to_box,
20
+ box_xyxy_to_xywh,
21
+ build_all_layer_point_grids,
22
+ calculate_stability_score,
23
+ coco_encode_rle,
24
+ generate_crop_boxes,
25
+ is_box_near_crop_edge,
26
+ mask_to_rle_pytorch,
27
+ remove_small_regions,
28
+ rle_to_mask,
29
+ uncrop_boxes_xyxy,
30
+ uncrop_masks,
31
+ uncrop_points,
32
+ )
33
+
34
+
35
+ class SamAutomaticMaskGenerator:
36
+ def __init__(
37
+ self,
38
+ model: Sam,
39
+ points_per_side: Optional[int] = 32,
40
+ points_per_batch: int = 64,
41
+ pred_iou_thresh: float = 0.88,
42
+ stability_score_thresh: float = 0.95,
43
+ stability_score_offset: float = 1.0,
44
+ box_nms_thresh: float = 0.7,
45
+ crop_n_layers: int = 0,
46
+ crop_nms_thresh: float = 0.7,
47
+ crop_overlap_ratio: float = 512 / 1500,
48
+ crop_n_points_downscale_factor: int = 1,
49
+ point_grids: Optional[List[np.ndarray]] = None,
50
+ min_mask_region_area: int = 0,
51
+ output_mode: str = "binary_mask",
52
+ ) -> None:
53
+ """
54
+ Using a SAM model, generates masks for the entire image.
55
+ Generates a grid of point prompts over the image, then filters
56
+ low quality and duplicate masks. The default settings are chosen
57
+ for SAM with a ViT-H backbone.
58
+
59
+ Arguments:
60
+ model (Sam): The SAM model to use for mask prediction.
61
+ points_per_side (int or None): The number of points to be sampled
62
+ along one side of the image. The total number of points is
63
+ points_per_side**2. If None, 'point_grids' must provide explicit
64
+ point sampling.
65
+ points_per_batch (int): Sets the number of points run simultaneously
66
+ by the model. Higher numbers may be faster but use more GPU memory.
67
+ pred_iou_thresh (float): A filtering threshold in [0,1], using the
68
+ model's predicted mask quality.
69
+ stability_score_thresh (float): A filtering threshold in [0,1], using
70
+ the stability of the mask under changes to the cutoff used to binarize
71
+ the model's mask predictions.
72
+ stability_score_offset (float): The amount to shift the cutoff when
73
+ calculated the stability score.
74
+ box_nms_thresh (float): The box IoU cutoff used by non-maximal
75
+ suppression to filter duplicate masks.
76
+ crop_n_layers (int): If >0, mask prediction will be run again on
77
+ crops of the image. Sets the number of layers to run, where each
78
+ layer has 2**i_layer number of image crops.
79
+ crop_nms_thresh (float): The box IoU cutoff used by non-maximal
80
+ suppression to filter duplicate masks between different crops.
81
+ crop_overlap_ratio (float): Sets the degree to which crops overlap.
82
+ In the first crop layer, crops will overlap by this fraction of
83
+ the image length. Later layers with more crops scale down this overlap.
84
+ crop_n_points_downscale_factor (int): The number of points-per-side
85
+ sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
86
+ point_grids (list(np.ndarray) or None): A list over explicit grids
87
+ of points used for sampling, normalized to [0,1]. The nth grid in the
88
+ list is used in the nth crop layer. Exclusive with points_per_side.
89
+ min_mask_region_area (int): If >0, postprocessing will be applied
90
+ to remove disconnected regions and holes in masks with area smaller
91
+ than min_mask_region_area. Requires opencv.
92
+ output_mode (str): The form masks are returned in. Can be 'binary_mask',
93
+ 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
94
+ For large resolutions, 'binary_mask' may consume large amounts of
95
+ memory.
96
+ """
97
+
98
+ assert (points_per_side is None) != (
99
+ point_grids is None
100
+ ), "Exactly one of points_per_side or point_grid must be provided."
101
+ if points_per_side is not None:
102
+ self.point_grids = build_all_layer_point_grids(
103
+ points_per_side,
104
+ crop_n_layers,
105
+ crop_n_points_downscale_factor,
106
+ )
107
+ elif point_grids is not None:
108
+ self.point_grids = point_grids
109
+ else:
110
+ raise ValueError("Can't have both points_per_side and point_grid be None.")
111
+
112
+ assert output_mode in [
113
+ "binary_mask",
114
+ "uncompressed_rle",
115
+ "coco_rle",
116
+ ], f"Unknown output_mode {output_mode}."
117
+ if output_mode == "coco_rle":
118
+ from pycocotools import mask as mask_utils # type: ignore # noqa: F401
119
+
120
+ if min_mask_region_area > 0:
121
+ import cv2 # type: ignore # noqa: F401
122
+
123
+ self.predictor = SamPredictor(model)
124
+ self.points_per_batch = points_per_batch
125
+ self.pred_iou_thresh = pred_iou_thresh
126
+ self.stability_score_thresh = stability_score_thresh
127
+ self.stability_score_offset = stability_score_offset
128
+ self.box_nms_thresh = box_nms_thresh
129
+ self.crop_n_layers = crop_n_layers
130
+ self.crop_nms_thresh = crop_nms_thresh
131
+ self.crop_overlap_ratio = crop_overlap_ratio
132
+ self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
133
+ self.min_mask_region_area = min_mask_region_area
134
+ self.output_mode = output_mode
135
+
136
+ @torch.no_grad()
137
+ def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
138
+ """
139
+ Generates masks for the given image.
140
+
141
+ Arguments:
142
+ image (np.ndarray): The image to generate masks for, in HWC uint8 format.
143
+
144
+ Returns:
145
+ list(dict(str, any)): A list over records for masks. Each record is
146
+ a dict containing the following keys:
147
+ segmentation (dict(str, any) or np.ndarray): The mask. If
148
+ output_mode='binary_mask', is an array of shape HW. Otherwise,
149
+ is a dictionary containing the RLE.
150
+ bbox (list(float)): The box around the mask, in XYWH format.
151
+ area (int): The area in pixels of the mask.
152
+ predicted_iou (float): The model's own prediction of the mask's
153
+ quality. This is filtered by the pred_iou_thresh parameter.
154
+ point_coords (list(list(float))): The point coordinates input
155
+ to the model to generate this mask.
156
+ stability_score (float): A measure of the mask's quality. This
157
+ is filtered on using the stability_score_thresh parameter.
158
+ crop_box (list(float)): The crop of the image used to generate
159
+ the mask, given in XYWH format.
160
+ """
161
+
162
+ # Generate masks
163
+ mask_data = self._generate_masks(image)
164
+
165
+ # Filter small disconnected regions and holes in masks
166
+ if self.min_mask_region_area > 0:
167
+ mask_data = self.postprocess_small_regions(
168
+ mask_data,
169
+ self.min_mask_region_area,
170
+ max(self.box_nms_thresh, self.crop_nms_thresh),
171
+ )
172
+
173
+ # Encode masks
174
+ if self.output_mode == "coco_rle":
175
+ mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]]
176
+ elif self.output_mode == "binary_mask":
177
+ mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
178
+ else:
179
+ mask_data["segmentations"] = mask_data["rles"]
180
+
181
+ # Write mask records
182
+ curr_anns = []
183
+ for idx in range(len(mask_data["segmentations"])):
184
+ ann = {
185
+ "segmentation": mask_data["segmentations"][idx],
186
+ "area": area_from_rle(mask_data["rles"][idx]),
187
+ "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
188
+ "predicted_iou": mask_data["iou_preds"][idx].item(),
189
+ "point_coords": [mask_data["points"][idx].tolist()],
190
+ "stability_score": mask_data["stability_score"][idx].item(),
191
+ "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
192
+ }
193
+ curr_anns.append(ann)
194
+
195
+ return curr_anns
196
+
197
+ def _generate_masks(self, image: np.ndarray) -> MaskData:
198
+ orig_size = image.shape[:2]
199
+ crop_boxes, layer_idxs = generate_crop_boxes(
200
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
201
+ )
202
+
203
+ # Iterate over image crops
204
+ data = MaskData()
205
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
206
+ crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
207
+ data.cat(crop_data)
208
+
209
+ # Remove duplicate masks between crops
210
+ if len(crop_boxes) > 1:
211
+ # Prefer masks from smaller crops
212
+ scores = 1 / box_area(data["crop_boxes"])
213
+ scores = scores.to(data["boxes"].device)
214
+ keep_by_nms = batched_nms(
215
+ data["boxes"].float(),
216
+ scores,
217
+ torch.zeros_like(data["boxes"][:, 0]), # categories
218
+ iou_threshold=self.crop_nms_thresh,
219
+ )
220
+ data.filter(keep_by_nms)
221
+
222
+ data.to_numpy()
223
+ return data
224
+
225
+ def _process_crop(
226
+ self,
227
+ image: np.ndarray,
228
+ crop_box: List[int],
229
+ crop_layer_idx: int,
230
+ orig_size: Tuple[int, ...],
231
+ ) -> MaskData:
232
+ # Crop the image and calculate embeddings
233
+ x0, y0, x1, y1 = crop_box
234
+ cropped_im = image[y0:y1, x0:x1, :]
235
+ cropped_im_size = cropped_im.shape[:2]
236
+ self.predictor.set_image(cropped_im)
237
+
238
+ # Get points for this crop
239
+ points_scale = np.array(cropped_im_size)[None, ::-1]
240
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
241
+
242
+ # Generate masks for this crop in batches
243
+ data = MaskData()
244
+ for (points,) in batch_iterator(self.points_per_batch, points_for_image):
245
+ batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)
246
+ data.cat(batch_data)
247
+ del batch_data
248
+ self.predictor.reset_image()
249
+
250
+ # Remove duplicates within this crop.
251
+ keep_by_nms = batched_nms(
252
+ data["boxes"].float(),
253
+ data["iou_preds"],
254
+ torch.zeros_like(data["boxes"][:, 0]), # categories
255
+ iou_threshold=self.box_nms_thresh,
256
+ )
257
+ data.filter(keep_by_nms)
258
+
259
+ # Return to the original image frame
260
+ data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
261
+ data["points"] = uncrop_points(data["points"], crop_box)
262
+ data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
263
+
264
+ return data
265
+
266
+ def _process_batch(
267
+ self,
268
+ points: np.ndarray,
269
+ im_size: Tuple[int, ...],
270
+ crop_box: List[int],
271
+ orig_size: Tuple[int, ...],
272
+ ) -> MaskData:
273
+ orig_h, orig_w = orig_size
274
+
275
+ # Run model on this batch
276
+ transformed_points = self.predictor.transform.apply_coords(points, im_size)
277
+ in_points = torch.as_tensor(transformed_points, device=self.predictor.device)
278
+ in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)
279
+ masks, iou_preds, _ = self.predictor.predict_torch(
280
+ in_points[:, None, :],
281
+ in_labels[:, None],
282
+ num_multimask_outputs=3,
283
+ return_logits=True,
284
+ )
285
+
286
+ # Serialize predictions and store in MaskData
287
+ data = MaskData(
288
+ masks=masks.flatten(0, 1),
289
+ iou_preds=iou_preds.flatten(0, 1),
290
+ points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),
291
+ )
292
+ del masks
293
+
294
+ # Filter by predicted IoU
295
+ if self.pred_iou_thresh > 0.0:
296
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
297
+ data.filter(keep_mask)
298
+
299
+ # Calculate stability score
300
+ data["stability_score"] = calculate_stability_score(
301
+ data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset
302
+ )
303
+ if self.stability_score_thresh > 0.0:
304
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
305
+ data.filter(keep_mask)
306
+
307
+ # Threshold masks and calculate boxes
308
+ data["masks"] = data["masks"] > self.predictor.model.mask_threshold
309
+ data["boxes"] = batched_mask_to_box(data["masks"])
310
+
311
+ # Filter boxes that touch crop boundaries
312
+ keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h])
313
+ if not torch.all(keep_mask):
314
+ data.filter(keep_mask)
315
+
316
+ # Compress to RLE
317
+ data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
318
+ data["rles"] = mask_to_rle_pytorch(data["masks"])
319
+ del data["masks"]
320
+
321
+ return data
322
+
323
+ @staticmethod
324
+ def postprocess_small_regions(
325
+ mask_data: MaskData, min_area: int, nms_thresh: float
326
+ ) -> MaskData:
327
+ """
328
+ Removes small disconnected regions and holes in masks, then reruns
329
+ box NMS to remove any new duplicates.
330
+
331
+ Edits mask_data in place.
332
+
333
+ Requires open-cv as a dependency.
334
+ """
335
+ if len(mask_data["rles"]) == 0:
336
+ return mask_data
337
+
338
+ # Filter small disconnected regions and holes
339
+ new_masks = []
340
+ scores = []
341
+ for rle in mask_data["rles"]:
342
+ mask = rle_to_mask(rle)
343
+
344
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
345
+ unchanged = not changed
346
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
347
+ unchanged = unchanged and not changed
348
+
349
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
350
+ # Give score=0 to changed masks and score=1 to unchanged masks
351
+ # so NMS will prefer ones that didn't need postprocessing
352
+ scores.append(float(unchanged))
353
+
354
+ # Recalculate boxes and remove any new duplicates
355
+ masks = torch.cat(new_masks, dim=0)
356
+ boxes = batched_mask_to_box(masks)
357
+ keep_by_nms = batched_nms(
358
+ boxes.float(),
359
+ torch.as_tensor(scores),
360
+ torch.zeros_like(boxes[:, 0]), # categories
361
+ iou_threshold=nms_thresh,
362
+ )
363
+
364
+ # Only recalculate RLEs for masks that have changed
365
+ for i_mask in keep_by_nms:
366
+ if scores[i_mask] == 0.0:
367
+ mask_torch = masks[i_mask].unsqueeze(0)
368
+ mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
369
+ mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
370
+ mask_data.filter(keep_by_nms)
371
+
372
+ return mask_data
utils/edge_sam/build_sam.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+
9
+ from functools import partial
10
+
11
+ from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer, RepViT
12
+
13
+
14
+ prompt_embed_dim = 256
15
+ image_size = 1024
16
+ vit_patch_size = 16
17
+ image_embedding_size = image_size // vit_patch_size
18
+
19
+
20
+ def build_sam_vit_h(checkpoint=None):
21
+ image_encoder = _build_sam_encoder(
22
+ encoder_embed_dim=1280,
23
+ encoder_depth=32,
24
+ encoder_num_heads=16,
25
+ encoder_global_attn_indexes=[7, 15, 23, 31]
26
+ )
27
+ return _build_sam(image_encoder, checkpoint)
28
+
29
+
30
+ def build_sam_vit_l(checkpoint=None):
31
+ image_encoder = _build_sam_encoder(
32
+ encoder_embed_dim=1024,
33
+ encoder_depth=24,
34
+ encoder_num_heads=16,
35
+ encoder_global_attn_indexes=[5, 11, 17, 23]
36
+ )
37
+ return _build_sam(image_encoder, checkpoint)
38
+
39
+
40
+ def build_sam_vit_b(checkpoint=None):
41
+ image_encoder = _build_sam_encoder(
42
+ encoder_embed_dim=768,
43
+ encoder_depth=12,
44
+ encoder_num_heads=12,
45
+ encoder_global_attn_indexes=[2, 5, 8, 11]
46
+ )
47
+ return _build_sam(image_encoder, checkpoint)
48
+
49
+
50
+ def build_edge_sam(checkpoint=None, upsample_mode="bicubic"):
51
+ image_encoder = RepViT(
52
+ arch="m1",
53
+ img_size=image_size,
54
+ upsample_mode=upsample_mode
55
+ )
56
+ return _build_sam(image_encoder, checkpoint)
57
+
58
+
59
+ sam_model_registry = {
60
+ "default": build_edge_sam,
61
+ "vit_h": build_sam_vit_h,
62
+ "vit_l": build_sam_vit_l,
63
+ "vit_b": build_sam_vit_b,
64
+ "edge_sam": build_edge_sam,
65
+ }
66
+ build_sam = build_edge_sam
67
+
68
+
69
+ def _build_sam_encoder(
70
+ encoder_embed_dim,
71
+ encoder_depth,
72
+ encoder_num_heads,
73
+ encoder_global_attn_indexes,
74
+ ):
75
+ image_encoder = ImageEncoderViT(
76
+ depth=encoder_depth,
77
+ embed_dim=encoder_embed_dim,
78
+ img_size=image_size,
79
+ mlp_ratio=4,
80
+ norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
81
+ num_heads=encoder_num_heads,
82
+ patch_size=vit_patch_size,
83
+ qkv_bias=True,
84
+ use_rel_pos=True,
85
+ global_attn_indexes=encoder_global_attn_indexes,
86
+ window_size=14,
87
+ out_chans=prompt_embed_dim,
88
+ )
89
+ return image_encoder
90
+
91
+
92
+ def _build_sam(
93
+ image_encoder,
94
+ checkpoint=None,
95
+ ):
96
+ sam = Sam(
97
+ image_encoder=image_encoder,
98
+ prompt_encoder=PromptEncoder(
99
+ embed_dim=prompt_embed_dim,
100
+ image_embedding_size=(image_embedding_size, image_embedding_size),
101
+ input_image_size=(image_size, image_size),
102
+ mask_in_chans=16,
103
+ ),
104
+ mask_decoder=MaskDecoder(
105
+ num_multimask_outputs=3,
106
+ transformer=TwoWayTransformer(
107
+ depth=2,
108
+ embedding_dim=prompt_embed_dim,
109
+ mlp_dim=2048,
110
+ num_heads=8,
111
+ ),
112
+ transformer_dim=prompt_embed_dim,
113
+ iou_head_depth=3,
114
+ iou_head_hidden_dim=256,
115
+ ),
116
+ pixel_mean=[123.675, 116.28, 103.53],
117
+ pixel_std=[58.395, 57.12, 57.375],
118
+ )
119
+ sam.eval()
120
+ if checkpoint is not None:
121
+ with open(checkpoint, "rb") as f:
122
+ state_dict = torch.load(f, map_location="cpu")
123
+ sam.load_state_dict(state_dict)
124
+ return sam
utils/edge_sam/modeling/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .sam import Sam
8
+ from .image_encoder import ImageEncoderViT
9
+ from .mask_decoder import MaskDecoder
10
+ from .prompt_encoder import PromptEncoder
11
+ from .transformer import TwoWayTransformer
12
+ from .rep_vit import *
utils/edge_sam/modeling/common.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from typing import Type
12
+
13
+
14
+ class MLPBlock(nn.Module):
15
+ def __init__(
16
+ self,
17
+ embedding_dim: int,
18
+ mlp_dim: int,
19
+ act: Type[nn.Module] = nn.GELU,
20
+ ) -> None:
21
+ super().__init__()
22
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
23
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
24
+ self.act = act()
25
+
26
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
27
+ return self.lin2(self.act(self.lin1(x)))
28
+
29
+
30
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
31
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
32
+ class LayerNorm2d(nn.Module):
33
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
34
+ super().__init__()
35
+ self.weight = nn.Parameter(torch.ones(num_channels))
36
+ self.bias = nn.Parameter(torch.zeros(num_channels))
37
+ self.eps = eps
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ u = x.mean(1, keepdim=True)
41
+ s = (x - u).pow(2).mean(1, keepdim=True)
42
+ x = (x - u) / torch.sqrt(s + self.eps)
43
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
44
+ return x
45
+
46
+
47
+ def val2list(x: list or tuple or any, repeat_time=1) -> list:
48
+ if isinstance(x, (list, tuple)):
49
+ return list(x)
50
+ return [x for _ in range(repeat_time)]
51
+
52
+
53
+ def val2tuple(x: list or tuple or any, min_len: int = 1, idx_repeat: int = -1) -> tuple:
54
+ x = val2list(x)
55
+
56
+ # repeat elements if necessary
57
+ if len(x) > 0:
58
+ x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))]
59
+
60
+ return tuple(x)
61
+
62
+
63
+ def list_sum(x: list) -> any:
64
+ return x[0] if len(x) == 1 else x[0] + list_sum(x[1:])
65
+
66
+
67
+ def resize(
68
+ x: torch.Tensor,
69
+ size: any or None = None,
70
+ scale_factor=None,
71
+ mode: str = "bicubic",
72
+ align_corners: bool or None = False,
73
+ ) -> torch.Tensor:
74
+ if mode in ["bilinear", "bicubic"]:
75
+ return F.interpolate(
76
+ x,
77
+ size=size,
78
+ scale_factor=scale_factor,
79
+ mode=mode,
80
+ align_corners=align_corners,
81
+ )
82
+ elif mode in ["nearest", "area"]:
83
+ return F.interpolate(x, size=size, scale_factor=scale_factor, mode=mode)
84
+ else:
85
+ raise NotImplementedError(f"resize(mode={mode}) not implemented.")
86
+
87
+
88
+ class UpSampleLayer(nn.Module):
89
+ def __init__(
90
+ self,
91
+ mode="bicubic",
92
+ size=None,
93
+ factor=2,
94
+ align_corners=False,
95
+ ):
96
+ super(UpSampleLayer, self).__init__()
97
+ self.mode = mode
98
+ self.size = val2list(size, 2) if size is not None else None
99
+ self.factor = None if self.size is not None else factor
100
+ self.align_corners = align_corners
101
+
102
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
103
+ return resize(x, self.size, self.factor, self.mode, self.align_corners)
104
+
105
+
106
+ class OpSequential(nn.Module):
107
+ def __init__(self, op_list):
108
+ super(OpSequential, self).__init__()
109
+ valid_op_list = []
110
+ for op in op_list:
111
+ if op is not None:
112
+ valid_op_list.append(op)
113
+ self.op_list = nn.ModuleList(valid_op_list)
114
+
115
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
116
+ for op in self.op_list:
117
+ x = op(x)
118
+ return x
utils/edge_sam/modeling/image_encoder.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from typing import Optional, Tuple, Type
12
+
13
+ from .common import LayerNorm2d, MLPBlock
14
+
15
+
16
+ # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
17
+ class ImageEncoderViT(nn.Module):
18
+ def __init__(
19
+ self,
20
+ img_size: int = 1024,
21
+ patch_size: int = 16,
22
+ in_chans: int = 3,
23
+ embed_dim: int = 768,
24
+ depth: int = 12,
25
+ num_heads: int = 12,
26
+ mlp_ratio: float = 4.0,
27
+ out_chans: int = 256,
28
+ qkv_bias: bool = True,
29
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
30
+ act_layer: Type[nn.Module] = nn.GELU,
31
+ use_abs_pos: bool = True,
32
+ use_rel_pos: bool = False,
33
+ rel_pos_zero_init: bool = True,
34
+ window_size: int = 0,
35
+ global_attn_indexes: Tuple[int, ...] = (),
36
+ ) -> None:
37
+ """
38
+ Args:
39
+ img_size (int): Input image size.
40
+ patch_size (int): Patch size.
41
+ in_chans (int): Number of input image channels.
42
+ embed_dim (int): Patch embedding dimension.
43
+ depth (int): Depth of ViT.
44
+ num_heads (int): Number of attention heads in each ViT block.
45
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
46
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
47
+ norm_layer (nn.Module): Normalization layer.
48
+ act_layer (nn.Module): Activation layer.
49
+ use_abs_pos (bool): If True, use absolute positional embeddings.
50
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
51
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
52
+ window_size (int): Window size for window attention blocks.
53
+ global_attn_indexes (list): Indexes for blocks using global attention.
54
+ """
55
+ super().__init__()
56
+ self.img_size = img_size
57
+
58
+ self.patch_embed = PatchEmbed(
59
+ kernel_size=(patch_size, patch_size),
60
+ stride=(patch_size, patch_size),
61
+ in_chans=in_chans,
62
+ embed_dim=embed_dim,
63
+ )
64
+
65
+ self.pos_embed: Optional[nn.Parameter] = None
66
+ if use_abs_pos:
67
+ # Initialize absolute positional embedding with pretrain image size.
68
+ self.pos_embed = nn.Parameter(
69
+ torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
70
+ )
71
+
72
+ self.blocks = nn.ModuleList()
73
+ for i in range(depth):
74
+ block = Block(
75
+ dim=embed_dim,
76
+ num_heads=num_heads,
77
+ mlp_ratio=mlp_ratio,
78
+ qkv_bias=qkv_bias,
79
+ norm_layer=norm_layer,
80
+ act_layer=act_layer,
81
+ use_rel_pos=use_rel_pos,
82
+ rel_pos_zero_init=rel_pos_zero_init,
83
+ window_size=window_size if i not in global_attn_indexes else 0,
84
+ input_size=(img_size // patch_size, img_size // patch_size),
85
+ )
86
+ self.blocks.append(block)
87
+
88
+ self.neck = nn.Sequential(
89
+ nn.Conv2d(
90
+ embed_dim,
91
+ out_chans,
92
+ kernel_size=1,
93
+ bias=False,
94
+ ),
95
+ LayerNorm2d(out_chans),
96
+ nn.Conv2d(
97
+ out_chans,
98
+ out_chans,
99
+ kernel_size=3,
100
+ padding=1,
101
+ bias=False,
102
+ ),
103
+ LayerNorm2d(out_chans),
104
+ )
105
+
106
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
107
+ x = self.patch_embed(x)
108
+ if self.pos_embed is not None:
109
+ x = x + self.pos_embed
110
+
111
+ for blk in self.blocks:
112
+ x = blk(x)
113
+
114
+ x = self.neck(x.permute(0, 3, 1, 2))
115
+
116
+ return x
117
+
118
+
119
+ class Block(nn.Module):
120
+ """Transformer blocks with support of window attention and residual propagation blocks"""
121
+
122
+ def __init__(
123
+ self,
124
+ dim: int,
125
+ num_heads: int,
126
+ mlp_ratio: float = 4.0,
127
+ qkv_bias: bool = True,
128
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
129
+ act_layer: Type[nn.Module] = nn.GELU,
130
+ use_rel_pos: bool = False,
131
+ rel_pos_zero_init: bool = True,
132
+ window_size: int = 0,
133
+ input_size: Optional[Tuple[int, int]] = None,
134
+ ) -> None:
135
+ """
136
+ Args:
137
+ dim (int): Number of input channels.
138
+ num_heads (int): Number of attention heads in each ViT block.
139
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
140
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
141
+ norm_layer (nn.Module): Normalization layer.
142
+ act_layer (nn.Module): Activation layer.
143
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
144
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
145
+ window_size (int): Window size for window attention blocks. If it equals 0, then
146
+ use global attention.
147
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
148
+ positional parameter size.
149
+ """
150
+ super().__init__()
151
+ self.norm1 = norm_layer(dim)
152
+ self.attn = Attention(
153
+ dim,
154
+ num_heads=num_heads,
155
+ qkv_bias=qkv_bias,
156
+ use_rel_pos=use_rel_pos,
157
+ rel_pos_zero_init=rel_pos_zero_init,
158
+ input_size=input_size if window_size == 0 else (window_size, window_size),
159
+ )
160
+
161
+ self.norm2 = norm_layer(dim)
162
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
163
+
164
+ self.window_size = window_size
165
+
166
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
167
+ shortcut = x
168
+ x = self.norm1(x)
169
+ # Window partition
170
+ if self.window_size > 0:
171
+ H, W = x.shape[1], x.shape[2]
172
+ x, pad_hw = window_partition(x, self.window_size)
173
+
174
+ x = self.attn(x)
175
+ # Reverse window partition
176
+ if self.window_size > 0:
177
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
178
+
179
+ x = shortcut + x
180
+ x = x + self.mlp(self.norm2(x))
181
+
182
+ return x
183
+
184
+
185
+ class Attention(nn.Module):
186
+ """Multi-head Attention block with relative position embeddings."""
187
+
188
+ def __init__(
189
+ self,
190
+ dim: int,
191
+ num_heads: int = 8,
192
+ qkv_bias: bool = True,
193
+ use_rel_pos: bool = False,
194
+ rel_pos_zero_init: bool = True,
195
+ input_size: Optional[Tuple[int, int]] = None,
196
+ ) -> None:
197
+ """
198
+ Args:
199
+ dim (int): Number of input channels.
200
+ num_heads (int): Number of attention heads.
201
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
202
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
203
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
204
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
205
+ positional parameter size.
206
+ """
207
+ super().__init__()
208
+ self.num_heads = num_heads
209
+ head_dim = dim // num_heads
210
+ self.scale = head_dim**-0.5
211
+
212
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
213
+ self.proj = nn.Linear(dim, dim)
214
+
215
+ self.use_rel_pos = use_rel_pos
216
+ if self.use_rel_pos:
217
+ assert (
218
+ input_size is not None
219
+ ), "Input size must be provided if using relative positional encoding."
220
+ # initialize relative positional embeddings
221
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
222
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
223
+
224
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
225
+ B, H, W, _ = x.shape
226
+ # qkv with shape (3, B, nHead, H * W, C)
227
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
228
+ # q, k, v with shape (B * nHead, H * W, C)
229
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
230
+
231
+ attn = (q * self.scale) @ k.transpose(-2, -1)
232
+
233
+ if self.use_rel_pos:
234
+ attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
235
+
236
+ attn = attn.softmax(dim=-1)
237
+ x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
238
+ x = self.proj(x)
239
+
240
+ return x
241
+
242
+
243
+ def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
244
+ """
245
+ Partition into non-overlapping windows with padding if needed.
246
+ Args:
247
+ x (tensor): input tokens with [B, H, W, C].
248
+ window_size (int): window size.
249
+
250
+ Returns:
251
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
252
+ (Hp, Wp): padded height and width before partition
253
+ """
254
+ B, H, W, C = x.shape
255
+
256
+ pad_h = (window_size - H % window_size) % window_size
257
+ pad_w = (window_size - W % window_size) % window_size
258
+ if pad_h > 0 or pad_w > 0:
259
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
260
+ Hp, Wp = H + pad_h, W + pad_w
261
+
262
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
263
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
264
+ return windows, (Hp, Wp)
265
+
266
+
267
+ def window_unpartition(
268
+ windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
269
+ ) -> torch.Tensor:
270
+ """
271
+ Window unpartition into original sequences and removing padding.
272
+ Args:
273
+ windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
274
+ window_size (int): window size.
275
+ pad_hw (Tuple): padded height and width (Hp, Wp).
276
+ hw (Tuple): original height and width (H, W) before padding.
277
+
278
+ Returns:
279
+ x: unpartitioned sequences with [B, H, W, C].
280
+ """
281
+ Hp, Wp = pad_hw
282
+ H, W = hw
283
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
284
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
285
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
286
+
287
+ if Hp > H or Wp > W:
288
+ x = x[:, :H, :W, :].contiguous()
289
+ return x
290
+
291
+
292
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
293
+ """
294
+ Get relative positional embeddings according to the relative positions of
295
+ query and key sizes.
296
+ Args:
297
+ q_size (int): size of query q.
298
+ k_size (int): size of key k.
299
+ rel_pos (Tensor): relative position embeddings (L, C).
300
+
301
+ Returns:
302
+ Extracted positional embeddings according to relative positions.
303
+ """
304
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
305
+ # Interpolate rel pos if needed.
306
+ if rel_pos.shape[0] != max_rel_dist:
307
+ # Interpolate rel pos.
308
+ rel_pos_resized = F.interpolate(
309
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
310
+ size=max_rel_dist,
311
+ mode="linear",
312
+ )
313
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
314
+ else:
315
+ rel_pos_resized = rel_pos
316
+
317
+ # Scale the coords with short length if shapes for q and k are different.
318
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
319
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
320
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
321
+
322
+ return rel_pos_resized[relative_coords.long()]
323
+
324
+
325
+ def add_decomposed_rel_pos(
326
+ attn: torch.Tensor,
327
+ q: torch.Tensor,
328
+ rel_pos_h: torch.Tensor,
329
+ rel_pos_w: torch.Tensor,
330
+ q_size: Tuple[int, int],
331
+ k_size: Tuple[int, int],
332
+ ) -> torch.Tensor:
333
+ """
334
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
335
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
336
+ Args:
337
+ attn (Tensor): attention map.
338
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
339
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
340
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
341
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
342
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
343
+
344
+ Returns:
345
+ attn (Tensor): attention map with added relative positional embeddings.
346
+ """
347
+ q_h, q_w = q_size
348
+ k_h, k_w = k_size
349
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
350
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
351
+
352
+ B, _, dim = q.shape
353
+ r_q = q.reshape(B, q_h, q_w, dim)
354
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
355
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
356
+
357
+ attn = (
358
+ attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
359
+ ).view(B, q_h * q_w, k_h * k_w)
360
+
361
+ return attn
362
+
363
+
364
+ class PatchEmbed(nn.Module):
365
+ """
366
+ Image to Patch Embedding.
367
+ """
368
+
369
+ def __init__(
370
+ self,
371
+ kernel_size: Tuple[int, int] = (16, 16),
372
+ stride: Tuple[int, int] = (16, 16),
373
+ padding: Tuple[int, int] = (0, 0),
374
+ in_chans: int = 3,
375
+ embed_dim: int = 768,
376
+ ) -> None:
377
+ """
378
+ Args:
379
+ kernel_size (Tuple): kernel size of the projection layer.
380
+ stride (Tuple): stride of the projection layer.
381
+ padding (Tuple): padding size of the projection layer.
382
+ in_chans (int): Number of input image channels.
383
+ embed_dim (int): Patch embedding dimension.
384
+ """
385
+ super().__init__()
386
+
387
+ self.proj = nn.Conv2d(
388
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
389
+ )
390
+
391
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
392
+ x = self.proj(x)
393
+ # B C H W -> B H W C
394
+ x = x.permute(0, 2, 3, 1)
395
+ return x
utils/edge_sam/modeling/mask_decoder.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+
11
+ from typing import List, Tuple, Type
12
+
13
+ from .common import LayerNorm2d
14
+
15
+
16
+ class MaskDecoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ *,
20
+ transformer_dim: int,
21
+ transformer: nn.Module,
22
+ num_multimask_outputs: int = 3,
23
+ activation: Type[nn.Module] = nn.GELU,
24
+ iou_head_depth: int = 3,
25
+ iou_head_hidden_dim: int = 256,
26
+ ) -> None:
27
+ """
28
+ Predicts masks given an image and prompt embeddings, using a
29
+ transformer architecture.
30
+
31
+ Arguments:
32
+ transformer_dim (int): the channel dimension of the transformer
33
+ transformer (nn.Module): the transformer used to predict masks
34
+ num_multimask_outputs (int): the number of masks to predict
35
+ when disambiguating masks
36
+ activation (nn.Module): the type of activation to use when
37
+ upscaling masks
38
+ iou_head_depth (int): the depth of the MLP used to predict
39
+ mask quality
40
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
41
+ used to predict mask quality
42
+ """
43
+ super().__init__()
44
+ self.transformer_dim = transformer_dim
45
+ self.transformer = transformer
46
+
47
+ self.num_multimask_outputs = num_multimask_outputs
48
+
49
+ self.iou_token = nn.Embedding(1, transformer_dim)
50
+ self.num_mask_tokens = num_multimask_outputs + 1
51
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
52
+
53
+ self.output_upscaling = nn.Sequential(
54
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
55
+ LayerNorm2d(transformer_dim // 4),
56
+ activation(),
57
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
58
+ activation(),
59
+ )
60
+ self.output_hypernetworks_mlps = nn.ModuleList(
61
+ [
62
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
63
+ for i in range(self.num_mask_tokens)
64
+ ]
65
+ )
66
+
67
+ self.iou_prediction_head = MLP(
68
+ transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
69
+ )
70
+
71
+ def forward(
72
+ self,
73
+ image_embeddings: torch.Tensor,
74
+ image_pe: torch.Tensor,
75
+ sparse_prompt_embeddings: torch.Tensor,
76
+ dense_prompt_embeddings: torch.Tensor,
77
+ num_multimask_outputs: int,
78
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
79
+ """
80
+ Predict masks given image and prompt embeddings.
81
+
82
+ Arguments:
83
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
84
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
85
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
86
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
87
+ num_multimask_outputs (int): the number of masks to predict
88
+ when disambiguating masks
89
+
90
+ Returns:
91
+ torch.Tensor: batched predicted masks
92
+ torch.Tensor: batched predictions of mask quality
93
+ """
94
+ masks, iou_pred = self.predict_masks(
95
+ image_embeddings=image_embeddings,
96
+ image_pe=image_pe,
97
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
98
+ dense_prompt_embeddings=dense_prompt_embeddings,
99
+ )
100
+
101
+ # Select the correct mask or masks for output
102
+ if num_multimask_outputs == 4:
103
+ mask_slice = slice(0, None)
104
+ elif num_multimask_outputs == 3:
105
+ mask_slice = slice(1, None)
106
+ elif num_multimask_outputs == 1:
107
+ mask_slice = slice(0, 1)
108
+ else:
109
+ raise ValueError
110
+
111
+ masks = masks[:, mask_slice, :, :]
112
+ iou_pred = iou_pred[:, mask_slice]
113
+
114
+ # Prepare output
115
+ return masks, iou_pred
116
+
117
+ def predict_masks(
118
+ self,
119
+ image_embeddings: torch.Tensor,
120
+ image_pe: torch.Tensor,
121
+ sparse_prompt_embeddings: torch.Tensor,
122
+ dense_prompt_embeddings: torch.Tensor,
123
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
124
+ """Predicts masks. See 'forward' for more details."""
125
+ # Concatenate output tokens
126
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
127
+ output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
128
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
129
+
130
+ # Expand per-image data in batch direction to be per-mask
131
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
132
+ src = src + dense_prompt_embeddings
133
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
134
+ b, c, h, w = src.shape
135
+
136
+ # Run the transformer
137
+ hs, src = self.transformer(src, pos_src, tokens)
138
+ iou_token_out = hs[:, 0, :]
139
+ mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
140
+
141
+ # Upscale mask embeddings and predict masks using the mask tokens
142
+ src = src.transpose(1, 2).view(b, c, h, w)
143
+ upscaled_embedding = self.output_upscaling(src)
144
+ hyper_in_list: List[torch.Tensor] = []
145
+ for i in range(self.num_mask_tokens):
146
+ hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
147
+ hyper_in = torch.stack(hyper_in_list, dim=1)
148
+ b, c, h, w = upscaled_embedding.shape
149
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
150
+
151
+ # Generate mask quality predictions
152
+ iou_pred = self.iou_prediction_head(iou_token_out)
153
+
154
+ return masks, iou_pred
155
+
156
+
157
+ # Lightly adapted from
158
+ # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
159
+ class MLP(nn.Module):
160
+ def __init__(
161
+ self,
162
+ input_dim: int,
163
+ hidden_dim: int,
164
+ output_dim: int,
165
+ num_layers: int,
166
+ sigmoid_output: bool = False,
167
+ ) -> None:
168
+ super().__init__()
169
+ self.num_layers = num_layers
170
+ h = [hidden_dim] * (num_layers - 1)
171
+ self.layers = nn.ModuleList(
172
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
173
+ )
174
+ self.sigmoid_output = sigmoid_output
175
+
176
+ def forward(self, x):
177
+ for i, layer in enumerate(self.layers):
178
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
179
+ if self.sigmoid_output:
180
+ x = F.sigmoid(x)
181
+ return x
utils/edge_sam/modeling/prompt_encoder.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch import nn
10
+
11
+ from typing import Any, Optional, Tuple, Type
12
+
13
+ from .common import LayerNorm2d
14
+
15
+
16
+ class PromptEncoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ embed_dim: int,
20
+ image_embedding_size: Tuple[int, int],
21
+ input_image_size: Tuple[int, int],
22
+ mask_in_chans: int,
23
+ activation: Type[nn.Module] = nn.GELU,
24
+ ) -> None:
25
+ """
26
+ Encodes prompts for input to SAM's mask decoder.
27
+
28
+ Arguments:
29
+ embed_dim (int): The prompts' embedding dimension
30
+ image_embedding_size (tuple(int, int)): The spatial size of the
31
+ image embedding, as (H, W).
32
+ input_image_size (int): The padded size of the image as input
33
+ to the image encoder, as (H, W).
34
+ mask_in_chans (int): The number of hidden channels used for
35
+ encoding input masks.
36
+ activation (nn.Module): The activation to use when encoding
37
+ input masks.
38
+ """
39
+ super().__init__()
40
+ self.embed_dim = embed_dim
41
+ self.input_image_size = input_image_size
42
+ self.image_embedding_size = image_embedding_size
43
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
44
+
45
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
46
+ point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
47
+ self.point_embeddings = nn.ModuleList(point_embeddings)
48
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
49
+
50
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
51
+ self.mask_downscaling = nn.Sequential(
52
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
53
+ LayerNorm2d(mask_in_chans // 4),
54
+ activation(),
55
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
56
+ LayerNorm2d(mask_in_chans),
57
+ activation(),
58
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
59
+ )
60
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
61
+
62
+ def get_dense_pe(self) -> torch.Tensor:
63
+ """
64
+ Returns the positional encoding used to encode point prompts,
65
+ applied to a dense set of points the shape of the image encoding.
66
+
67
+ Returns:
68
+ torch.Tensor: Positional encoding with shape
69
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
70
+ """
71
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
72
+
73
+ def _embed_points(
74
+ self,
75
+ points: torch.Tensor,
76
+ labels: torch.Tensor,
77
+ pad: bool,
78
+ ) -> torch.Tensor:
79
+ """Embeds point prompts."""
80
+ points = points + 0.5 # Shift to center of pixel
81
+ if pad:
82
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
83
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
84
+ points = torch.cat([points, padding_point], dim=1)
85
+ labels = torch.cat([labels, padding_label], dim=1)
86
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
87
+ point_embedding[labels == -1] = 0.0
88
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
89
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
90
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
91
+ return point_embedding
92
+
93
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
94
+ """Embeds box prompts."""
95
+ boxes = boxes + 0.5 # Shift to center of pixel
96
+ coords = boxes.reshape(-1, 2, 2)
97
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
98
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
99
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
100
+ return corner_embedding
101
+
102
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
103
+ """Embeds mask inputs."""
104
+ mask_embedding = self.mask_downscaling(masks)
105
+ return mask_embedding
106
+
107
+ def _get_batch_size(
108
+ self,
109
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
110
+ boxes: Optional[torch.Tensor],
111
+ masks: Optional[torch.Tensor],
112
+ ) -> int:
113
+ """
114
+ Gets the batch size of the output given the batch size of the input prompts.
115
+ """
116
+ if points is not None:
117
+ return points[0].shape[0]
118
+ elif boxes is not None:
119
+ return boxes.shape[0]
120
+ elif masks is not None:
121
+ return masks.shape[0]
122
+ else:
123
+ return 1
124
+
125
+ def _get_device(self) -> torch.device:
126
+ return self.point_embeddings[0].weight.device
127
+
128
+ def forward(
129
+ self,
130
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
131
+ boxes: Optional[torch.Tensor],
132
+ masks: Optional[torch.Tensor],
133
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
134
+ """
135
+ Embeds different types of prompts, returning both sparse and dense
136
+ embeddings.
137
+
138
+ Arguments:
139
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
140
+ and labels to embed.
141
+ boxes (torch.Tensor or none): boxes to embed
142
+ masks (torch.Tensor or none): masks to embed
143
+
144
+ Returns:
145
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
146
+ BxNx(embed_dim), where N is determined by the number of input points
147
+ and boxes.
148
+ torch.Tensor: dense embeddings for the masks, in the shape
149
+ Bx(embed_dim)x(embed_H)x(embed_W)
150
+ """
151
+ bs = self._get_batch_size(points, boxes, masks)
152
+ sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
153
+ if points is not None:
154
+ coords, labels = points
155
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
156
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
157
+ if boxes is not None:
158
+ box_embeddings = self._embed_boxes(boxes)
159
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
160
+
161
+ if masks is not None:
162
+ dense_embeddings = self._embed_masks(masks)
163
+ else:
164
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
165
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
166
+ )
167
+
168
+ return sparse_embeddings, dense_embeddings
169
+
170
+
171
+ class PositionEmbeddingRandom(nn.Module):
172
+ """
173
+ Positional encoding using random spatial frequencies.
174
+ """
175
+
176
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
177
+ super().__init__()
178
+ if scale is None or scale <= 0.0:
179
+ scale = 1.0
180
+ self.register_buffer(
181
+ "positional_encoding_gaussian_matrix",
182
+ scale * torch.randn((2, num_pos_feats)),
183
+ )
184
+
185
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
186
+ """Positionally encode points that are normalized to [0,1]."""
187
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
188
+ coords = 2 * coords - 1
189
+ coords = coords @ self.positional_encoding_gaussian_matrix
190
+ coords = 2 * np.pi * coords
191
+ # outputs d_1 x ... x d_n x C shape
192
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
193
+
194
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
195
+ """Generate positional encoding for a grid of the specified size."""
196
+ h, w = size
197
+ device: Any = self.positional_encoding_gaussian_matrix.device
198
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
199
+ y_embed = grid.cumsum(dim=0) - 0.5
200
+ x_embed = grid.cumsum(dim=1) - 0.5
201
+ y_embed = y_embed / h
202
+ x_embed = x_embed / w
203
+
204
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
205
+ return pe.permute(2, 0, 1) # C x H x W
206
+
207
+ def forward_with_coords(
208
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
209
+ ) -> torch.Tensor:
210
+ """Positionally encode points that are not normalized to [0,1]."""
211
+ coords = coords_input.clone()
212
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
213
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
214
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
utils/edge_sam/modeling/rep_vit.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from edge_sam.modeling.common import LayerNorm2d, UpSampleLayer, OpSequential
3
+
4
+ __all__ = ['rep_vit_m1', 'rep_vit_m2', 'rep_vit_m3', 'RepViT']
5
+
6
+ m1_cfgs = [
7
+ # k, t, c, SE, HS, s
8
+ [3, 2, 48, 1, 0, 1],
9
+ [3, 2, 48, 0, 0, 1],
10
+ [3, 2, 48, 0, 0, 1],
11
+ [3, 2, 96, 0, 0, 2],
12
+ [3, 2, 96, 1, 0, 1],
13
+ [3, 2, 96, 0, 0, 1],
14
+ [3, 2, 96, 0, 0, 1],
15
+ [3, 2, 192, 0, 1, 2],
16
+ [3, 2, 192, 1, 1, 1],
17
+ [3, 2, 192, 0, 1, 1],
18
+ [3, 2, 192, 1, 1, 1],
19
+ [3, 2, 192, 0, 1, 1],
20
+ [3, 2, 192, 1, 1, 1],
21
+ [3, 2, 192, 0, 1, 1],
22
+ [3, 2, 192, 1, 1, 1],
23
+ [3, 2, 192, 0, 1, 1],
24
+ [3, 2, 192, 1, 1, 1],
25
+ [3, 2, 192, 0, 1, 1],
26
+ [3, 2, 192, 1, 1, 1],
27
+ [3, 2, 192, 0, 1, 1],
28
+ [3, 2, 192, 1, 1, 1],
29
+ [3, 2, 192, 0, 1, 1],
30
+ [3, 2, 192, 0, 1, 1],
31
+ [3, 2, 384, 0, 1, 2],
32
+ [3, 2, 384, 1, 1, 1],
33
+ [3, 2, 384, 0, 1, 1]
34
+ ]
35
+
36
+ m2_cfgs = [
37
+ # k, t, c, SE, HS, s
38
+ [3, 2, 64, 1, 0, 1],
39
+ [3, 2, 64, 0, 0, 1],
40
+ [3, 2, 64, 0, 0, 1],
41
+ [3, 2, 128, 0, 0, 2],
42
+ [3, 2, 128, 1, 0, 1],
43
+ [3, 2, 128, 0, 0, 1],
44
+ [3, 2, 128, 0, 0, 1],
45
+ [3, 2, 256, 0, 1, 2],
46
+ [3, 2, 256, 1, 1, 1],
47
+ [3, 2, 256, 0, 1, 1],
48
+ [3, 2, 256, 1, 1, 1],
49
+ [3, 2, 256, 0, 1, 1],
50
+ [3, 2, 256, 1, 1, 1],
51
+ [3, 2, 256, 0, 1, 1],
52
+ [3, 2, 256, 1, 1, 1],
53
+ [3, 2, 256, 0, 1, 1],
54
+ [3, 2, 256, 1, 1, 1],
55
+ [3, 2, 256, 0, 1, 1],
56
+ [3, 2, 256, 1, 1, 1],
57
+ [3, 2, 256, 0, 1, 1],
58
+ [3, 2, 256, 0, 1, 1],
59
+ [3, 2, 512, 0, 1, 2],
60
+ [3, 2, 512, 1, 1, 1],
61
+ [3, 2, 512, 0, 1, 1]
62
+ ]
63
+
64
+ m3_cfgs = [
65
+ # k, t, c, SE, HS, s
66
+ [3, 2, 64, 1, 0, 1],
67
+ [3, 2, 64, 0, 0, 1],
68
+ [3, 2, 64, 1, 0, 1],
69
+ [3, 2, 64, 0, 0, 1],
70
+ [3, 2, 64, 0, 0, 1],
71
+ [3, 2, 128, 0, 0, 2],
72
+ [3, 2, 128, 1, 0, 1],
73
+ [3, 2, 128, 0, 0, 1],
74
+ [3, 2, 128, 1, 0, 1],
75
+ [3, 2, 128, 0, 0, 1],
76
+ [3, 2, 128, 0, 0, 1],
77
+ [3, 2, 256, 0, 1, 2],
78
+ [3, 2, 256, 1, 1, 1],
79
+ [3, 2, 256, 0, 1, 1],
80
+ [3, 2, 256, 1, 1, 1],
81
+ [3, 2, 256, 0, 1, 1],
82
+ [3, 2, 256, 1, 1, 1],
83
+ [3, 2, 256, 0, 1, 1],
84
+ [3, 2, 256, 1, 1, 1],
85
+ [3, 2, 256, 0, 1, 1],
86
+ [3, 2, 256, 1, 1, 1],
87
+ [3, 2, 256, 0, 1, 1],
88
+ [3, 2, 256, 1, 1, 1],
89
+ [3, 2, 256, 0, 1, 1],
90
+ [3, 2, 256, 1, 1, 1],
91
+ [3, 2, 256, 0, 1, 1],
92
+ [3, 2, 256, 1, 1, 1],
93
+ [3, 2, 256, 0, 1, 1],
94
+ [3, 2, 256, 1, 1, 1],
95
+ [3, 2, 256, 0, 1, 1],
96
+ [3, 2, 256, 0, 1, 1],
97
+ [3, 2, 512, 0, 1, 2],
98
+ [3, 2, 512, 1, 1, 1],
99
+ [3, 2, 512, 0, 1, 1]
100
+ ]
101
+
102
+
103
+ def _make_divisible(v, divisor, min_value=None):
104
+ """
105
+ This function is taken from the original tf repo.
106
+ It ensures that all layers have a channel number that is divisible by 8
107
+ It can be seen here:
108
+ https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
109
+ :param v:
110
+ :param divisor:
111
+ :param min_value:
112
+ :return:
113
+ """
114
+ if min_value is None:
115
+ min_value = divisor
116
+ new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
117
+ # Make sure that round down does not go down by more than 10%.
118
+ if new_v < 0.9 * v:
119
+ new_v += divisor
120
+ return new_v
121
+
122
+
123
+ from timm.models.layers import SqueezeExcite
124
+
125
+ import torch
126
+
127
+
128
+ class Conv2d_BN(torch.nn.Sequential):
129
+ def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1,
130
+ groups=1, bn_weight_init=1, resolution=-10000):
131
+ super().__init__()
132
+ self.add_module('c', torch.nn.Conv2d(
133
+ a, b, ks, stride, pad, dilation, groups, bias=False))
134
+ self.add_module('bn', torch.nn.BatchNorm2d(b))
135
+ torch.nn.init.constant_(self.bn.weight, bn_weight_init)
136
+ torch.nn.init.constant_(self.bn.bias, 0)
137
+
138
+ @torch.no_grad()
139
+ def fuse(self):
140
+ c, bn = self._modules.values()
141
+ w = bn.weight / (bn.running_var + bn.eps) ** 0.5
142
+ w = c.weight * w[:, None, None, None]
143
+ b = bn.bias - bn.running_mean * bn.weight / \
144
+ (bn.running_var + bn.eps) ** 0.5
145
+ m = torch.nn.Conv2d(w.size(1) * self.c.groups, w.size(
146
+ 0), w.shape[2:], stride=self.c.stride, padding=self.c.padding, dilation=self.c.dilation,
147
+ groups=self.c.groups,
148
+ device=c.weight.device)
149
+ m.weight.data.copy_(w)
150
+ m.bias.data.copy_(b)
151
+ return m
152
+
153
+
154
+ class Residual(torch.nn.Module):
155
+ def __init__(self, m, drop=0.):
156
+ super().__init__()
157
+ self.m = m
158
+ self.drop = drop
159
+
160
+ def forward(self, x):
161
+ if self.training and self.drop > 0:
162
+ return x + self.m(x) * torch.rand(x.size(0), 1, 1, 1,
163
+ device=x.device).ge_(self.drop).div(1 - self.drop).detach()
164
+ else:
165
+ return x + self.m(x)
166
+
167
+ @torch.no_grad()
168
+ def fuse(self):
169
+ if isinstance(self.m, Conv2d_BN):
170
+ m = self.m.fuse()
171
+ assert (m.groups == m.in_channels)
172
+ identity = torch.ones(m.weight.shape[0], m.weight.shape[1], 1, 1)
173
+ identity = torch.nn.functional.pad(identity, [1, 1, 1, 1])
174
+ m.weight += identity.to(m.weight.device)
175
+ return m
176
+ elif isinstance(self.m, torch.nn.Conv2d):
177
+ m = self.m
178
+ assert (m.groups != m.in_channels)
179
+ identity = torch.ones(m.weight.shape[0], m.weight.shape[1], 1, 1)
180
+ identity = torch.nn.functional.pad(identity, [1, 1, 1, 1])
181
+ m.weight += identity.to(m.weight.device)
182
+ return m
183
+ else:
184
+ return self
185
+
186
+
187
+ class RepVGGDW(torch.nn.Module):
188
+ def __init__(self, ed) -> None:
189
+ super().__init__()
190
+ self.conv = Conv2d_BN(ed, ed, 3, 1, 1, groups=ed)
191
+ self.conv1 = Conv2d_BN(ed, ed, 1, 1, 0, groups=ed)
192
+ self.dim = ed
193
+
194
+ def forward(self, x):
195
+ return self.conv(x) + self.conv1(x) + x
196
+
197
+ @torch.no_grad()
198
+ def fuse(self):
199
+ conv = self.conv.fuse()
200
+ conv1 = self.conv1.fuse()
201
+
202
+ conv_w = conv.weight
203
+ conv_b = conv.bias
204
+ conv1_w = conv1.weight
205
+ conv1_b = conv1.bias
206
+
207
+ conv1_w = torch.nn.functional.pad(conv1_w, [1, 1, 1, 1])
208
+
209
+ identity = torch.nn.functional.pad(torch.ones(conv1_w.shape[0], conv1_w.shape[1], 1, 1, device=conv1_w.device),
210
+ [1, 1, 1, 1])
211
+
212
+ final_conv_w = conv_w + conv1_w + identity
213
+ final_conv_b = conv_b + conv1_b
214
+
215
+ conv.weight.data.copy_(final_conv_w)
216
+ conv.bias.data.copy_(final_conv_b)
217
+ return conv
218
+
219
+
220
+ class RepViTBlock(nn.Module):
221
+ def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se, use_hs, skip_downsample=False):
222
+ super(RepViTBlock, self).__init__()
223
+ assert stride in [1, 2]
224
+
225
+ self.identity = stride == 1 and inp == oup
226
+ assert (hidden_dim == 2 * inp)
227
+
228
+ if stride == 2:
229
+ if skip_downsample:
230
+ stride = 1
231
+ self.token_mixer = nn.Sequential(
232
+ Conv2d_BN(inp, inp, kernel_size, stride, (kernel_size - 1) // 2, groups=inp),
233
+ SqueezeExcite(inp, 0.25) if use_se else nn.Identity(),
234
+ Conv2d_BN(inp, oup, ks=1, stride=1, pad=0)
235
+ )
236
+ self.channel_mixer = Residual(nn.Sequential(
237
+ # pw
238
+ Conv2d_BN(oup, 2 * oup, 1, 1, 0),
239
+ nn.GELU() if use_hs else nn.GELU(),
240
+ # pw-linear
241
+ Conv2d_BN(2 * oup, oup, 1, 1, 0, bn_weight_init=0),
242
+ ))
243
+ else:
244
+ assert (self.identity)
245
+ self.token_mixer = nn.Sequential(
246
+ RepVGGDW(inp),
247
+ SqueezeExcite(inp, 0.25) if use_se else nn.Identity(),
248
+ )
249
+ self.channel_mixer = Residual(nn.Sequential(
250
+ # pw
251
+ Conv2d_BN(inp, hidden_dim, 1, 1, 0),
252
+ nn.GELU() if use_hs else nn.GELU(),
253
+ # pw-linear
254
+ Conv2d_BN(hidden_dim, oup, 1, 1, 0, bn_weight_init=0),
255
+ ))
256
+
257
+ def forward(self, x):
258
+ return self.channel_mixer(self.token_mixer(x))
259
+
260
+
261
+ from timm.models.vision_transformer import trunc_normal_
262
+
263
+
264
+ class BN_Linear(torch.nn.Sequential):
265
+ def __init__(self, a, b, bias=True, std=0.02):
266
+ super().__init__()
267
+ self.add_module('bn', torch.nn.BatchNorm1d(a))
268
+ self.add_module('l', torch.nn.Linear(a, b, bias=bias))
269
+ trunc_normal_(self.l.weight, std=std)
270
+ if bias:
271
+ torch.nn.init.constant_(self.l.bias, 0)
272
+
273
+ @torch.no_grad()
274
+ def fuse(self):
275
+ bn, l = self._modules.values()
276
+ w = bn.weight / (bn.running_var + bn.eps) ** 0.5
277
+ b = bn.bias - self.bn.running_mean * \
278
+ self.bn.weight / (bn.running_var + bn.eps) ** 0.5
279
+ w = l.weight * w[None, :]
280
+ if l.bias is None:
281
+ b = b @ self.l.weight.T
282
+ else:
283
+ b = (l.weight @ b[:, None]).view(-1) + self.l.bias
284
+ m = torch.nn.Linear(w.size(1), w.size(0), device=l.weight.device)
285
+ m.weight.data.copy_(w)
286
+ m.bias.data.copy_(b)
287
+ return m
288
+
289
+
290
+ class RepViT(nn.Module):
291
+ arch_settings = {
292
+ 'm1': m1_cfgs,
293
+ 'm2': m2_cfgs,
294
+ 'm3': m3_cfgs
295
+ }
296
+
297
+ def __init__(self, arch, img_size=1024, upsample_mode='bicubic'):
298
+ super(RepViT, self).__init__()
299
+ # setting of inverted residual blocks
300
+ self.cfgs = self.arch_settings[arch]
301
+ self.img_size = img_size
302
+
303
+ # building first layer
304
+ input_channel = self.cfgs[0][2]
305
+ patch_embed = torch.nn.Sequential(Conv2d_BN(3, input_channel // 2, 3, 2, 1), torch.nn.GELU(),
306
+ Conv2d_BN(input_channel // 2, input_channel, 3, 2, 1))
307
+ layers = [patch_embed]
308
+ # building inverted residual blocks
309
+ block = RepViTBlock
310
+ self.stage_idx = []
311
+ prev_c = input_channel
312
+ for idx, (k, t, c, use_se, use_hs, s) in enumerate(self.cfgs):
313
+ output_channel = _make_divisible(c, 8)
314
+ exp_size = _make_divisible(input_channel * t, 8)
315
+ skip_downsample = False
316
+ if c != prev_c:
317
+ self.stage_idx.append(idx - 1)
318
+ prev_c = c
319
+ layers.append(block(input_channel, exp_size, output_channel, k, s, use_se, use_hs, skip_downsample))
320
+ input_channel = output_channel
321
+ self.stage_idx.append(idx)
322
+ self.features = nn.ModuleList(layers)
323
+
324
+ stage2_channels = _make_divisible(self.cfgs[self.stage_idx[2]][2], 8)
325
+ stage3_channels = _make_divisible(self.cfgs[self.stage_idx[3]][2], 8)
326
+ self.fuse_stage2 = nn.Conv2d(stage2_channels, 256, kernel_size=1, bias=False)
327
+ self.fuse_stage3 = OpSequential([
328
+ nn.Conv2d(stage3_channels, 256, kernel_size=1, bias=False),
329
+ UpSampleLayer(factor=2, mode=upsample_mode),
330
+ ])
331
+
332
+ self.neck = nn.Sequential(
333
+ nn.Conv2d(256, 256, kernel_size=1, bias=False),
334
+ LayerNorm2d(256),
335
+ nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
336
+ LayerNorm2d(256),
337
+ )
338
+
339
+ def forward(self, x):
340
+ counter = 0
341
+ output_dict = dict()
342
+ # patch_embed
343
+ x = self.features[0](x)
344
+ output_dict['stem'] = x
345
+ # stages
346
+ for idx, f in enumerate(self.features[1:]):
347
+ x = f(x)
348
+ if idx in self.stage_idx:
349
+ output_dict[f'stage{counter}'] = x
350
+ counter += 1
351
+
352
+ x = self.fuse_stage2(output_dict['stage2']) + self.fuse_stage3(output_dict['stage3'])
353
+
354
+ x = self.neck(x)
355
+ return x
356
+
357
+
358
+ def rep_vit_m1(img_size=1024, **kwargs):
359
+ return RepViT('m1', img_size, **kwargs)
360
+
361
+
362
+ def rep_vit_m2(img_size=1024, **kwargs):
363
+ return RepViT('m2', img_size, **kwargs)
364
+
365
+
366
+ def rep_vit_m3(img_size=1024, **kwargs):
367
+ return RepViT('m3', img_size, **kwargs)
utils/edge_sam/modeling/sam.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+
11
+ from typing import Any, Dict, List, Tuple
12
+
13
+ from .image_encoder import ImageEncoderViT
14
+ from .mask_decoder import MaskDecoder
15
+ from .prompt_encoder import PromptEncoder
16
+ from ..utils.amg import calculate_stability_score
17
+
18
+
19
+ class Sam(nn.Module):
20
+ mask_threshold: float = 0.0
21
+ image_format: str = "RGB"
22
+ stability_score_offset: float = 1.0
23
+
24
+ def __init__(
25
+ self,
26
+ image_encoder: ImageEncoderViT,
27
+ prompt_encoder: PromptEncoder,
28
+ mask_decoder: MaskDecoder,
29
+ pixel_mean: List[float] = [123.675, 116.28, 103.53],
30
+ pixel_std: List[float] = [58.395, 57.12, 57.375],
31
+ ) -> None:
32
+ """
33
+ SAM predicts object masks from an image and input prompts.
34
+
35
+ Arguments:
36
+ image_encoder (ImageEncoderViT): The backbone used to encode the
37
+ image into image embeddings that allow for efficient mask prediction.
38
+ prompt_encoder (PromptEncoder): Encodes various types of input prompts.
39
+ mask_decoder (MaskDecoder): Predicts masks from the image embeddings
40
+ and encoded prompts.
41
+ pixel_mean (list(float)): Mean values for normalizing pixels in the input image.
42
+ pixel_std (list(float)): Std values for normalizing pixels in the input image.
43
+ """
44
+ super().__init__()
45
+ self.image_encoder = image_encoder
46
+ self.prompt_encoder = prompt_encoder
47
+ self.mask_decoder = mask_decoder
48
+ self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False)
49
+ self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False)
50
+
51
+ @property
52
+ def device(self) -> Any:
53
+ return self.pixel_mean.device
54
+
55
+ @torch.no_grad()
56
+ def forward_dummy_encoder(self, x):
57
+ return self.image_encoder(x)
58
+
59
+ @torch.no_grad()
60
+ def forward(
61
+ self,
62
+ batched_input: List[Dict[str, Any]],
63
+ num_multimask_outputs: int = 1,
64
+ use_stability_score: bool = False
65
+ ) -> List[Dict[str, torch.Tensor]]:
66
+ """
67
+ Predicts masks end-to-end from provided images and prompts.
68
+ If prompts are not known in advance, using SamPredictor is
69
+ recommended over calling the model directly.
70
+
71
+ Arguments:
72
+ batched_input (list(dict)): A list over input images, each a
73
+ dictionary with the following keys. A prompt key can be
74
+ excluded if it is not present.
75
+ 'image': The image as a torch tensor in 3xHxW format,
76
+ already transformed for input to the model.
77
+ 'original_size': (tuple(int, int)) The original size of
78
+ the image before transformation, as (H, W).
79
+ 'point_coords': (torch.Tensor) Batched point prompts for
80
+ this image, with shape BxNx2. Already transformed to the
81
+ input frame of the model.
82
+ 'point_labels': (torch.Tensor) Batched labels for point prompts,
83
+ with shape BxN.
84
+ 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.
85
+ Already transformed to the input frame of the model.
86
+ 'mask_inputs': (torch.Tensor) Batched mask inputs to the model,
87
+ in the form Bx1xHxW.
88
+ num_multimask_outputs (int): the number of masks to predict
89
+ when disambiguating masks. Choices: 1, 3, 4.
90
+ use_stability_score (bool): If true, use stability scores to substitute
91
+ IoU predictions.
92
+
93
+ Returns:
94
+ (list(dict)): A list over input images, where each element is
95
+ as dictionary with the following keys.
96
+ 'masks': (torch.Tensor) Batched binary mask predictions,
97
+ with shape BxCxHxW, where B is the number of input prompts,
98
+ C is determined by multimask_output, and (H, W) is the
99
+ original size of the image.
100
+ 'iou_predictions': (torch.Tensor) The model's predictions
101
+ of mask quality, in shape BxC.
102
+ 'low_res_logits': (torch.Tensor) Low resolution logits with
103
+ shape BxCxHxW, where H=W=256. Can be passed as mask input
104
+ to subsequent iterations of prediction.
105
+ """
106
+ input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0)
107
+ image_embeddings = self.image_encoder(input_images)
108
+
109
+ outputs = []
110
+ for image_record, curr_embedding in zip(batched_input, image_embeddings):
111
+ if "point_coords" in image_record:
112
+ points = (image_record["point_coords"], image_record["point_labels"])
113
+ else:
114
+ points = None
115
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
116
+ points=points,
117
+ boxes=image_record.get("boxes", None),
118
+ masks=image_record.get("mask_inputs", None),
119
+ )
120
+ low_res_masks, iou_predictions = self.mask_decoder(
121
+ image_embeddings=curr_embedding.unsqueeze(0),
122
+ image_pe=self.prompt_encoder.get_dense_pe(),
123
+ sparse_prompt_embeddings=sparse_embeddings,
124
+ dense_prompt_embeddings=dense_embeddings,
125
+ num_multimask_outputs=num_multimask_outputs,
126
+ )
127
+ if use_stability_score:
128
+ iou_predictions = calculate_stability_score(
129
+ low_res_masks, self.mask_threshold, self.stability_score_offset
130
+ )
131
+ masks = self.postprocess_masks(
132
+ low_res_masks,
133
+ input_size=image_record["image"].shape[-2:],
134
+ original_size=image_record["original_size"],
135
+ )
136
+ masks = masks > self.mask_threshold
137
+ outputs.append(
138
+ {
139
+ "masks": masks,
140
+ "iou_predictions": iou_predictions,
141
+ "low_res_logits": low_res_masks,
142
+ }
143
+ )
144
+ return outputs
145
+
146
+ def postprocess_masks(
147
+ self,
148
+ masks: torch.Tensor,
149
+ input_size: Tuple[int, ...],
150
+ original_size: Tuple[int, ...],
151
+ ) -> torch.Tensor:
152
+ """
153
+ Remove padding and upscale masks to the original image size.
154
+
155
+ Arguments:
156
+ masks (torch.Tensor): Batched masks from the mask_decoder,
157
+ in BxCxHxW format.
158
+ input_size (tuple(int, int)): The size of the image input to the
159
+ model, in (H, W) format. Used to remove padding.
160
+ original_size (tuple(int, int)): The original size of the image
161
+ before resizing for input to the model, in (H, W) format.
162
+
163
+ Returns:
164
+ (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)
165
+ is given by original_size.
166
+ """
167
+ masks = F.interpolate(
168
+ masks,
169
+ (self.image_encoder.img_size, self.image_encoder.img_size),
170
+ mode="bilinear",
171
+ align_corners=False,
172
+ )
173
+ masks = masks[..., : input_size[0], : input_size[1]]
174
+ masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False)
175
+ return masks
176
+
177
+ def preprocess(self, x: torch.Tensor) -> torch.Tensor:
178
+ """Normalize pixel values and pad to a square input."""
179
+ # Normalize colors
180
+ x = (x - self.pixel_mean) / self.pixel_std
181
+
182
+ # Pad
183
+ h, w = x.shape[-2:]
184
+ padh = self.image_encoder.img_size - h
185
+ padw = self.image_encoder.img_size - w
186
+ x = F.pad(x, (0, padw, 0, padh))
187
+ return x
utils/edge_sam/modeling/transformer.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+
10
+ import math
11
+ from typing import Tuple, Type
12
+
13
+ from .common import MLPBlock
14
+
15
+
16
+ class TwoWayTransformer(nn.Module):
17
+ def __init__(
18
+ self,
19
+ depth: int,
20
+ embedding_dim: int,
21
+ num_heads: int,
22
+ mlp_dim: int,
23
+ activation: Type[nn.Module] = nn.ReLU,
24
+ attention_downsample_rate: int = 2,
25
+ ) -> None:
26
+ """
27
+ A transformer decoder that attends to an input image using
28
+ queries whose positional embedding is supplied.
29
+
30
+ Args:
31
+ depth (int): number of layers in the transformer
32
+ embedding_dim (int): the channel dimension for the input embeddings
33
+ num_heads (int): the number of heads for multihead attention. Must
34
+ divide embedding_dim
35
+ mlp_dim (int): the channel dimension internal to the MLP block
36
+ activation (nn.Module): the activation to use in the MLP block
37
+ """
38
+ super().__init__()
39
+ self.depth = depth
40
+ self.embedding_dim = embedding_dim
41
+ self.num_heads = num_heads
42
+ self.mlp_dim = mlp_dim
43
+ self.layers = nn.ModuleList()
44
+
45
+ for i in range(depth):
46
+ self.layers.append(
47
+ TwoWayAttentionBlock(
48
+ embedding_dim=embedding_dim,
49
+ num_heads=num_heads,
50
+ mlp_dim=mlp_dim,
51
+ activation=activation,
52
+ attention_downsample_rate=attention_downsample_rate,
53
+ skip_first_layer_pe=(i == 0),
54
+ )
55
+ )
56
+
57
+ self.final_attn_token_to_image = Attention(
58
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
59
+ )
60
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
61
+
62
+ def forward(
63
+ self,
64
+ image_embedding: Tensor,
65
+ image_pe: Tensor,
66
+ point_embedding: Tensor,
67
+ ) -> Tuple[Tensor, Tensor]:
68
+ """
69
+ Args:
70
+ image_embedding (torch.Tensor): image to attend to. Should be shape
71
+ B x embedding_dim x h x w for any h and w.
72
+ image_pe (torch.Tensor): the positional encoding to add to the image. Must
73
+ have the same shape as image_embedding.
74
+ point_embedding (torch.Tensor): the embedding to add to the query points.
75
+ Must have shape B x N_points x embedding_dim for any N_points.
76
+
77
+ Returns:
78
+ torch.Tensor: the processed point_embedding
79
+ torch.Tensor: the processed image_embedding
80
+ """
81
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
82
+ bs, c, h, w = image_embedding.shape
83
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
84
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
85
+
86
+ # Prepare queries
87
+ queries = point_embedding
88
+ keys = image_embedding
89
+
90
+ # Apply transformer blocks and final layernorm
91
+ for layer in self.layers:
92
+ queries, keys = layer(
93
+ queries=queries,
94
+ keys=keys,
95
+ query_pe=point_embedding,
96
+ key_pe=image_pe,
97
+ )
98
+
99
+ # Apply the final attention layer from the points to the image
100
+ q = queries + point_embedding
101
+ k = keys + image_pe
102
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
103
+ queries = queries + attn_out
104
+ queries = self.norm_final_attn(queries)
105
+
106
+ return queries, keys
107
+
108
+
109
+ class TwoWayAttentionBlock(nn.Module):
110
+ def __init__(
111
+ self,
112
+ embedding_dim: int,
113
+ num_heads: int,
114
+ mlp_dim: int = 2048,
115
+ activation: Type[nn.Module] = nn.ReLU,
116
+ attention_downsample_rate: int = 2,
117
+ skip_first_layer_pe: bool = False,
118
+ ) -> None:
119
+ """
120
+ A transformer block with four layers: (1) self-attention of sparse
121
+ inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
122
+ block on sparse inputs, and (4) cross attention of dense inputs to sparse
123
+ inputs.
124
+
125
+ Arguments:
126
+ embedding_dim (int): the channel dimension of the embeddings
127
+ num_heads (int): the number of heads in the attention layers
128
+ mlp_dim (int): the hidden dimension of the mlp block
129
+ activation (nn.Module): the activation of the mlp block
130
+ skip_first_layer_pe (bool): skip the PE on the first layer
131
+ """
132
+ super().__init__()
133
+ self.self_attn = Attention(embedding_dim, num_heads)
134
+ self.norm1 = nn.LayerNorm(embedding_dim)
135
+
136
+ self.cross_attn_token_to_image = Attention(
137
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
138
+ )
139
+ self.norm2 = nn.LayerNorm(embedding_dim)
140
+
141
+ self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
142
+ self.norm3 = nn.LayerNorm(embedding_dim)
143
+
144
+ self.norm4 = nn.LayerNorm(embedding_dim)
145
+ self.cross_attn_image_to_token = Attention(
146
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
147
+ )
148
+
149
+ self.skip_first_layer_pe = skip_first_layer_pe
150
+
151
+ def forward(
152
+ self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
153
+ ) -> Tuple[Tensor, Tensor]:
154
+ # Self attention block
155
+ if self.skip_first_layer_pe:
156
+ queries = self.self_attn(q=queries, k=queries, v=queries)
157
+ else:
158
+ q = queries + query_pe
159
+ attn_out = self.self_attn(q=q, k=q, v=queries)
160
+ queries = queries + attn_out
161
+ queries = self.norm1(queries)
162
+
163
+ # Cross attention block, tokens attending to image embedding
164
+ q = queries + query_pe
165
+ k = keys + key_pe
166
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
167
+ queries = queries + attn_out
168
+ queries = self.norm2(queries)
169
+
170
+ # MLP block
171
+ mlp_out = self.mlp(queries)
172
+ queries = queries + mlp_out
173
+ queries = self.norm3(queries)
174
+
175
+ # Cross attention block, image embedding attending to tokens
176
+ q = queries + query_pe
177
+ k = keys + key_pe
178
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
179
+ keys = keys + attn_out
180
+ keys = self.norm4(keys)
181
+
182
+ return queries, keys
183
+
184
+
185
+ class Attention(nn.Module):
186
+ """
187
+ An attention layer that allows for downscaling the size of the embedding
188
+ after projection to queries, keys, and values.
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ embedding_dim: int,
194
+ num_heads: int,
195
+ downsample_rate: int = 1,
196
+ ) -> None:
197
+ super().__init__()
198
+ self.embedding_dim = embedding_dim
199
+ self.internal_dim = embedding_dim // downsample_rate
200
+ self.num_heads = num_heads
201
+ assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
202
+
203
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
204
+ self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
205
+ self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
206
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
207
+
208
+ def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
209
+ b, n, c = x.shape
210
+ x = x.reshape(b, n, num_heads, c // num_heads)
211
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
212
+
213
+ def _recombine_heads(self, x: Tensor) -> Tensor:
214
+ b, n_heads, n_tokens, c_per_head = x.shape
215
+ x = x.transpose(1, 2)
216
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
217
+
218
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
219
+ # Input projections
220
+ q = self.q_proj(q)
221
+ k = self.k_proj(k)
222
+ v = self.v_proj(v)
223
+
224
+ # Separate into heads
225
+ q = self._separate_heads(q, self.num_heads)
226
+ k = self._separate_heads(k, self.num_heads)
227
+ v = self._separate_heads(v, self.num_heads)
228
+
229
+ # Attention
230
+ _, _, _, c_per_head = q.shape
231
+ attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
232
+ attn = attn / math.sqrt(c_per_head)
233
+ attn = torch.softmax(attn, dim=-1)
234
+
235
+ # Get output
236
+ out = attn @ v
237
+ out = self._recombine_heads(out)
238
+ out = self.out_proj(out)
239
+
240
+ return out
utils/edge_sam/onnx/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .predictor_onnx import SamPredictorONNX
utils/edge_sam/onnx/predictor_onnx.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import cv2
9
+
10
+ import onnxruntime
11
+ from typing import Optional, Tuple
12
+
13
+ from ..utils.transforms import ResizeLongestSide
14
+
15
+
16
+ class SamPredictorONNX:
17
+ mask_threshold: float = 0.0
18
+ image_format: str = "RGB"
19
+ img_size = 1024
20
+ pixel_mean = np.array([123.675, 116.28, 103.53])[None, :, None, None]
21
+ pixel_std = np.array([58.395, 57.12, 57.375])[None, :, None, None]
22
+
23
+ def __init__(
24
+ self,
25
+ encoder_path: str,
26
+ decoder_path: str
27
+ ) -> None:
28
+ super().__init__()
29
+ self.encoder = onnxruntime.InferenceSession(encoder_path)
30
+ self.decoder = onnxruntime.InferenceSession(decoder_path)
31
+
32
+ # Set the execution provider to GPU if available
33
+ if 'CUDAExecutionProvider' in onnxruntime.get_available_providers():
34
+ self.encoder.set_providers(['CUDAExecutionProvider'])
35
+ self.decoder.set_providers(['CUDAExecutionProvider'])
36
+
37
+ self.transform = ResizeLongestSide(self.img_size)
38
+ self.reset_image()
39
+
40
+ def set_image(
41
+ self,
42
+ image: np.ndarray,
43
+ image_format: str = "RGB",
44
+ ) -> None:
45
+ assert image_format in [
46
+ "RGB",
47
+ "BGR",
48
+ ], f"image_format must be in ['RGB', 'BGR'], is {image_format}."
49
+ if image_format != self.image_format:
50
+ image = image[..., ::-1]
51
+
52
+ # Transform the image to the form expected by the model
53
+ input_image = self.transform.apply_image(image)
54
+ input_image = input_image.transpose(2, 0, 1)[None, :, :, :]
55
+ self.reset_image()
56
+ self.original_size = image.shape[:2]
57
+ self.input_size = tuple(input_image.shape[-2:])
58
+ input_image = self.preprocess(input_image).astype(np.float32)
59
+ outputs = self.encoder.run(None, {'image': input_image})
60
+ self.features = outputs[0]
61
+ self.is_image_set = True
62
+
63
+ return self.features
64
+
65
+ def predict(
66
+ self,
67
+ features: np.ndarray = None,
68
+ point_coords: Optional[np.ndarray] = None,
69
+ point_labels: Optional[np.ndarray] = None,
70
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
71
+ if features is None and not self.is_image_set:
72
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
73
+ if features is None:
74
+ features = self.features
75
+
76
+ point_coords = self.transform.apply_coords(point_coords, self.original_size)
77
+ outputs = self.decoder.run(None, {
78
+ 'image_embeddings': features,
79
+ 'point_coords': point_coords.astype(np.float32),
80
+ 'point_labels': point_labels.astype(np.float32)
81
+ })
82
+ scores, low_res_masks = outputs[0], outputs[1]
83
+ masks = self.postprocess_masks(low_res_masks)
84
+ masks = masks > self.mask_threshold
85
+
86
+ return masks, scores, low_res_masks
87
+
88
+ def reset_image(self) -> None:
89
+ """Resets the currently set image."""
90
+ self.is_image_set = False
91
+ self.features = None
92
+ self.orig_h = None
93
+ self.orig_w = None
94
+ self.input_h = None
95
+ self.input_w = None
96
+
97
+ def preprocess(self, x: np.ndarray):
98
+ x = (x - self.pixel_mean) / self.pixel_std
99
+ h, w = x.shape[-2:]
100
+ padh = self.img_size - h
101
+ padw = self.img_size - w
102
+ x = np.pad(x, ((0, 0), (0, 0), (0, padh), (0, padw)), mode='constant', constant_values=0)
103
+ return x
104
+
105
+ def postprocess_masks(self, mask: np.ndarray):
106
+ mask = mask.squeeze(0).transpose(1, 2, 0)
107
+ mask = cv2.resize(mask, (self.img_size, self.img_size), interpolation=cv2.INTER_LINEAR)
108
+ mask = mask[:self.input_size[0], :self.input_size[1], :]
109
+ mask = cv2.resize(mask, (self.original_size[1], self.original_size[0]), interpolation=cv2.INTER_LINEAR)
110
+ mask = mask.transpose(2, 0, 1)[None, :, :, :]
111
+ return mask
utils/edge_sam/predictor.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from edge_sam.modeling import Sam
11
+
12
+ from typing import Optional, Tuple
13
+
14
+ from .utils.transforms import ResizeLongestSide
15
+ from .utils.amg import calculate_stability_score
16
+
17
+
18
+ class SamPredictor:
19
+ def __init__(
20
+ self,
21
+ sam_model: Sam,
22
+ ) -> None:
23
+ """
24
+ Uses SAM to calculate the image embedding for an image, and then
25
+ allow repeated, efficient mask prediction given prompts.
26
+
27
+ Arguments:
28
+ sam_model (Sam): The model to use for mask prediction.
29
+ """
30
+ super().__init__()
31
+ self.model = sam_model
32
+ self.transform = ResizeLongestSide(sam_model.image_encoder.img_size)
33
+ self.stability_score_offset = 1.0
34
+ self.reset_image()
35
+
36
+ def set_image(
37
+ self,
38
+ image: np.ndarray,
39
+ image_format: str = "RGB",
40
+ ) -> torch.Tensor:
41
+ """
42
+ Calculates the image embeddings for the provided image, allowing
43
+ masks to be predicted with the 'predict' method.
44
+
45
+ Arguments:
46
+ image (np.ndarray): The image for calculating masks. Expects an
47
+ image in HWC uint8 format, with pixel values in [0, 255].
48
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
49
+ """
50
+ assert image_format in [
51
+ "RGB",
52
+ "BGR",
53
+ ], f"image_format must be in ['RGB', 'BGR'], is {image_format}."
54
+ if image_format != self.model.image_format:
55
+ image = image[..., ::-1]
56
+
57
+ # Transform the image to the form expected by the model
58
+ input_image = self.transform.apply_image(image)
59
+ input_image_torch = torch.as_tensor(input_image, device=self.device)
60
+ input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]
61
+
62
+ return self.set_torch_image(input_image_torch, image.shape[:2])
63
+
64
+ @torch.no_grad()
65
+ def set_torch_image(
66
+ self,
67
+ transformed_image: torch.Tensor,
68
+ original_image_size: Tuple[int, ...],
69
+ ) -> torch.Tensor:
70
+ """
71
+ Calculates the image embeddings for the provided image, allowing
72
+ masks to be predicted with the 'predict' method. Expects the input
73
+ image to be already transformed to the format expected by the model.
74
+
75
+ Arguments:
76
+ transformed_image (torch.Tensor): The input image, with shape
77
+ 1x3xHxW, which has been transformed with ResizeLongestSide.
78
+ original_image_size (tuple(int, int)): The size of the image
79
+ before transformation, in (H, W) format.
80
+ """
81
+ assert (
82
+ len(transformed_image.shape) == 4
83
+ and transformed_image.shape[1] == 3
84
+ and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size
85
+ ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}."
86
+ self.reset_image()
87
+
88
+ self.original_size = original_image_size
89
+ self.input_size = tuple(transformed_image.shape[-2:])
90
+ input_image = self.model.preprocess(transformed_image)
91
+ self.features = self.model.image_encoder(input_image)
92
+ self.is_image_set = True
93
+
94
+ return self.features
95
+
96
+ def predict(
97
+ self,
98
+ features: torch.Tensor = None,
99
+ point_coords: Optional[np.ndarray] = None,
100
+ point_labels: Optional[np.ndarray] = None,
101
+ box: Optional[np.ndarray] = None,
102
+ mask_input: Optional[np.ndarray] = None,
103
+ num_multimask_outputs: int = 3,
104
+ return_logits: bool = False,
105
+ use_stability_score: bool = False
106
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
107
+ """
108
+ Predict masks for the given input prompts, using the currently set image.
109
+
110
+ Arguments:
111
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
112
+ model. Each point is in (X,Y) in pixels.
113
+ point_labels (np.ndarray or None): A length N array of labels for the
114
+ point prompts. 1 indicates a foreground point and 0 indicates a
115
+ background point.
116
+ box (np.ndarray or None): A length 4 array given a box prompt to the
117
+ model, in XYXY format.
118
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
119
+ coming from a previous prediction iteration. Has form 1xHxW, where
120
+ for SAM, H=W=256.
121
+ num_multimask_outputs (int): the number of masks to predict
122
+ when disambiguating masks. Choices: 1, 3, 4.
123
+ return_logits (bool): If true, returns un-thresholded masks logits
124
+ instead of a binary mask.
125
+ use_stability_score (bool): If true, use stability scores to substitute
126
+ IoU predictions.
127
+
128
+ Returns:
129
+ (np.ndarray): The output masks in CxHxW format, where C is the
130
+ number of masks, and (H, W) is the original image size.
131
+ (np.ndarray): An array of length C containing the model's
132
+ predictions for the quality of each mask.
133
+ (np.ndarray): An array of shape CxHxW, where C is the number
134
+ of masks and H=W=256. These low resolution logits can be passed to
135
+ a subsequent iteration as mask input.
136
+ """
137
+ if features is None and not self.is_image_set:
138
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
139
+
140
+ if features is None:
141
+ features = self.features
142
+
143
+ # Transform input prompts
144
+ coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None
145
+ if point_coords is not None:
146
+ assert (
147
+ point_labels is not None
148
+ ), "point_labels must be supplied if point_coords is supplied."
149
+ point_coords = self.transform.apply_coords(point_coords, self.original_size)
150
+ coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)
151
+ labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
152
+ coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]
153
+ if box is not None:
154
+ box = self.transform.apply_boxes(box, self.original_size)
155
+ box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device)
156
+ box_torch = box_torch[None, :]
157
+ if mask_input is not None:
158
+ mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device)
159
+ mask_input_torch = mask_input_torch[None, :, :, :]
160
+
161
+ masks, iou_predictions, low_res_masks = self.predict_torch(
162
+ features,
163
+ coords_torch,
164
+ labels_torch,
165
+ box_torch,
166
+ mask_input_torch,
167
+ num_multimask_outputs,
168
+ return_logits=return_logits,
169
+ use_stability_score=use_stability_score
170
+ )
171
+
172
+ masks_np = masks[0].detach().cpu().numpy()
173
+ iou_predictions_np = iou_predictions[0].detach().cpu().numpy()
174
+ low_res_masks_np = low_res_masks[0].detach().cpu().numpy()
175
+ return masks_np, iou_predictions_np, low_res_masks_np
176
+
177
+ @torch.no_grad()
178
+ def predict_torch(
179
+ self,
180
+ features: torch.Tensor,
181
+ point_coords: Optional[torch.Tensor],
182
+ point_labels: Optional[torch.Tensor],
183
+ boxes: Optional[torch.Tensor] = None,
184
+ mask_input: Optional[torch.Tensor] = None,
185
+ num_multimask_outputs: int = 3,
186
+ return_logits: bool = False,
187
+ use_stability_score: bool = True
188
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
189
+ """
190
+ Predict masks for the given input prompts, using the currently set image.
191
+ Input prompts are batched torch tensors and are expected to already be
192
+ transformed to the input frame using ResizeLongestSide.
193
+
194
+ Arguments:
195
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
196
+ model. Each point is in (X,Y) in pixels.
197
+ point_labels (torch.Tensor or None): A BxN array of labels for the
198
+ point prompts. 1 indicates a foreground point and 0 indicates a
199
+ background point.
200
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
201
+ model, in XYXY format.
202
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
203
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
204
+ for SAM, H=W=256. Masks returned by a previous iteration of the
205
+ predict method do not need further transformation.
206
+ num_multimask_outputs (int): the number of masks to predict
207
+ when disambiguating masks. Choices: 1, 3, 4.
208
+ return_logits (bool): If true, returns un-thresholded masks logits
209
+ instead of a binary mask.
210
+ use_stability_score (bool): If true, use stability scores to substitute
211
+ IoU predictions.
212
+
213
+ Returns:
214
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
215
+ number of masks, and (H, W) is the original image size.
216
+ (torch.Tensor): An array of shape BxC containing the model's
217
+ predictions for the quality of each mask.
218
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
219
+ of masks and H=W=256. These low res logits can be passed to
220
+ a subsequent iteration as mask input.
221
+ """
222
+ if features is None and not self.is_image_set:
223
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
224
+
225
+ if point_coords is not None:
226
+ points = (point_coords, point_labels)
227
+ else:
228
+ points = None
229
+
230
+ # Embed prompts
231
+ sparse_embeddings, dense_embeddings = self.model.prompt_encoder(
232
+ points=points,
233
+ boxes=boxes,
234
+ masks=mask_input,
235
+ )
236
+
237
+ # Predict masks
238
+ low_res_masks, iou_predictions = self.model.mask_decoder(
239
+ image_embeddings=features,
240
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
241
+ sparse_prompt_embeddings=sparse_embeddings,
242
+ dense_prompt_embeddings=dense_embeddings,
243
+ num_multimask_outputs=num_multimask_outputs,
244
+ )
245
+
246
+ if use_stability_score:
247
+ iou_predictions = calculate_stability_score(
248
+ low_res_masks, self.model.mask_threshold, self.stability_score_offset
249
+ )
250
+
251
+ # Upscale the masks to the original image resolution
252
+ masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size)
253
+
254
+ if not return_logits:
255
+ masks = masks > self.model.mask_threshold
256
+
257
+ return masks, iou_predictions, low_res_masks
258
+
259
+ def get_image_embedding(self) -> torch.Tensor:
260
+ """
261
+ Returns the image embeddings for the currently set image, with
262
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
263
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
264
+ """
265
+ if not self.is_image_set:
266
+ raise RuntimeError(
267
+ "An image must be set with .set_image(...) to generate an embedding."
268
+ )
269
+ assert self.features is not None, "Features must exist if an image has been set."
270
+ return self.features
271
+
272
+ @property
273
+ def device(self) -> torch.device:
274
+ return self.model.device
275
+
276
+ def reset_image(self) -> None:
277
+ """Resets the currently set image."""
278
+ self.is_image_set = False
279
+ self.features = None
280
+ self.orig_h = None
281
+ self.orig_w = None
282
+ self.input_h = None
283
+ self.input_w = None
utils/edge_sam/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
utils/edge_sam/utils/amg.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ import math
11
+ from copy import deepcopy
12
+ from itertools import product
13
+ from typing import Any, Dict, Generator, ItemsView, List, Tuple
14
+
15
+
16
+ class MaskData:
17
+ """
18
+ A structure for storing masks and their related data in batched format.
19
+ Implements basic filtering and concatenation.
20
+ """
21
+
22
+ def __init__(self, **kwargs) -> None:
23
+ for v in kwargs.values():
24
+ assert isinstance(
25
+ v, (list, np.ndarray, torch.Tensor)
26
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
27
+ self._stats = dict(**kwargs)
28
+
29
+ def __setitem__(self, key: str, item: Any) -> None:
30
+ assert isinstance(
31
+ item, (list, np.ndarray, torch.Tensor)
32
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
33
+ self._stats[key] = item
34
+
35
+ def __delitem__(self, key: str) -> None:
36
+ del self._stats[key]
37
+
38
+ def __getitem__(self, key: str) -> Any:
39
+ return self._stats[key]
40
+
41
+ def items(self) -> ItemsView[str, Any]:
42
+ return self._stats.items()
43
+
44
+ def filter(self, keep: torch.Tensor) -> None:
45
+ for k, v in self._stats.items():
46
+ if v is None:
47
+ self._stats[k] = None
48
+ elif isinstance(v, torch.Tensor):
49
+ self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
50
+ elif isinstance(v, np.ndarray):
51
+ self._stats[k] = v[keep.detach().cpu().numpy()]
52
+ elif isinstance(v, list) and keep.dtype == torch.bool:
53
+ self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
54
+ elif isinstance(v, list):
55
+ self._stats[k] = [v[i] for i in keep]
56
+ else:
57
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
58
+
59
+ def cat(self, new_stats: "MaskData") -> None:
60
+ for k, v in new_stats.items():
61
+ if k not in self._stats or self._stats[k] is None:
62
+ self._stats[k] = deepcopy(v)
63
+ elif isinstance(v, torch.Tensor):
64
+ self._stats[k] = torch.cat([self._stats[k], v], dim=0)
65
+ elif isinstance(v, np.ndarray):
66
+ self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
67
+ elif isinstance(v, list):
68
+ self._stats[k] = self._stats[k] + deepcopy(v)
69
+ else:
70
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
71
+
72
+ def to_numpy(self) -> None:
73
+ for k, v in self._stats.items():
74
+ if isinstance(v, torch.Tensor):
75
+ self._stats[k] = v.detach().cpu().numpy()
76
+
77
+
78
+ def is_box_near_crop_edge(
79
+ boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
80
+ ) -> torch.Tensor:
81
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
82
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
83
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
84
+ boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
85
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
86
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
87
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
88
+ return torch.any(near_crop_edge, dim=1)
89
+
90
+
91
+ def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
92
+ box_xywh = deepcopy(box_xyxy)
93
+ box_xywh[2] = box_xywh[2] - box_xywh[0]
94
+ box_xywh[3] = box_xywh[3] - box_xywh[1]
95
+ return box_xywh
96
+
97
+
98
+ def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
99
+ assert len(args) > 0 and all(
100
+ len(a) == len(args[0]) for a in args
101
+ ), "Batched iteration must have inputs of all the same size."
102
+ n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
103
+ for b in range(n_batches):
104
+ yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
105
+
106
+
107
+ def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
108
+ """
109
+ Encodes masks to an uncompressed RLE, in the format expected by
110
+ pycoco tools.
111
+ """
112
+ # Put in fortran order and flatten h,w
113
+ b, h, w = tensor.shape
114
+ tensor = tensor.permute(0, 2, 1).flatten(1)
115
+
116
+ # Compute change indices
117
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
118
+ change_indices = diff.nonzero()
119
+
120
+ # Encode run length
121
+ out = []
122
+ for i in range(b):
123
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1]
124
+ cur_idxs = torch.cat(
125
+ [
126
+ torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
127
+ cur_idxs + 1,
128
+ torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
129
+ ]
130
+ )
131
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
132
+ counts = [] if tensor[i, 0] == 0 else [0]
133
+ counts.extend(btw_idxs.detach().cpu().tolist())
134
+ out.append({"size": [h, w], "counts": counts})
135
+ return out
136
+
137
+
138
+ def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
139
+ """Compute a binary mask from an uncompressed RLE."""
140
+ h, w = rle["size"]
141
+ mask = np.empty(h * w, dtype=bool)
142
+ idx = 0
143
+ parity = False
144
+ for count in rle["counts"]:
145
+ mask[idx : idx + count] = parity
146
+ idx += count
147
+ parity ^= True
148
+ mask = mask.reshape(w, h)
149
+ return mask.transpose() # Put in C order
150
+
151
+
152
+ def area_from_rle(rle: Dict[str, Any]) -> int:
153
+ return sum(rle["counts"][1::2])
154
+
155
+
156
+ def calculate_stability_score(
157
+ masks: torch.Tensor, mask_threshold: float, threshold_offset: float
158
+ ) -> torch.Tensor:
159
+ """
160
+ Computes the stability score for a batch of masks. The stability
161
+ score is the IoU between the binary masks obtained by thresholding
162
+ the predicted mask logits at high and low values.
163
+ """
164
+ # One mask is always contained inside the other.
165
+ # Save memory by preventing unnecessary cast to torch.int64
166
+ intersections = (
167
+ (masks > (mask_threshold + threshold_offset))
168
+ .sum(-1, dtype=torch.int16)
169
+ .sum(-1, dtype=torch.int32)
170
+ )
171
+ unions = (
172
+ (masks > (mask_threshold - threshold_offset))
173
+ .sum(-1, dtype=torch.int16)
174
+ .sum(-1, dtype=torch.int32)
175
+ )
176
+ return intersections / unions
177
+
178
+
179
+ def build_point_grid(n_per_side: int) -> np.ndarray:
180
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
181
+ offset = 1 / (2 * n_per_side)
182
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
183
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
184
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
185
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
186
+ return points
187
+
188
+
189
+ def build_all_layer_point_grids(
190
+ n_per_side: int, n_layers: int, scale_per_layer: int
191
+ ) -> List[np.ndarray]:
192
+ """Generates point grids for all crop layers."""
193
+ points_by_layer = []
194
+ for i in range(n_layers + 1):
195
+ n_points = int(n_per_side / (scale_per_layer**i))
196
+ points_by_layer.append(build_point_grid(n_points))
197
+ return points_by_layer
198
+
199
+
200
+ def generate_crop_boxes(
201
+ im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
202
+ ) -> Tuple[List[List[int]], List[int]]:
203
+ """
204
+ Generates a list of crop boxes of different sizes. Each layer
205
+ has (2**i)**2 boxes for the ith layer.
206
+ """
207
+ crop_boxes, layer_idxs = [], []
208
+ im_h, im_w = im_size
209
+ short_side = min(im_h, im_w)
210
+
211
+ # Original image
212
+ crop_boxes.append([0, 0, im_w, im_h])
213
+ layer_idxs.append(0)
214
+
215
+ def crop_len(orig_len, n_crops, overlap):
216
+ return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
217
+
218
+ for i_layer in range(n_layers):
219
+ n_crops_per_side = 2 ** (i_layer + 1)
220
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
221
+
222
+ crop_w = crop_len(im_w, n_crops_per_side, overlap)
223
+ crop_h = crop_len(im_h, n_crops_per_side, overlap)
224
+
225
+ crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
226
+ crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
227
+
228
+ # Crops in XYWH format
229
+ for x0, y0 in product(crop_box_x0, crop_box_y0):
230
+ box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
231
+ crop_boxes.append(box)
232
+ layer_idxs.append(i_layer + 1)
233
+
234
+ return crop_boxes, layer_idxs
235
+
236
+
237
+ def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
238
+ x0, y0, _, _ = crop_box
239
+ offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
240
+ # Check if boxes has a channel dimension
241
+ if len(boxes.shape) == 3:
242
+ offset = offset.unsqueeze(1)
243
+ return boxes + offset
244
+
245
+
246
+ def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
247
+ x0, y0, _, _ = crop_box
248
+ offset = torch.tensor([[x0, y0]], device=points.device)
249
+ # Check if points has a channel dimension
250
+ if len(points.shape) == 3:
251
+ offset = offset.unsqueeze(1)
252
+ return points + offset
253
+
254
+
255
+ def uncrop_masks(
256
+ masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
257
+ ) -> torch.Tensor:
258
+ x0, y0, x1, y1 = crop_box
259
+ if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
260
+ return masks
261
+ # Coordinate transform masks
262
+ pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
263
+ pad = (x0, pad_x - x0, y0, pad_y - y0)
264
+ return torch.nn.functional.pad(masks, pad, value=0)
265
+
266
+
267
+ def remove_small_regions(
268
+ mask: np.ndarray, area_thresh: float, mode: str
269
+ ) -> Tuple[np.ndarray, bool]:
270
+ """
271
+ Removes small disconnected regions and holes in a mask. Returns the
272
+ mask and an indicator of if the mask has been modified.
273
+ """
274
+ import cv2 # type: ignore
275
+
276
+ assert mode in ["holes", "islands"]
277
+ correct_holes = mode == "holes"
278
+ working_mask = (correct_holes ^ mask).astype(np.uint8)
279
+ n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
280
+ sizes = stats[:, -1][1:] # Row 0 is background label
281
+ small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
282
+ if len(small_regions) == 0:
283
+ return mask, False
284
+ fill_labels = [0] + small_regions
285
+ if not correct_holes:
286
+ fill_labels = [i for i in range(n_labels) if i not in fill_labels]
287
+ # If every region is below threshold, keep largest
288
+ if len(fill_labels) == 0:
289
+ fill_labels = [int(np.argmax(sizes)) + 1]
290
+ mask = np.isin(regions, fill_labels)
291
+ return mask, True
292
+
293
+
294
+ def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
295
+ from pycocotools import mask as mask_utils # type: ignore
296
+
297
+ h, w = uncompressed_rle["size"]
298
+ rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
299
+ rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
300
+ return rle
301
+
302
+
303
+ def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
304
+ """
305
+ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
306
+ an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
307
+ """
308
+ # torch.max below raises an error on empty inputs, just skip in this case
309
+ if torch.numel(masks) == 0:
310
+ return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
311
+
312
+ # Normalize shape to CxHxW
313
+ shape = masks.shape
314
+ h, w = shape[-2:]
315
+ if len(shape) > 2:
316
+ masks = masks.flatten(0, -3)
317
+ else:
318
+ masks = masks.unsqueeze(0)
319
+
320
+ # Get top and bottom edges
321
+ in_height, _ = torch.max(masks, dim=-1)
322
+ in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
323
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
324
+ in_height_coords = in_height_coords + h * (~in_height)
325
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
326
+
327
+ # Get left and right edges
328
+ in_width, _ = torch.max(masks, dim=-2)
329
+ in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
330
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
331
+ in_width_coords = in_width_coords + w * (~in_width)
332
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
333
+
334
+ # If the mask is empty the right edge will be to the left of the left edge.
335
+ # Replace these boxes with [0, 0, 0, 0]
336
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
337
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
338
+ out = out * (~empty_filter).unsqueeze(-1)
339
+
340
+ # Return to original shape
341
+ if len(shape) > 2:
342
+ out = out.reshape(*shape[:-2], 4)
343
+ else:
344
+ out = out[0]
345
+
346
+ return out
utils/edge_sam/utils/coreml.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from ..modeling import Sam
4
+ from .amg import calculate_stability_score
5
+
6
+
7
+ class SamCoreMLModel(nn.Module):
8
+ """
9
+ This model should not be called directly, but is used in CoreML export.
10
+ """
11
+
12
+ def __init__(
13
+ self,
14
+ model: Sam,
15
+ use_stability_score: bool = False
16
+ ) -> None:
17
+ super().__init__()
18
+ self.mask_decoder = model.mask_decoder
19
+ self.model = model
20
+ self.img_size = model.image_encoder.img_size
21
+ self.use_stability_score = use_stability_score
22
+ self.stability_score_offset = 1.0
23
+
24
+ def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor:
25
+ point_coords = point_coords + 0.5
26
+ point_coords = point_coords / self.img_size
27
+ point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords)
28
+ point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding)
29
+
30
+ point_embedding = point_embedding * (point_labels != -1)
31
+ point_embedding = point_embedding + self.model.prompt_encoder.not_a_point_embed.weight * (
32
+ point_labels == -1
33
+ )
34
+
35
+ for i in range(self.model.prompt_encoder.num_point_embeddings):
36
+ point_embedding = point_embedding + self.model.prompt_encoder.point_embeddings[
37
+ i
38
+ ].weight * (point_labels == i)
39
+
40
+ return point_embedding
41
+
42
+ @torch.no_grad()
43
+ def forward(
44
+ self,
45
+ image_embeddings: torch.Tensor,
46
+ point_coords: torch.Tensor,
47
+ point_labels: torch.Tensor,
48
+ ):
49
+ sparse_embedding = self._embed_points(point_coords, point_labels)
50
+ dense_embedding = self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1)
51
+
52
+ masks, scores = self.model.mask_decoder.predict_masks(
53
+ image_embeddings=image_embeddings,
54
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
55
+ sparse_prompt_embeddings=sparse_embedding,
56
+ dense_prompt_embeddings=dense_embedding,
57
+ )
58
+
59
+ if self.use_stability_score:
60
+ scores = calculate_stability_score(
61
+ masks, self.model.mask_threshold, self.stability_score_offset
62
+ )
63
+
64
+ return scores, masks
utils/edge_sam/utils/transforms.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch.nn import functional as F
10
+ from torchvision.transforms.functional import resize, to_pil_image # type: ignore
11
+
12
+ from copy import deepcopy
13
+ from typing import Tuple
14
+
15
+
16
+ class ResizeLongestSide:
17
+ """
18
+ Resizes images to the longest side 'target_length', as well as provides
19
+ methods for resizing coordinates and boxes. Provides methods for
20
+ transforming both numpy array and batched torch tensors.
21
+ """
22
+
23
+ def __init__(self, target_length: int) -> None:
24
+ self.target_length = target_length
25
+
26
+ def apply_image(self, image: np.ndarray) -> np.ndarray:
27
+ """
28
+ Expects a numpy array with shape HxWxC in uint8 format.
29
+ """
30
+ target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
31
+ return np.array(resize(to_pil_image(image), target_size))
32
+
33
+ def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
34
+ """
35
+ Expects a numpy array of length 2 in the final dimension. Requires the
36
+ original image size in (H, W) format.
37
+ """
38
+ old_h, old_w = original_size
39
+ new_h, new_w = self.get_preprocess_shape(
40
+ original_size[0], original_size[1], self.target_length
41
+ )
42
+ coords = deepcopy(coords).astype(float)
43
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
44
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
45
+ return coords
46
+
47
+ def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
48
+ """
49
+ Expects a numpy array shape Bx4. Requires the original image size
50
+ in (H, W) format.
51
+ """
52
+ boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)
53
+ return boxes.reshape(-1, 4)
54
+
55
+ def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:
56
+ """
57
+ Expects batched images with shape BxCxHxW and float format. This
58
+ transformation may not exactly match apply_image. apply_image is
59
+ the transformation expected by the model.
60
+ """
61
+ # Expects an image in BCHW format. May not exactly match apply_image.
62
+ target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length)
63
+ return F.interpolate(
64
+ image, target_size, mode="bilinear", align_corners=False, antialias=True
65
+ )
66
+
67
+ def apply_coords_torch(
68
+ self, coords: torch.Tensor, original_size: Tuple[int, ...]
69
+ ) -> torch.Tensor:
70
+ """
71
+ Expects a torch tensor with length 2 in the last dimension. Requires the
72
+ original image size in (H, W) format.
73
+ """
74
+ old_h, old_w = original_size
75
+ new_h, new_w = self.get_preprocess_shape(
76
+ original_size[0], original_size[1], self.target_length
77
+ )
78
+ coords = deepcopy(coords).to(torch.float)
79
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
80
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
81
+ return coords
82
+
83
+ def apply_boxes_torch(
84
+ self, boxes: torch.Tensor, original_size: Tuple[int, ...]
85
+ ) -> torch.Tensor:
86
+ """
87
+ Expects a torch tensor with shape Bx4. Requires the original image
88
+ size in (H, W) format.
89
+ """
90
+ boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)
91
+ return boxes.reshape(-1, 4)
92
+
93
+ @staticmethod
94
+ def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:
95
+ """
96
+ Compute the output size given input size and target long side length.
97
+ """
98
+ scale = long_side_length * 1.0 / max(oldh, oldw)
99
+ newh, neww = oldh * scale, oldw * scale
100
+ neww = int(neww + 0.5)
101
+ newh = int(newh + 0.5)
102
+ return (newh, neww)
utils/fastSAM.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ def FastSAM_points_inference(
4
+ input,
5
+ input_size=1024,
6
+ iou_threshold=0.7,
7
+ conf_threshold=0.25,
8
+ better_quality=False,
9
+ withContours=True,
10
+ use_retina=True,
11
+ mask_random_color=True,
12
+ ):
13
+ global global_points
14
+ global global_point_label
15
+ input = Image.fromarray(input)
16
+ input_size = int(input_size) # 确保 imgsz 是整数
17
+ # Thanks for the suggestion by hysts in HuggingFace.
18
+ w, h = input.size
19
+ scale = input_size / max(w, h)
20
+ new_w = int(w * scale)
21
+ new_h = int(h * scale)
22
+ input = input.resize((new_w, new_h))
23
+
24
+ scaled_points = [[int(x * scale) for x in point] for point in global_points]
25
+
26
+ results = FASTSAM_MODEL(input,
27
+ device=DEVICE,
28
+ retina_masks=True,
29
+ iou=iou_threshold,
30
+ conf=conf_threshold,
31
+ imgsz=input_size,)
32
+
33
+ results = format_results(results[0], 0)
34
+ annotations, _ = point_prompt(results, scaled_points, global_point_label, new_h, new_w)
35
+ annotations = np.array([annotations])
36
+
37
+ fig = fast_process(annotations=annotations,
38
+ image=input,
39
+ device=DEVICE,
40
+ scale=(1024 // input_size),
41
+ better_quality=better_quality,
42
+ mask_random_color=mask_random_color,
43
+ bbox=None,
44
+ use_retina=use_retina,
45
+ withContours=withContours,)
46
+
47
+ global_points = []
48
+ global_point_label = []
49
+
50
+ return fig
utils/tools.py CHANGED
@@ -5,9 +5,14 @@ import matplotlib.pyplot as plt
5
  import cv2
6
  import torch
7
  import os
 
8
  import sys
9
  import clip
10
 
 
 
 
 
11
 
12
  def convert_box_xywh_to_xyxy(box):
13
  if len(box) == 4:
 
5
  import cv2
6
  import torch
7
  import os
8
+ import io
9
  import sys
10
  import clip
11
 
12
+ def pil_to_bytes(pil_image):
13
+ buffer = io.BytesIO()
14
+ pil_image.save(buffer, format="PNG") # or other format like "JPEG"
15
+ return buffer.getvalue()
16
 
17
  def convert_box_xywh_to_xyxy(box):
18
  if len(box) == 4:
weights/edge_sam.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:439b086a20ab6fba90c12cba32e0001ba3aa726da5791ff8738acdd440330991
3
+ size 38807540
weights/edge_sam_3x.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a3e3261da9e2f4c8154410885689ae57d09cbf4cf5d0c848b9d80b6df336ece
3
+ size 38807540
weights/edge_sam_3x_decoder.mlpackage.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8a278c28ee831e1a43e6f8e1ea5f2c9f0dd7dc4965ef6126204958217fcff7e
3
+ size 9158303
weights/edge_sam_3x_decoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83a2174d54571596913dcb7455d021e713623c3dca30a31c8c41ab98c9fb0863
3
+ size 15937006
weights/edge_sam_3x_encoder.mlpackage.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c749659493a12948937a845cc9c0578930c3532ebbdbaf64c71a32c7a3a6dec
3
+ size 10294845
weights/edge_sam_3x_encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:719a498cf5b3fe9be9f01ee513e13d3915f9028aa4f23dfd30eaaa0a17143159
3
+ size 22098300
weights/edge_sam_decoder.mlpackage.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5b1f12242e4a181bbce0c1df0334083ccae8b71d6bd729d6e6bb0837e0f75e2
3
+ size 9161751
weights/edge_sam_decoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e820af76837271db87478851603c6ce855906ca96baae2238217c2d5a38e0926
3
+ size 15937006
weights/edge_sam_encoder.mlpackage.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d011879601db71e95c578f3a9c3a26b8eb0e42e97896784da28d17b43da7e87e
3
+ size 10290888
weights/edge_sam_encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c051e69a2a16ca8f5e09583ca18420ef0e75a67387dd90228ac9438f7f01357a
3
+ size 22098300