Master-Shi commited on
Commit
122ad07
·
verified ·
1 Parent(s): 8d09c2d

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/__init__.py +1 -0
  2. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/agent_core.py +563 -0
  3. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/client_llm.py +205 -0
  4. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/client_sam3.py +138 -0
  5. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/__init__.py +1 -0
  6. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/boxes.py +438 -0
  7. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/color_map.py +150 -0
  8. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/keypoints.py +244 -0
  9. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/mask_overlap_removal.py +128 -0
  10. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/masks.py +560 -0
  11. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/memory.py +87 -0
  12. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/rle.py +122 -0
  13. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/roi_align.py +75 -0
  14. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/rotated_boxes.py +533 -0
  15. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/som_utils.py +406 -0
  16. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/visualizer.py +1662 -0
  17. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/zoom_in.py +195 -0
  18. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/system_prompts/system_prompt.txt +242 -0
  19. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/system_prompts/system_prompt_iterative_checking.txt +26 -0
  20. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/viz.py +114 -0
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/agent_core.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+
7
+ import cv2
8
+ from PIL import Image
9
+
10
+ from .client_llm import send_generate_request
11
+ from .client_sam3 import call_sam_service
12
+ from .viz import visualize
13
+
14
+
15
+ def save_debug_messages(messages_list, debug, debug_folder_path, debug_jsonl_path):
16
+ """Save messages to debug jsonl file if debug is enabled"""
17
+ if debug and debug_jsonl_path:
18
+ # Ensure the debug directory exists before writing
19
+ os.makedirs(debug_folder_path, exist_ok=True)
20
+ with open(debug_jsonl_path, "w") as f:
21
+ for msg in messages_list:
22
+ f.write(json.dumps(msg, indent=4) + "\n")
23
+
24
+
25
+ def cleanup_debug_files(debug, debug_folder_path, debug_jsonl_path):
26
+ """Clean up debug files when function successfully returns"""
27
+ if debug and debug_folder_path:
28
+ try:
29
+ if os.path.exists(debug_jsonl_path):
30
+ os.remove(debug_jsonl_path)
31
+ if os.path.exists(debug_folder_path):
32
+ os.rmdir(debug_folder_path)
33
+ except Exception as e:
34
+ print(f"Warning: Could not clean up debug files: {e}")
35
+
36
+
37
+ def count_images(messages):
38
+ """Count the total number of images present in the messages history."""
39
+ total = 0
40
+ for message in messages:
41
+ # Check if message has content (should be a list)
42
+ if "content" in message and isinstance(message["content"], list):
43
+ # Iterate through each content item
44
+ for content_item in message["content"]:
45
+ # Check if content item is a dict with type "image"
46
+ if (
47
+ isinstance(content_item, dict)
48
+ and content_item.get("type") == "image"
49
+ ):
50
+ total += 1
51
+ return total
52
+
53
+
54
+ def _prune_messages_for_next_round(
55
+ messages_list,
56
+ used_text_prompts,
57
+ latest_sam3_text_prompt,
58
+ img_path,
59
+ initial_text_prompt,
60
+ ):
61
+ """Return a new messages list that contains only:
62
+ 1) messages[:2] (with optional warning text added to the second message's content)
63
+ 2) the latest assistant message (and everything after it) that contains a segment_phrase tool call
64
+ """
65
+ # There should not be more than 10 messages in the conversation history
66
+ assert len(messages_list) < 10
67
+
68
+ # Part 1: always keep the first two message JSONs
69
+ part1 = copy.deepcopy(messages_list[:2])
70
+
71
+ # Part 2: search backwards for the latest assistant message containing a segment_phrase tool call
72
+ part2_start_idx = None
73
+ for idx in range(len(messages_list) - 1, 1, -1):
74
+ msg = messages_list[idx]
75
+ # We only consider assistant messages with a "content" list
76
+ if msg.get("role") != "assistant" or "content" not in msg:
77
+ continue
78
+ # Look for any content element that is a text containing the segment_phrase tool call
79
+ for content in msg["content"]:
80
+ if (
81
+ isinstance(content, dict)
82
+ and content.get("type") == "text"
83
+ and "<tool>" in content.get("text", "")
84
+ and "segment_phrase" in content.get("text", "")
85
+ ):
86
+ part2_start_idx = idx
87
+ break
88
+ if part2_start_idx is not None:
89
+ break
90
+
91
+ part2 = messages_list[part2_start_idx:] if part2_start_idx is not None else []
92
+
93
+ # Part 3: decide whether to add warning text to the second message in part1
94
+ previously_used = (
95
+ [p for p in used_text_prompts if p != latest_sam3_text_prompt]
96
+ if latest_sam3_text_prompt
97
+ else list(used_text_prompts)
98
+ )
99
+ if part2 and len(previously_used) > 0:
100
+ warning_text = f'Note that we have previously called the segment_phrase tool with each "text_prompt" in this list: {list(previously_used)}, but none of the generated results were satisfactory. So make sure that you do not use any of these phrases as the "text_prompt" to call the segment_phrase tool again.'
101
+ # Replace the second message entirely to keep exactly 2 content items
102
+ part1[1] = {
103
+ "role": "user",
104
+ "content": [
105
+ {"type": "image", "image": img_path},
106
+ {
107
+ "type": "text",
108
+ "text": f"The above image is the raw input image. The initial user input query is: '{initial_text_prompt}'."
109
+ + " "
110
+ + warning_text,
111
+ },
112
+ ],
113
+ }
114
+ assert len(part1[1]["content"]) == 2
115
+
116
+ # Build the new messages list: part1 (with optional warning), then part2
117
+ new_messages = list(part1)
118
+ new_messages.extend(part2)
119
+ return new_messages
120
+
121
+
122
+ def agent_inference(
123
+ img_path: str,
124
+ initial_text_prompt: str,
125
+ debug: bool = False,
126
+ send_generate_request=send_generate_request,
127
+ call_sam_service=call_sam_service,
128
+ max_generations: int = 100,
129
+ output_dir="../../sam3_agent_out",
130
+ ):
131
+ """
132
+ Given a text prompt and an image, this tool will perform all aspects of agentic problem solving,
133
+ while saving sam3 and MLLM outputs to their respective directories.
134
+
135
+ Args:
136
+ img_path: Path to the input image
137
+ initial_text_prompt: Initial text prompt from the user
138
+ debug: Whether to enable debug mode
139
+ max_generations: Maximum number of send_generate_request calls allowed (default: 100)
140
+ """
141
+ # setup dir
142
+ sam_output_dir = os.path.join(output_dir, "sam_out")
143
+ error_save_dir = os.path.join(output_dir, "none_out")
144
+ debug_save_dir = os.path.join(output_dir, "agent_debug_out")
145
+ os.makedirs(sam_output_dir, exist_ok=True)
146
+ os.makedirs(error_save_dir, exist_ok=True)
147
+ os.makedirs(debug_save_dir, exist_ok=True)
148
+ current_dir = os.path.dirname(os.path.abspath(__file__))
149
+ MLLM_SYSTEM_PROMPT_PATH = os.path.join(
150
+ current_dir, "system_prompts/system_prompt.txt"
151
+ )
152
+ ITERATIVE_CHECKING_SYSTEM_PROMPT_PATH = os.path.join(
153
+ current_dir, "system_prompts/system_prompt_iterative_checking.txt"
154
+ )
155
+ # init variables
156
+ PATH_TO_LATEST_OUTPUT_JSON = ""
157
+ LATEST_SAM3_TEXT_PROMPT = ""
158
+ USED_TEXT_PROMPTS = (
159
+ set()
160
+ ) # Track all previously used text prompts for segment_phrase
161
+ generation_count = 0 # Counter for number of send_generate_request calls
162
+
163
+ # debug setup
164
+ debug_folder_path = None
165
+ debug_jsonl_path = None
166
+ if debug:
167
+ debug_folder_path = os.path.join(
168
+ debug_save_dir, f"{img_path.rsplit('/', 1)[-1].rsplit('.', 1)[0]}"
169
+ )
170
+ debug_jsonl_path = os.path.join(debug_folder_path, "debug_history.json")
171
+ os.makedirs(debug_folder_path, exist_ok=True)
172
+
173
+ # The helper functions are now defined outside the agent_inference function
174
+ with open(MLLM_SYSTEM_PROMPT_PATH, "r") as f:
175
+ system_prompt = f.read().strip()
176
+ with open(ITERATIVE_CHECKING_SYSTEM_PROMPT_PATH, "r") as f:
177
+ iterative_checking_system_prompt = f.read().strip()
178
+
179
+ # Construct the initial message list
180
+ messages = [
181
+ {"role": "system", "content": system_prompt},
182
+ {
183
+ "role": "user",
184
+ "content": [
185
+ {"type": "image", "image": img_path},
186
+ {
187
+ "type": "text",
188
+ "text": f"The above image is the raw input image. The initial user input query is: '{initial_text_prompt}'.",
189
+ },
190
+ ],
191
+ },
192
+ ]
193
+ print(f"> Text prompt: {initial_text_prompt}")
194
+ print(f"> Image path: {img_path}")
195
+
196
+ print("\n\n")
197
+ print("-" * 30 + f" Round {str(generation_count + 1)}" + "-" * 30)
198
+ print("\n\n")
199
+ generated_text = send_generate_request(messages)
200
+ print(f"\n>>> MLLM Response [start]\n{generated_text}\n<<< MLLM Response [end]\n")
201
+ while generated_text is not None:
202
+ save_debug_messages(messages, debug, debug_folder_path, debug_jsonl_path)
203
+ assert (
204
+ "<tool>" in generated_text,
205
+ f"Generated text does not contain <tool> tag: {generated_text}",
206
+ )
207
+ generated_text = generated_text.split("</tool>", 1)[0] + "</tool>"
208
+ tool_call_json_str = (
209
+ generated_text.split("<tool>")[-1]
210
+ .split("</tool>")[0]
211
+ .strip()
212
+ .replace(r"}}}", r"}}") # remove extra } if any
213
+ )
214
+ try:
215
+ tool_call = json.loads(tool_call_json_str)
216
+ except json.JSONDecodeError:
217
+ raise ValueError(f"Invalid JSON in tool call: {tool_call_json_str}")
218
+
219
+ if PATH_TO_LATEST_OUTPUT_JSON == "":
220
+ # The first tool call must be segment_phrase or report_no_mask
221
+ assert (
222
+ tool_call["name"] == "segment_phrase"
223
+ or tool_call["name"] == "report_no_mask"
224
+ )
225
+
226
+ if tool_call["name"] == "segment_phrase":
227
+ print("🔍 Calling segment_phrase tool...")
228
+ assert list(tool_call["parameters"].keys()) == ["text_prompt"]
229
+
230
+ # Check if this text_prompt has been used before
231
+ current_text_prompt = tool_call["parameters"]["text_prompt"]
232
+ if current_text_prompt in USED_TEXT_PROMPTS:
233
+ print(
234
+ f"❌ Text prompt '{current_text_prompt}' has been used before. Requesting a different prompt."
235
+ )
236
+ duplicate_prompt_message = f"You have previously used '{current_text_prompt}' as your text_prompt to call the segment_phrase tool. You may not use it again. Please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase prompt, while adhering to all the rules stated in the system prompt. You must also never use any of the following text_prompt(s): {str(list(USED_TEXT_PROMPTS))}."
237
+ messages.append(
238
+ {
239
+ "role": "assistant",
240
+ "content": [{"type": "text", "text": generated_text}],
241
+ }
242
+ )
243
+ messages.append(
244
+ {
245
+ "role": "user",
246
+ "content": [{"type": "text", "text": duplicate_prompt_message}],
247
+ }
248
+ )
249
+ else:
250
+ # Add the text_prompt to the set of used prompts
251
+ USED_TEXT_PROMPTS.add(current_text_prompt)
252
+ LATEST_SAM3_TEXT_PROMPT = current_text_prompt
253
+ PATH_TO_LATEST_OUTPUT_JSON = call_sam_service(
254
+ image_path=img_path,
255
+ text_prompt=current_text_prompt,
256
+ output_folder_path=sam_output_dir,
257
+ )
258
+ sam3_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
259
+ sam3_output_image_path = sam3_outputs["output_image_path"]
260
+ num_masks = len(sam3_outputs["pred_boxes"])
261
+
262
+ messages.append(
263
+ {
264
+ "role": "assistant",
265
+ "content": [{"type": "text", "text": generated_text}],
266
+ }
267
+ )
268
+ if num_masks == 0:
269
+ print("❌ No masks generated by SAM3, reporting no mask to Qwen.")
270
+ sam3_output_text_message = f"The segment_phrase tool did not generate any masks for the text_prompt '{current_text_prompt}'. Now, please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase text_prompt, while adhering to all the rules stated in the system prompt. Please be reminded that the original user query was '{initial_text_prompt}'."
271
+ messages.append(
272
+ {
273
+ "role": "user",
274
+ "content": [
275
+ {"type": "text", "text": sam3_output_text_message}
276
+ ],
277
+ }
278
+ )
279
+ else:
280
+ sam3_output_text_message = rf"The segment_phrase tool generated {num_masks} available masks. All {num_masks} available masks are rendered in this image below, now you must analyze the {num_masks} available mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action. Please be reminded that the original user query was '{initial_text_prompt}'."
281
+ messages.append(
282
+ {
283
+ "role": "user",
284
+ "content": [
285
+ {"type": "text", "text": sam3_output_text_message},
286
+ {"type": "image", "image": sam3_output_image_path},
287
+ ],
288
+ }
289
+ )
290
+ print("\n\n>>> sam3_output_text_message:\n", sam3_output_text_message)
291
+
292
+ elif tool_call["name"] == "examine_each_mask":
293
+ print("🔍 Calling examine_each_mask tool...")
294
+ assert LATEST_SAM3_TEXT_PROMPT != ""
295
+
296
+ # Make sure that the last message is a image
297
+ assert (
298
+ messages[-1]["content"][1]["type"] == "image"
299
+ ), "Second content element should be an image"
300
+ messages.pop() # Remove the last user message
301
+ # Add simplified replacement message
302
+ simplified_message = {
303
+ "role": "user",
304
+ "content": [
305
+ {
306
+ "type": "text",
307
+ "text": "The segment_phrase tool generated several masks. Now you must analyze the mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action.",
308
+ }
309
+ ],
310
+ }
311
+ messages.append(simplified_message)
312
+
313
+ current_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
314
+ num_masks = len(current_outputs["pred_masks"])
315
+ masks_to_keep = []
316
+
317
+ # MLLM check the mask one by one
318
+ for i in range(num_masks):
319
+ print(f"🔍 Checking mask {i+1}/{num_masks}...")
320
+ image_w_mask_i, image_w_zoomed_in_mask_i = visualize(current_outputs, i)
321
+
322
+ image_w_zoomed_in_mask_i_path = os.path.join(
323
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png".replace("/", "_")
324
+ ).replace(".png", f"_zoom_in_mask_{i + 1}.png")
325
+ image_w_mask_i_path = os.path.join(
326
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png".replace("/", "_")
327
+ ).replace(".png", f"_selected_mask_{i + 1}.png")
328
+ image_w_zoomed_in_mask_i.save(image_w_zoomed_in_mask_i_path)
329
+ image_w_mask_i.save(image_w_mask_i_path)
330
+
331
+ iterative_checking_messages = [
332
+ {"role": "system", "content": iterative_checking_system_prompt},
333
+ {
334
+ "role": "user",
335
+ "content": [
336
+ {"type": "text", "text": f"The raw input image: "},
337
+ {"type": "image", "image": img_path},
338
+ {
339
+ "type": "text",
340
+ "text": f"The initial user input query is: '{initial_text_prompt}'",
341
+ },
342
+ {
343
+ "type": "text",
344
+ "text": f"Image with the predicted segmentation mask rendered on it: ",
345
+ },
346
+ {"type": "image", "image": image_w_mask_i_path},
347
+ {
348
+ "type": "text",
349
+ "text": f"Image with the zoomed-in mask: ",
350
+ },
351
+ {"type": "image", "image": image_w_zoomed_in_mask_i_path},
352
+ ],
353
+ },
354
+ ]
355
+ checking_generated_text = send_generate_request(
356
+ iterative_checking_messages
357
+ )
358
+
359
+ # Process the generated text to determine if the mask should be kept or rejected
360
+ if checking_generated_text is None:
361
+ raise ValueError(
362
+ "Generated text is None, which is unexpected. Please check the Qwen server and the input parameters."
363
+ )
364
+ print(f"Generated text for mask {i+1}: {checking_generated_text}")
365
+ verdict = (
366
+ checking_generated_text.split("<verdict>")[-1]
367
+ .split("</verdict>")[0]
368
+ .strip()
369
+ )
370
+ if "Accept" in verdict:
371
+ assert not "Reject" in verdict
372
+ print(f"Mask {i+1} accepted, keeping it in the outputs.")
373
+ masks_to_keep.append(i)
374
+ elif "Reject" in verdict:
375
+ assert not "Accept" in verdict
376
+ print(f"Mask {i+1} rejected, removing it from the outputs.")
377
+ else:
378
+ raise ValueError(
379
+ f"Unexpected verdict in generated text: {checking_generated_text}. Expected 'Accept' or 'Reject'."
380
+ )
381
+
382
+ updated_outputs = {
383
+ "original_image_path": current_outputs["original_image_path"],
384
+ "orig_img_h": current_outputs["orig_img_h"],
385
+ "orig_img_w": current_outputs["orig_img_w"],
386
+ "pred_boxes": [current_outputs["pred_boxes"][i] for i in masks_to_keep],
387
+ "pred_scores": [
388
+ current_outputs["pred_scores"][i] for i in masks_to_keep
389
+ ],
390
+ "pred_masks": [current_outputs["pred_masks"][i] for i in masks_to_keep],
391
+ }
392
+
393
+ image_w_check_masks = visualize(updated_outputs)
394
+ image_w_check_masks_path = os.path.join(
395
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png"
396
+ ).replace(
397
+ ".png",
398
+ f"_selected_masks_{'-'.join(map(str, [i+1 for i in masks_to_keep]))}.png".replace(
399
+ "/", "_"
400
+ ),
401
+ )
402
+ image_w_check_masks.save(image_w_check_masks_path)
403
+ # save the updated json outputs and append to message history
404
+ messages.append(
405
+ {
406
+ "role": "assistant",
407
+ "content": [{"type": "text", "text": generated_text}],
408
+ }
409
+ )
410
+ if len(masks_to_keep) == 0:
411
+ messages.append(
412
+ {
413
+ "role": "user",
414
+ "content": [
415
+ {
416
+ "type": "text",
417
+ "text": f"The original user query was: '{initial_text_prompt}'. The examine_each_mask tool examined and rejected all of the masks generated by the segment_phrase tool. Now, please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase text_prompt, while adhering to all the rules stated in the system prompt.",
418
+ }
419
+ ],
420
+ }
421
+ )
422
+ else:
423
+ messages.append(
424
+ {
425
+ "role": "user",
426
+ "content": [
427
+ {
428
+ "type": "text",
429
+ "text": f"The original user query was: '{initial_text_prompt}'. After calling the examine_each_mask tool on the available masks, the number of available masks is now {len(masks_to_keep)}. All {len(masks_to_keep)} available masks are rendered in this image below, now you must analyze the {len(masks_to_keep)} available mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action.",
430
+ },
431
+ {"type": "image", "image": image_w_check_masks_path},
432
+ ],
433
+ }
434
+ )
435
+
436
+ # Create a new filename based on the original path to avoid filename length issues
437
+ base_path = PATH_TO_LATEST_OUTPUT_JSON
438
+ # Remove any existing "masks_" suffix to avoid duplication
439
+ if "masks_" in base_path:
440
+ base_path = base_path.split("masks_")[0] + ".json"
441
+ # Create new filename with current masks; use a clearer suffix when empty
442
+ if len(masks_to_keep) == 0:
443
+ PATH_TO_LATEST_OUTPUT_JSON = base_path.replace(
444
+ ".json", "masks_none.json"
445
+ )
446
+ else:
447
+ PATH_TO_LATEST_OUTPUT_JSON = base_path.replace(
448
+ ".json", f"masks_{'_'.join(map(str, masks_to_keep))}.json"
449
+ )
450
+ json.dump(updated_outputs, open(PATH_TO_LATEST_OUTPUT_JSON, "w"), indent=4)
451
+
452
+ elif tool_call["name"] == "select_masks_and_return":
453
+ print("🔍 Calling select_masks_and_return tool...")
454
+ current_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
455
+
456
+ assert list(tool_call["parameters"].keys()) == ["final_answer_masks"]
457
+ masks_to_keep = tool_call["parameters"]["final_answer_masks"]
458
+
459
+ # Keep only valid mask indices, remove duplicates, and preserve deterministic ascending order
460
+ available_masks = set(range(1, len(current_outputs["pred_masks"]) + 1))
461
+ masks_to_keep = sorted({i for i in masks_to_keep if i in available_masks})
462
+ # Change this to a update message telling the model to try again along with information about errors made.
463
+
464
+ final_outputs = {
465
+ "original_image_path": current_outputs["original_image_path"],
466
+ "orig_img_h": current_outputs["orig_img_h"],
467
+ "orig_img_w": current_outputs["orig_img_w"],
468
+ "pred_boxes": [
469
+ current_outputs["pred_boxes"][i - 1] for i in masks_to_keep
470
+ ],
471
+ "pred_scores": [
472
+ current_outputs["pred_scores"][i - 1] for i in masks_to_keep
473
+ ],
474
+ "pred_masks": [
475
+ current_outputs["pred_masks"][i - 1] for i in masks_to_keep
476
+ ],
477
+ }
478
+
479
+ rendered_final_output = visualize(final_outputs)
480
+ messages.append(
481
+ {
482
+ "role": "assistant",
483
+ "content": [{"type": "text", "text": generated_text}],
484
+ }
485
+ )
486
+
487
+ # Clean up debug files before successful return
488
+ cleanup_debug_files(debug, debug_folder_path, debug_jsonl_path)
489
+ return messages, final_outputs, rendered_final_output
490
+
491
+ elif tool_call["name"] == "report_no_mask":
492
+ print("🔍 Calling report_no_mask tool...")
493
+ height, width = cv2.imread(img_path).shape[:2]
494
+ final_outputs = {
495
+ "original_image_path": img_path,
496
+ "orig_img_h": height,
497
+ "orig_img_w": width,
498
+ "pred_boxes": [],
499
+ "pred_scores": [],
500
+ "pred_masks": [],
501
+ }
502
+ rendered_final_output = Image.open(img_path)
503
+ messages.append(
504
+ {
505
+ "role": "assistant",
506
+ "content": [{"type": "text", "text": generated_text}],
507
+ }
508
+ )
509
+ return messages, final_outputs, rendered_final_output
510
+
511
+ else:
512
+ raise ValueError(f"Unknown tool call: {tool_call['name']}")
513
+
514
+ # sometimes the MLLM don't know when to stop, and generates multiple tool calls in one round, so we need to split the generated text by </tool> and only keep the first one
515
+
516
+ for message in messages:
517
+ if message["role"] == "assistant" and "content" in message:
518
+ for content in message["content"]:
519
+ if (
520
+ isinstance(content, dict)
521
+ and content.get("type") == "text"
522
+ and "text" in content
523
+ ):
524
+ content["text"] = (
525
+ content["text"].split("</tool>", 1)[0] + "</tool>\n\n"
526
+ )
527
+ # Prune the messages history before the next MLLM generation round according to the 3-part rules.
528
+ # This keeps history compact and ensures the model sees only the allowed parts.
529
+ messages = _prune_messages_for_next_round(
530
+ messages,
531
+ USED_TEXT_PROMPTS,
532
+ LATEST_SAM3_TEXT_PROMPT,
533
+ img_path,
534
+ initial_text_prompt,
535
+ )
536
+ # make sure there can never be more than 2 images in the context
537
+ assert count_images(messages) <= 2
538
+ generation_count += 1
539
+ if generation_count > max_generations:
540
+ raise ValueError(
541
+ f"Exceeded maximum number of allowed generation requests ({max_generations})"
542
+ )
543
+
544
+ print("\n\n")
545
+ print("-" * 30 + f" Round {str(generation_count + 1)}" + "-" * 30)
546
+ print("\n\n")
547
+ generated_text = send_generate_request(messages)
548
+ print(
549
+ f"\n>>> MLLM Response [start]\n{generated_text}\n<<< MLLM Response [end]\n"
550
+ )
551
+
552
+ print("\n\n>>> SAM 3 Agent execution ended.\n\n")
553
+
554
+ error_save_path = os.path.join(
555
+ error_save_dir,
556
+ f"{img_path.rsplit('/', 1)[-1].rsplit('.', 1)[0]}_error_history.json",
557
+ )
558
+ with open(error_save_path, "w") as f:
559
+ json.dump(messages, f, indent=4)
560
+ print("Saved messages history that caused error to:", error_save_path)
561
+ raise ValueError(
562
+ rf"Generated text is None, which is unexpected. Please check the Qwen server and the input parameters for image path: {img_path} and initial text prompt: {initial_text_prompt}."
563
+ )
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/client_llm.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import base64
4
+ import os
5
+ from typing import Any, Optional
6
+
7
+ from openai import OpenAI
8
+
9
+
10
+ def get_image_base64_and_mime(image_path):
11
+ """Convert image file to base64 string and get MIME type"""
12
+ try:
13
+ # Get MIME type based on file extension
14
+ ext = os.path.splitext(image_path)[1].lower()
15
+ mime_types = {
16
+ ".jpg": "image/jpeg",
17
+ ".jpeg": "image/jpeg",
18
+ ".png": "image/png",
19
+ ".gif": "image/gif",
20
+ ".webp": "image/webp",
21
+ ".bmp": "image/bmp",
22
+ }
23
+ mime_type = mime_types.get(ext, "image/jpeg") # Default to JPEG
24
+
25
+ # Convert image to base64
26
+ with open(image_path, "rb") as image_file:
27
+ base64_data = base64.b64encode(image_file.read()).decode("utf-8")
28
+ return base64_data, mime_type
29
+ except Exception as e:
30
+ print(f"Error converting image to base64: {e}")
31
+ return None, None
32
+
33
+
34
+ def send_generate_request(
35
+ messages,
36
+ server_url=None,
37
+ model="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
38
+ api_key=None,
39
+ max_tokens=4096,
40
+ ):
41
+ """
42
+ Sends a request to the OpenAI-compatible API endpoint using the OpenAI client library.
43
+
44
+ Args:
45
+ server_url (str): The base URL of the server, e.g. "http://127.0.0.1:8000"
46
+ messages (list): A list of message dicts, each containing role and content.
47
+ model (str): The model to use for generation (default: "llama-4")
48
+ max_tokens (int): Maximum number of tokens to generate (default: 4096)
49
+
50
+ Returns:
51
+ str: The generated response text from the server.
52
+ """
53
+ # Process messages to convert image paths to base64
54
+ processed_messages = []
55
+ for message in messages:
56
+ processed_message = message.copy()
57
+ if message["role"] == "user" and "content" in message:
58
+ processed_content = []
59
+ for c in message["content"]:
60
+ if isinstance(c, dict) and c.get("type") == "image":
61
+ # Convert image path to base64 format
62
+ image_path = c["image"]
63
+
64
+ print("image_path", image_path)
65
+ new_image_path = image_path.replace(
66
+ "?", "%3F"
67
+ ) # Escape ? in the path
68
+
69
+ # Read the image file and convert to base64
70
+ try:
71
+ base64_image, mime_type = get_image_base64_and_mime(
72
+ new_image_path
73
+ )
74
+ if base64_image is None:
75
+ print(
76
+ f"Warning: Could not convert image to base64: {new_image_path}"
77
+ )
78
+ continue
79
+
80
+ # Create the proper image_url structure with base64 data
81
+ processed_content.append(
82
+ {
83
+ "type": "image_url",
84
+ "image_url": {
85
+ "url": f"data:{mime_type};base64,{base64_image}",
86
+ "detail": "high",
87
+ },
88
+ }
89
+ )
90
+
91
+ except FileNotFoundError:
92
+ print(f"Warning: Image file not found: {new_image_path}")
93
+ continue
94
+ except Exception as e:
95
+ print(f"Warning: Error processing image {new_image_path}: {e}")
96
+ continue
97
+ else:
98
+ processed_content.append(c)
99
+
100
+ processed_message["content"] = processed_content
101
+ processed_messages.append(processed_message)
102
+
103
+ # Create OpenAI client with custom base URL
104
+ client = OpenAI(api_key=api_key, base_url=server_url)
105
+
106
+ try:
107
+ print(f"🔍 Calling model {model}...")
108
+ response = client.chat.completions.create(
109
+ model=model,
110
+ messages=processed_messages,
111
+ max_completion_tokens=max_tokens,
112
+ n=1,
113
+ )
114
+ # print(f"Received response: {response.choices[0].message}")
115
+
116
+ # Extract the response content
117
+ if response.choices and len(response.choices) > 0:
118
+ return response.choices[0].message.content
119
+ else:
120
+ print(f"Unexpected response format: {response}")
121
+ return None
122
+
123
+ except Exception as e:
124
+ print(f"Request failed: {e}")
125
+ return None
126
+
127
+
128
+ def send_direct_request(
129
+ llm: Any,
130
+ messages: list[dict[str, Any]],
131
+ sampling_params: Any,
132
+ ) -> Optional[str]:
133
+ """
134
+ Run inference on a vLLM model instance directly without using a server.
135
+
136
+ Args:
137
+ llm: Initialized vLLM LLM instance (passed from external initialization)
138
+ messages: List of message dicts with role and content (OpenAI format)
139
+ sampling_params: vLLM SamplingParams instance (initialized externally)
140
+
141
+ Returns:
142
+ str: Generated response text, or None if inference fails
143
+ """
144
+ try:
145
+ # Process messages to handle images (convert to base64 if needed)
146
+ processed_messages = []
147
+ for message in messages:
148
+ processed_message = message.copy()
149
+ if message["role"] == "user" and "content" in message:
150
+ processed_content = []
151
+ for c in message["content"]:
152
+ if isinstance(c, dict) and c.get("type") == "image":
153
+ # Convert image path to base64 format
154
+ image_path = c["image"]
155
+ new_image_path = image_path.replace("?", "%3F")
156
+
157
+ try:
158
+ base64_image, mime_type = get_image_base64_and_mime(
159
+ new_image_path
160
+ )
161
+ if base64_image is None:
162
+ print(
163
+ f"Warning: Could not convert image: {new_image_path}"
164
+ )
165
+ continue
166
+
167
+ # vLLM expects image_url format
168
+ processed_content.append(
169
+ {
170
+ "type": "image_url",
171
+ "image_url": {
172
+ "url": f"data:{mime_type};base64,{base64_image}"
173
+ },
174
+ }
175
+ )
176
+ except Exception as e:
177
+ print(
178
+ f"Warning: Error processing image {new_image_path}: {e}"
179
+ )
180
+ continue
181
+ else:
182
+ processed_content.append(c)
183
+
184
+ processed_message["content"] = processed_content
185
+ processed_messages.append(processed_message)
186
+
187
+ print("🔍 Running direct inference with vLLM...")
188
+
189
+ # Run inference using vLLM's chat interface
190
+ outputs = llm.chat(
191
+ messages=processed_messages,
192
+ sampling_params=sampling_params,
193
+ )
194
+
195
+ # Extract the generated text from the first output
196
+ if outputs and len(outputs) > 0:
197
+ generated_text = outputs[0].outputs[0].text
198
+ return generated_text
199
+ else:
200
+ print(f"Unexpected output format: {outputs}")
201
+ return None
202
+
203
+ except Exception as e:
204
+ print(f"Direct inference failed: {e}")
205
+ return None
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/client_sam3.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import json
4
+ import os
5
+
6
+ import torch
7
+ from PIL import Image
8
+
9
+ from sam3.model.box_ops import box_xyxy_to_xywh
10
+ from sam3.train.masks_ops import rle_encode
11
+
12
+ from .helpers.mask_overlap_removal import remove_overlapping_masks
13
+ from .viz import visualize
14
+
15
+
16
+ def sam3_inference(processor, image_path, text_prompt):
17
+ """Run SAM 3 image inference with text prompts and format the outputs"""
18
+ image = Image.open(image_path)
19
+ orig_img_w, orig_img_h = image.size
20
+
21
+ # model inference
22
+ inference_state = processor.set_image(image)
23
+ inference_state = processor.set_text_prompt(
24
+ state=inference_state, prompt=text_prompt
25
+ )
26
+
27
+ # format and assemble outputs
28
+ pred_boxes_xyxy = torch.stack(
29
+ [
30
+ inference_state["boxes"][:, 0] / orig_img_w,
31
+ inference_state["boxes"][:, 1] / orig_img_h,
32
+ inference_state["boxes"][:, 2] / orig_img_w,
33
+ inference_state["boxes"][:, 3] / orig_img_h,
34
+ ],
35
+ dim=-1,
36
+ ) # normalized in range [0, 1]
37
+ pred_boxes_xywh = box_xyxy_to_xywh(pred_boxes_xyxy).tolist()
38
+ pred_masks = rle_encode(inference_state["masks"].squeeze(1))
39
+ pred_masks = [m["counts"] for m in pred_masks]
40
+ outputs = {
41
+ "orig_img_h": orig_img_h,
42
+ "orig_img_w": orig_img_w,
43
+ "pred_boxes": pred_boxes_xywh,
44
+ "pred_masks": pred_masks,
45
+ "pred_scores": inference_state["scores"].tolist(),
46
+ }
47
+ return outputs
48
+
49
+
50
+ def call_sam_service(
51
+ sam3_processor,
52
+ image_path: str,
53
+ text_prompt: str,
54
+ output_folder_path: str = "sam3_output",
55
+ ):
56
+ """
57
+ Loads an image, sends it with a text prompt to the service,
58
+ saves the results, and renders the visualization.
59
+ """
60
+ print(f"📞 Loading image '{image_path}' and sending with prompt '{text_prompt}'...")
61
+
62
+ text_prompt_for_save_path = (
63
+ text_prompt.replace("/", "_") if "/" in text_prompt else text_prompt
64
+ )
65
+
66
+ os.makedirs(
67
+ os.path.join(output_folder_path, image_path.replace("/", "-")), exist_ok=True
68
+ )
69
+ output_json_path = os.path.join(
70
+ output_folder_path,
71
+ image_path.replace("/", "-"),
72
+ rf"{text_prompt_for_save_path}.json",
73
+ )
74
+ output_image_path = os.path.join(
75
+ output_folder_path,
76
+ image_path.replace("/", "-"),
77
+ rf"{text_prompt_for_save_path}.png",
78
+ )
79
+
80
+ try:
81
+ # Send the image and text prompt as a multipart/form-data request
82
+ serialized_response = sam3_inference(sam3_processor, image_path, text_prompt)
83
+
84
+ # 1. Prepare the response dictionary
85
+ serialized_response = remove_overlapping_masks(serialized_response)
86
+ serialized_response = {
87
+ "original_image_path": image_path,
88
+ "output_image_path": output_image_path,
89
+ **serialized_response,
90
+ }
91
+
92
+ # 2. Reorder predictions by scores (highest to lowest) if scores are available
93
+ if "pred_scores" in serialized_response and serialized_response["pred_scores"]:
94
+ # Create indices sorted by scores in descending order
95
+ score_indices = sorted(
96
+ range(len(serialized_response["pred_scores"])),
97
+ key=lambda i: serialized_response["pred_scores"][i],
98
+ reverse=True,
99
+ )
100
+
101
+ # Reorder all three lists based on the sorted indices
102
+ serialized_response["pred_scores"] = [
103
+ serialized_response["pred_scores"][i] for i in score_indices
104
+ ]
105
+ serialized_response["pred_boxes"] = [
106
+ serialized_response["pred_boxes"][i] for i in score_indices
107
+ ]
108
+ serialized_response["pred_masks"] = [
109
+ serialized_response["pred_masks"][i] for i in score_indices
110
+ ]
111
+
112
+ # 3. Remove any invalid RLE masks that is too short (shorter than 5 characters)
113
+ valid_masks = []
114
+ valid_boxes = []
115
+ valid_scores = []
116
+ for i, rle in enumerate(serialized_response["pred_masks"]):
117
+ if len(rle) > 4:
118
+ valid_masks.append(rle)
119
+ valid_boxes.append(serialized_response["pred_boxes"][i])
120
+ valid_scores.append(serialized_response["pred_scores"][i])
121
+ serialized_response["pred_masks"] = valid_masks
122
+ serialized_response["pred_boxes"] = valid_boxes
123
+ serialized_response["pred_scores"] = valid_scores
124
+
125
+ with open(output_json_path, "w") as f:
126
+ json.dump(serialized_response, f, indent=4)
127
+ print(f"✅ Raw JSON response saved to '{output_json_path}'")
128
+
129
+ # 4. Render and save visualizations on the image and save it in the SAM3 output folder
130
+ print("🔍 Rendering visualizations on the image ...")
131
+ viz_image = visualize(serialized_response)
132
+ os.makedirs(os.path.dirname(output_image_path), exist_ok=True)
133
+ viz_image.save(output_image_path)
134
+ print("✅ Saved visualization at:", output_image_path)
135
+ except Exception as e:
136
+ print(f"❌ Error calling service: {e}")
137
+
138
+ return output_json_path
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/boxes.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import math
4
+ from enum import IntEnum, unique
5
+ from typing import List, Tuple, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch import device
10
+
11
+ _RawBoxType = Union[List[float], Tuple[float, ...], torch.Tensor, np.ndarray]
12
+
13
+
14
+ @unique
15
+ class BoxMode(IntEnum):
16
+ """
17
+ Enum of different ways to represent a box.
18
+ """
19
+
20
+ XYXY_ABS = 0
21
+ """
22
+ (x0, y0, x1, y1) in absolute floating points coordinates.
23
+ The coordinates in range [0, width or height].
24
+ """
25
+ XYWH_ABS = 1
26
+ """
27
+ (x0, y0, w, h) in absolute floating points coordinates.
28
+ """
29
+ XYXY_REL = 2
30
+ """
31
+ Not yet supported!
32
+ (x0, y0, x1, y1) in range [0, 1]. They are relative to the size of the image.
33
+ """
34
+ XYWH_REL = 3
35
+ """
36
+ Not yet supported!
37
+ (x0, y0, w, h) in range [0, 1]. They are relative to the size of the image.
38
+ """
39
+ XYWHA_ABS = 4
40
+ """
41
+ (xc, yc, w, h, a) in absolute floating points coordinates.
42
+ (xc, yc) is the center of the rotated box, and the angle a is in degrees ccw.
43
+ """
44
+
45
+ @staticmethod
46
+ def convert(
47
+ box: _RawBoxType, from_mode: "BoxMode", to_mode: "BoxMode"
48
+ ) -> _RawBoxType:
49
+ """
50
+ Args:
51
+ box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5
52
+ from_mode, to_mode (BoxMode)
53
+
54
+ Returns:
55
+ The converted box of the same type.
56
+ """
57
+ if from_mode == to_mode:
58
+ return box
59
+
60
+ original_type = type(box)
61
+ is_numpy = isinstance(box, np.ndarray)
62
+ single_box = isinstance(box, (list, tuple))
63
+ if single_box:
64
+ assert len(box) == 4 or len(box) == 5, (
65
+ "BoxMode.convert takes either a k-tuple/list or an Nxk array/tensor,"
66
+ " where k == 4 or 5"
67
+ )
68
+ arr = torch.tensor(box)[None, :]
69
+ else:
70
+ # avoid modifying the input box
71
+ if is_numpy:
72
+ arr = torch.from_numpy(np.asarray(box)).clone()
73
+ else:
74
+ arr = box.clone()
75
+
76
+ assert to_mode not in [
77
+ BoxMode.XYXY_REL,
78
+ BoxMode.XYWH_REL,
79
+ ] and from_mode not in [
80
+ BoxMode.XYXY_REL,
81
+ BoxMode.XYWH_REL,
82
+ ], "Relative mode not yet supported!"
83
+
84
+ if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:
85
+ assert (
86
+ arr.shape[-1] == 5
87
+ ), "The last dimension of input shape must be 5 for XYWHA format"
88
+ original_dtype = arr.dtype
89
+ arr = arr.double()
90
+
91
+ w = arr[:, 2]
92
+ h = arr[:, 3]
93
+ a = arr[:, 4]
94
+ c = torch.abs(torch.cos(a * math.pi / 180.0))
95
+ s = torch.abs(torch.sin(a * math.pi / 180.0))
96
+ # This basically computes the horizontal bounding rectangle of the rotated box
97
+ new_w = c * w + s * h
98
+ new_h = c * h + s * w
99
+
100
+ # convert center to top-left corner
101
+ arr[:, 0] -= new_w / 2.0
102
+ arr[:, 1] -= new_h / 2.0
103
+ # bottom-right corner
104
+ arr[:, 2] = arr[:, 0] + new_w
105
+ arr[:, 3] = arr[:, 1] + new_h
106
+
107
+ arr = arr[:, :4].to(dtype=original_dtype)
108
+ elif from_mode == BoxMode.XYWH_ABS and to_mode == BoxMode.XYWHA_ABS:
109
+ original_dtype = arr.dtype
110
+ arr = arr.double()
111
+ arr[:, 0] += arr[:, 2] / 2.0
112
+ arr[:, 1] += arr[:, 3] / 2.0
113
+ angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)
114
+ arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)
115
+ else:
116
+ if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:
117
+ arr[:, 2] += arr[:, 0]
118
+ arr[:, 3] += arr[:, 1]
119
+ elif from_mode == BoxMode.XYXY_ABS and to_mode == BoxMode.XYWH_ABS:
120
+ arr[:, 2] -= arr[:, 0]
121
+ arr[:, 3] -= arr[:, 1]
122
+ else:
123
+ raise NotImplementedError(
124
+ "Conversion from BoxMode {} to {} is not supported yet".format(
125
+ from_mode, to_mode
126
+ )
127
+ )
128
+
129
+ if single_box:
130
+ return original_type(arr.flatten().tolist())
131
+ if is_numpy:
132
+ return arr.numpy()
133
+ else:
134
+ return arr
135
+
136
+
137
+ class Boxes:
138
+ """
139
+ This structure stores a list of boxes as a Nx4 torch.Tensor.
140
+ It supports some common methods about boxes
141
+ (`area`, `clip`, `nonempty`, etc),
142
+ and also behaves like a Tensor
143
+ (support indexing, `to(device)`, `.device`, and iteration over all boxes)
144
+
145
+ Attributes:
146
+ tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2).
147
+ """
148
+
149
+ def __init__(self, tensor: torch.Tensor):
150
+ """
151
+ Args:
152
+ tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2).
153
+ """
154
+ if not isinstance(tensor, torch.Tensor):
155
+ tensor = torch.as_tensor(
156
+ tensor, dtype=torch.float32, device=torch.device("cpu")
157
+ )
158
+ else:
159
+ tensor = tensor.to(torch.float32)
160
+ if tensor.numel() == 0:
161
+ # Use reshape, so we don't end up creating a new tensor that does not depend on
162
+ # the inputs (and consequently confuses jit)
163
+ tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32)
164
+ assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size()
165
+
166
+ self.tensor = tensor
167
+
168
+ def clone(self) -> "Boxes":
169
+ """
170
+ Clone the Boxes.
171
+
172
+ Returns:
173
+ Boxes
174
+ """
175
+ return Boxes(self.tensor.clone())
176
+
177
+ def to(self, device: torch.device):
178
+ # Boxes are assumed float32 and does not support to(dtype)
179
+ return Boxes(self.tensor.to(device=device))
180
+
181
+ def area(self) -> torch.Tensor:
182
+ """
183
+ Computes the area of all the boxes.
184
+
185
+ Returns:
186
+ torch.Tensor: a vector with areas of each box.
187
+ """
188
+ box = self.tensor
189
+ area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1])
190
+ return area
191
+
192
+ def clip(self, box_size: Tuple[int, int]) -> None:
193
+ """
194
+ Clip (in place) the boxes by limiting x coordinates to the range [0, width]
195
+ and y coordinates to the range [0, height].
196
+
197
+ Args:
198
+ box_size (height, width): The clipping box's size.
199
+ """
200
+ assert torch.isfinite(self.tensor).all(), "Box tensor contains infinite or NaN!"
201
+ h, w = box_size
202
+ x1 = self.tensor[:, 0].clamp(min=0, max=w)
203
+ y1 = self.tensor[:, 1].clamp(min=0, max=h)
204
+ x2 = self.tensor[:, 2].clamp(min=0, max=w)
205
+ y2 = self.tensor[:, 3].clamp(min=0, max=h)
206
+ self.tensor = torch.stack((x1, y1, x2, y2), dim=-1)
207
+
208
+ def nonempty(self, threshold: float = 0.0) -> torch.Tensor:
209
+ """
210
+ Find boxes that are non-empty.
211
+ A box is considered empty, if either of its side is no larger than threshold.
212
+
213
+ Returns:
214
+ Tensor:
215
+ a binary vector which represents whether each box is empty
216
+ (False) or non-empty (True).
217
+ """
218
+ box = self.tensor
219
+ widths = box[:, 2] - box[:, 0]
220
+ heights = box[:, 3] - box[:, 1]
221
+ keep = (widths > threshold) & (heights > threshold)
222
+ return keep
223
+
224
+ def __getitem__(self, item) -> "Boxes":
225
+ """
226
+ Args:
227
+ item: int, slice, or a BoolTensor
228
+
229
+ Returns:
230
+ Boxes: Create a new :class:`Boxes` by indexing.
231
+
232
+ The following usage are allowed:
233
+
234
+ 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.
235
+ 2. `new_boxes = boxes[2:10]`: return a slice of boxes.
236
+ 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor
237
+ with `length = len(boxes)`. Nonzero elements in the vector will be selected.
238
+
239
+ Note that the returned Boxes might share storage with this Boxes,
240
+ subject to Pytorch's indexing semantics.
241
+ """
242
+ if isinstance(item, int):
243
+ return Boxes(self.tensor[item].view(1, -1))
244
+ b = self.tensor[item]
245
+ assert (
246
+ b.dim() == 2
247
+ ), "Indexing on Boxes with {} failed to return a matrix!".format(item)
248
+ return Boxes(b)
249
+
250
+ def __len__(self) -> int:
251
+ return self.tensor.shape[0]
252
+
253
+ def __repr__(self) -> str:
254
+ return "Boxes(" + str(self.tensor) + ")"
255
+
256
+ def inside_box(
257
+ self, box_size: Tuple[int, int], boundary_threshold: int = 0
258
+ ) -> torch.Tensor:
259
+ """
260
+ Args:
261
+ box_size (height, width): Size of the reference box.
262
+ boundary_threshold (int): Boxes that extend beyond the reference box
263
+ boundary by more than boundary_threshold are considered "outside".
264
+
265
+ Returns:
266
+ a binary vector, indicating whether each box is inside the reference box.
267
+ """
268
+ height, width = box_size
269
+ inds_inside = (
270
+ (self.tensor[..., 0] >= -boundary_threshold)
271
+ & (self.tensor[..., 1] >= -boundary_threshold)
272
+ & (self.tensor[..., 2] < width + boundary_threshold)
273
+ & (self.tensor[..., 3] < height + boundary_threshold)
274
+ )
275
+ return inds_inside
276
+
277
+ def get_centers(self) -> torch.Tensor:
278
+ """
279
+ Returns:
280
+ The box centers in a Nx2 array of (x, y).
281
+ """
282
+ return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2
283
+
284
+ def scale(self, scale_x: float, scale_y: float) -> None:
285
+ """
286
+ Scale the box with horizontal and vertical scaling factors
287
+ """
288
+ self.tensor[:, 0::2] *= scale_x
289
+ self.tensor[:, 1::2] *= scale_y
290
+
291
+ @classmethod
292
+ def cat(cls, boxes_list: List["Boxes"]) -> "Boxes":
293
+ """
294
+ Concatenates a list of Boxes into a single Boxes
295
+
296
+ Arguments:
297
+ boxes_list (list[Boxes])
298
+
299
+ Returns:
300
+ Boxes: the concatenated Boxes
301
+ """
302
+ assert isinstance(boxes_list, (list, tuple))
303
+ if len(boxes_list) == 0:
304
+ return cls(torch.empty(0))
305
+ assert all([isinstance(box, Boxes) for box in boxes_list])
306
+
307
+ # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input
308
+ cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))
309
+ return cat_boxes
310
+
311
+ @property
312
+ def device(self) -> device:
313
+ return self.tensor.device
314
+
315
+ # type "Iterator[torch.Tensor]", yield, and iter() not supported by torchscript
316
+ # https://github.com/pytorch/pytorch/issues/18627
317
+ @torch.jit.unused
318
+ def __iter__(self):
319
+ """
320
+ Yield a box as a Tensor of shape (4,) at a time.
321
+ """
322
+ yield from self.tensor
323
+
324
+
325
+ def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
326
+ """
327
+ Given two lists of boxes of size N and M,
328
+ compute the intersection area between __all__ N x M pairs of boxes.
329
+ The box order must be (xmin, ymin, xmax, ymax)
330
+
331
+ Args:
332
+ boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.
333
+
334
+ Returns:
335
+ Tensor: intersection, sized [N,M].
336
+ """
337
+ boxes1, boxes2 = boxes1.tensor, boxes2.tensor
338
+ width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(
339
+ boxes1[:, None, :2], boxes2[:, :2]
340
+ ) # [N,M,2]
341
+
342
+ width_height.clamp_(min=0) # [N,M,2]
343
+ intersection = width_height.prod(dim=2) # [N,M]
344
+ return intersection
345
+
346
+
347
+ # implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py
348
+ # with slight modifications
349
+ def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
350
+ """
351
+ Given two lists of boxes of size N and M, compute the IoU
352
+ (intersection over union) between **all** N x M pairs of boxes.
353
+ The box order must be (xmin, ymin, xmax, ymax).
354
+
355
+ Args:
356
+ boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.
357
+
358
+ Returns:
359
+ Tensor: IoU, sized [N,M].
360
+ """
361
+ area1 = boxes1.area() # [N]
362
+ area2 = boxes2.area() # [M]
363
+ inter = pairwise_intersection(boxes1, boxes2)
364
+
365
+ # handle empty boxes
366
+ iou = torch.where(
367
+ inter > 0,
368
+ inter / (area1[:, None] + area2 - inter),
369
+ torch.zeros(1, dtype=inter.dtype, device=inter.device),
370
+ )
371
+ return iou
372
+
373
+
374
+ def pairwise_ioa(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
375
+ """
376
+ Similar to :func:`pariwise_iou` but compute the IoA (intersection over boxes2 area).
377
+
378
+ Args:
379
+ boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.
380
+
381
+ Returns:
382
+ Tensor: IoA, sized [N,M].
383
+ """
384
+ area2 = boxes2.area() # [M]
385
+ inter = pairwise_intersection(boxes1, boxes2)
386
+
387
+ # handle empty boxes
388
+ ioa = torch.where(
389
+ inter > 0, inter / area2, torch.zeros(1, dtype=inter.dtype, device=inter.device)
390
+ )
391
+ return ioa
392
+
393
+
394
+ def pairwise_point_box_distance(points: torch.Tensor, boxes: Boxes):
395
+ """
396
+ Pairwise distance between N points and M boxes. The distance between a
397
+ point and a box is represented by the distance from the point to 4 edges
398
+ of the box. Distances are all positive when the point is inside the box.
399
+
400
+ Args:
401
+ points: Nx2 coordinates. Each row is (x, y)
402
+ boxes: M boxes
403
+
404
+ Returns:
405
+ Tensor: distances of size (N, M, 4). The 4 values are distances from
406
+ the point to the left, top, right, bottom of the box.
407
+ """
408
+ x, y = points.unsqueeze(dim=2).unbind(dim=1) # (N, 1)
409
+ x0, y0, x1, y1 = boxes.tensor.unsqueeze(dim=0).unbind(dim=2) # (1, M)
410
+ return torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2)
411
+
412
+
413
+ def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
414
+ """
415
+ Compute pairwise intersection over union (IOU) of two sets of matched
416
+ boxes that have the same number of boxes.
417
+ Similar to :func:`pairwise_iou`, but computes only diagonal elements of the matrix.
418
+
419
+ Args:
420
+ boxes1 (Boxes): bounding boxes, sized [N,4].
421
+ boxes2 (Boxes): same length as boxes1
422
+ Returns:
423
+ Tensor: iou, sized [N].
424
+ """
425
+ assert len(boxes1) == len(boxes2), (
426
+ "boxlists should have the same" "number of entries, got {}, {}".format(
427
+ len(boxes1), len(boxes2)
428
+ )
429
+ )
430
+ area1 = boxes1.area() # [N]
431
+ area2 = boxes2.area() # [N]
432
+ box1, box2 = boxes1.tensor, boxes2.tensor
433
+ lt = torch.max(box1[:, :2], box2[:, :2]) # [N,2]
434
+ rb = torch.min(box1[:, 2:], box2[:, 2:]) # [N,2]
435
+ wh = (rb - lt).clamp(min=0) # [N,2]
436
+ inter = wh[:, 0] * wh[:, 1] # [N]
437
+ iou = inter / (area1 + area2 - inter) # [N]
438
+ return iou
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/color_map.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """
4
+ An awesome colormap for really neat visualizations.
5
+ Copied from Detectron, and removed gray colors.
6
+ """
7
+
8
+ import random
9
+
10
+ import numpy as np
11
+
12
+ __all__ = ["colormap", "random_color", "random_colors"]
13
+
14
+
15
+ # A list of 25 bright and sharp colors for segmentation masks,
16
+ # generated from the edges of the sRGB color space for maximum intensity.
17
+ _COLORS = (
18
+ np.array(
19
+ [
20
+ # The original 8 sharp colors
21
+ 1.000,
22
+ 1.000,
23
+ 0.000, # 1. Yellow
24
+ 0.000,
25
+ 1.000,
26
+ 0.000, # 2. Lime
27
+ 0.000,
28
+ 1.000,
29
+ 1.000, # 3. Cyan
30
+ 1.000,
31
+ 0.000,
32
+ 1.000, # 4. Magenta
33
+ 1.000,
34
+ 0.000,
35
+ 0.000, # 5. Red
36
+ 1.000,
37
+ 0.498,
38
+ 0.000, # 6. Orange
39
+ 0.498,
40
+ 1.000,
41
+ 0.000, # 7. Chartreuse
42
+ 0.000,
43
+ 1.000,
44
+ 0.498, # 8. Spring Green
45
+ 1.000,
46
+ 0.000,
47
+ 0.498, # 9. Rose
48
+ 0.498,
49
+ 0.000,
50
+ 1.000, # 10. Violet
51
+ 0.753,
52
+ 1.000,
53
+ 0.000, # 11. Electric Lime
54
+ 1.000,
55
+ 0.753,
56
+ 0.000, # 12. Vivid Orange
57
+ 0.000,
58
+ 1.000,
59
+ 0.753, # 13. Turquoise
60
+ 0.753,
61
+ 0.000,
62
+ 1.000, # 14. Bright Violet
63
+ 1.000,
64
+ 0.000,
65
+ 0.753, # 15. Bright Pink
66
+ 1.000,
67
+ 0.251,
68
+ 0.000, # 16. Fiery Orange
69
+ 0.251,
70
+ 1.000,
71
+ 0.000, # 17. Bright Chartreuse
72
+ 0.000,
73
+ 1.000,
74
+ 0.251, # 18. Malachite Green
75
+ 0.251,
76
+ 0.000,
77
+ 1.000, # 19. Deep Violet
78
+ 1.000,
79
+ 0.000,
80
+ 0.251, # 20. Hot Pink
81
+ ]
82
+ )
83
+ .astype(np.float32)
84
+ .reshape(-1, 3)
85
+ )
86
+
87
+
88
+ def colormap(rgb=False, maximum=255):
89
+ """
90
+ Args:
91
+ rgb (bool): whether to return RGB colors or BGR colors.
92
+ maximum (int): either 255 or 1
93
+
94
+ Returns:
95
+ ndarray: a float32 array of Nx3 colors, in range [0, 255] or [0, 1]
96
+ """
97
+ assert maximum in [255, 1], maximum
98
+ c = _COLORS * maximum
99
+ if not rgb:
100
+ c = c[:, ::-1]
101
+ return c
102
+
103
+
104
+ def random_color(rgb=False, maximum=255):
105
+ """
106
+ Args:
107
+ rgb (bool): whether to return RGB colors or BGR colors.
108
+ maximum (int): either 255 or 1
109
+
110
+ Returns:
111
+ ndarray: a vector of 3 numbers
112
+ """
113
+ idx = np.random.randint(0, len(_COLORS))
114
+ ret = _COLORS[idx] * maximum
115
+ if not rgb:
116
+ ret = ret[::-1]
117
+ return ret
118
+
119
+
120
+ def random_colors(N, rgb=False, maximum=255):
121
+ """
122
+ Args:
123
+ N (int): number of unique colors needed
124
+ rgb (bool): whether to return RGB colors or BGR colors.
125
+ maximum (int): either 255 or 1
126
+
127
+ Returns:
128
+ ndarray: a list of random_color
129
+ """
130
+ indices = random.sample(range(len(_COLORS)), N)
131
+ ret = [_COLORS[i] * maximum for i in indices]
132
+ if not rgb:
133
+ ret = [x[::-1] for x in ret]
134
+ return ret
135
+
136
+
137
+ if __name__ == "__main__":
138
+ import cv2
139
+
140
+ size = 100
141
+ H, W = 10, 10
142
+ canvas = np.random.rand(H * size, W * size, 3).astype("float32")
143
+ for h in range(H):
144
+ for w in range(W):
145
+ idx = h * W + w
146
+ if idx >= len(_COLORS):
147
+ break
148
+ canvas[h * size : (h + 1) * size, w * size : (w + 1) * size] = _COLORS[idx]
149
+ cv2.imshow("a", canvas)
150
+ cv2.waitKey(0)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/keypoints.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from typing import Any, List, Tuple, Union
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+
9
+
10
+ class Keypoints:
11
+ """
12
+ Stores keypoint **annotation** data. GT Instances have a `gt_keypoints` property
13
+ containing the x,y location and visibility flag of each keypoint. This tensor has shape
14
+ (N, K, 3) where N is the number of instances and K is the number of keypoints per instance.
15
+
16
+ The visibility flag follows the COCO format and must be one of three integers:
17
+
18
+ * v=0: not labeled (in which case x=y=0)
19
+ * v=1: labeled but not visible
20
+ * v=2: labeled and visible
21
+ """
22
+
23
+ def __init__(self, keypoints: Union[torch.Tensor, np.ndarray, List[List[float]]]):
24
+ """
25
+ Arguments:
26
+ keypoints: A Tensor, numpy array, or list of the x, y, and visibility of each keypoint.
27
+ The shape should be (N, K, 3) where N is the number of
28
+ instances, and K is the number of keypoints per instance.
29
+ """
30
+ device = (
31
+ keypoints.device
32
+ if isinstance(keypoints, torch.Tensor)
33
+ else torch.device("cpu")
34
+ )
35
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=device)
36
+ assert keypoints.dim() == 3 and keypoints.shape[2] == 3, keypoints.shape
37
+ self.tensor = keypoints
38
+
39
+ def __len__(self) -> int:
40
+ return self.tensor.size(0)
41
+
42
+ def to(self, *args: Any, **kwargs: Any) -> "Keypoints":
43
+ return type(self)(self.tensor.to(*args, **kwargs))
44
+
45
+ @property
46
+ def device(self) -> torch.device:
47
+ return self.tensor.device
48
+
49
+ def to_heatmap(self, boxes: torch.Tensor, heatmap_size: int) -> torch.Tensor:
50
+ """
51
+ Convert keypoint annotations to a heatmap of one-hot labels for training,
52
+ as described in :paper:`Mask R-CNN`.
53
+
54
+ Arguments:
55
+ boxes: Nx4 tensor, the boxes to draw the keypoints to
56
+
57
+ Returns:
58
+ heatmaps:
59
+ A tensor of shape (N, K), each element is integer spatial label
60
+ in the range [0, heatmap_size**2 - 1] for each keypoint in the input.
61
+ valid:
62
+ A tensor of shape (N, K) containing whether each keypoint is in the roi or not.
63
+ """
64
+ return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)
65
+
66
+ def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Keypoints":
67
+ """
68
+ Create a new `Keypoints` by indexing on this `Keypoints`.
69
+
70
+ The following usage are allowed:
71
+
72
+ 1. `new_kpts = kpts[3]`: return a `Keypoints` which contains only one instance.
73
+ 2. `new_kpts = kpts[2:10]`: return a slice of key points.
74
+ 3. `new_kpts = kpts[vector]`, where vector is a torch.ByteTensor
75
+ with `length = len(kpts)`. Nonzero elements in the vector will be selected.
76
+
77
+ Note that the returned Keypoints might share storage with this Keypoints,
78
+ subject to Pytorch's indexing semantics.
79
+ """
80
+ if isinstance(item, int):
81
+ return Keypoints([self.tensor[item]])
82
+ return Keypoints(self.tensor[item])
83
+
84
+ def __repr__(self) -> str:
85
+ s = self.__class__.__name__ + "("
86
+ s += "num_instances={})".format(len(self.tensor))
87
+ return s
88
+
89
+ @staticmethod
90
+ def cat(keypoints_list: List["Keypoints"]) -> "Keypoints":
91
+ """
92
+ Concatenates a list of Keypoints into a single Keypoints
93
+
94
+ Arguments:
95
+ keypoints_list (list[Keypoints])
96
+
97
+ Returns:
98
+ Keypoints: the concatenated Keypoints
99
+ """
100
+ assert isinstance(keypoints_list, (list, tuple))
101
+ assert len(keypoints_list) > 0
102
+ assert all(isinstance(keypoints, Keypoints) for keypoints in keypoints_list)
103
+
104
+ cat_kpts = type(keypoints_list[0])(
105
+ torch.cat([kpts.tensor for kpts in keypoints_list], dim=0)
106
+ )
107
+ return cat_kpts
108
+
109
+
110
+ def _keypoints_to_heatmap(
111
+ keypoints: torch.Tensor, rois: torch.Tensor, heatmap_size: int
112
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
113
+ """
114
+ Encode keypoint locations into a target heatmap for use in SoftmaxWithLoss across space.
115
+
116
+ Maps keypoints from the half-open interval [x1, x2) on continuous image coordinates to the
117
+ closed interval [0, heatmap_size - 1] on discrete image coordinates. We use the
118
+ continuous-discrete conversion from Heckbert 1990 ("What is the coordinate of a pixel?"):
119
+ d = floor(c) and c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.
120
+
121
+ Arguments:
122
+ keypoints: tensor of keypoint locations in of shape (N, K, 3).
123
+ rois: Nx4 tensor of rois in xyxy format
124
+ heatmap_size: integer side length of square heatmap.
125
+
126
+ Returns:
127
+ heatmaps: A tensor of shape (N, K) containing an integer spatial label
128
+ in the range [0, heatmap_size**2 - 1] for each keypoint in the input.
129
+ valid: A tensor of shape (N, K) containing whether each keypoint is in
130
+ the roi or not.
131
+ """
132
+
133
+ if rois.numel() == 0:
134
+ return rois.new().long(), rois.new().long()
135
+ offset_x = rois[:, 0]
136
+ offset_y = rois[:, 1]
137
+ scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
138
+ scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
139
+
140
+ offset_x = offset_x[:, None]
141
+ offset_y = offset_y[:, None]
142
+ scale_x = scale_x[:, None]
143
+ scale_y = scale_y[:, None]
144
+
145
+ x = keypoints[..., 0]
146
+ y = keypoints[..., 1]
147
+
148
+ x_boundary_inds = x == rois[:, 2][:, None]
149
+ y_boundary_inds = y == rois[:, 3][:, None]
150
+
151
+ x = (x - offset_x) * scale_x
152
+ x = x.floor().long()
153
+ y = (y - offset_y) * scale_y
154
+ y = y.floor().long()
155
+
156
+ x[x_boundary_inds] = heatmap_size - 1
157
+ y[y_boundary_inds] = heatmap_size - 1
158
+
159
+ valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
160
+ vis = keypoints[..., 2] > 0
161
+ valid = (valid_loc & vis).long()
162
+
163
+ lin_ind = y * heatmap_size + x
164
+ heatmaps = lin_ind * valid
165
+
166
+ return heatmaps, valid
167
+
168
+
169
+ @torch.jit.script_if_tracing
170
+ def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:
171
+ """
172
+ Extract predicted keypoint locations from heatmaps.
173
+
174
+ Args:
175
+ maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for
176
+ each ROI and each keypoint.
177
+ rois (Tensor): (#ROIs, 4). The box of each ROI.
178
+
179
+ Returns:
180
+ Tensor of shape (#ROIs, #keypoints, 4) with the last dimension corresponding to
181
+ (x, y, logit, score) for each keypoint.
182
+
183
+ When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate,
184
+ we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from
185
+ Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.
186
+ """
187
+
188
+ offset_x = rois[:, 0]
189
+ offset_y = rois[:, 1]
190
+
191
+ widths = (rois[:, 2] - rois[:, 0]).clamp(min=1)
192
+ heights = (rois[:, 3] - rois[:, 1]).clamp(min=1)
193
+ widths_ceil = widths.ceil()
194
+ heights_ceil = heights.ceil()
195
+
196
+ num_rois, num_keypoints = maps.shape[:2]
197
+ xy_preds = maps.new_zeros(rois.shape[0], num_keypoints, 4)
198
+
199
+ width_corrections = widths / widths_ceil
200
+ height_corrections = heights / heights_ceil
201
+
202
+ keypoints_idx = torch.arange(num_keypoints, device=maps.device)
203
+
204
+ for i in range(num_rois):
205
+ outsize = (int(heights_ceil[i]), int(widths_ceil[i]))
206
+ roi_map = F.interpolate(
207
+ maps[[i]], size=outsize, mode="bicubic", align_corners=False
208
+ )
209
+
210
+ # Although semantically equivalent, `reshape` is used instead of `squeeze` due
211
+ # to limitation during ONNX export of `squeeze` in scripting mode
212
+ roi_map = roi_map.reshape(roi_map.shape[1:]) # keypoints x H x W
213
+
214
+ # softmax over the spatial region
215
+ max_score, _ = roi_map.view(num_keypoints, -1).max(1)
216
+ max_score = max_score.view(num_keypoints, 1, 1)
217
+ tmp_full_resolution = (roi_map - max_score).exp_()
218
+ tmp_pool_resolution = (maps[i] - max_score).exp_()
219
+ # Produce scores over the region H x W, but normalize with POOL_H x POOL_W,
220
+ # so that the scores of objects of different absolute sizes will be more comparable
221
+ roi_map_scores = tmp_full_resolution / tmp_pool_resolution.sum(
222
+ (1, 2), keepdim=True
223
+ )
224
+
225
+ w = roi_map.shape[2]
226
+ pos = roi_map.view(num_keypoints, -1).argmax(1)
227
+
228
+ x_int = pos % w
229
+ y_int = (pos - x_int) // w
230
+
231
+ assert (
232
+ roi_map_scores[keypoints_idx, y_int, x_int]
233
+ == roi_map_scores.view(num_keypoints, -1).max(1)[0]
234
+ ).all()
235
+
236
+ x = (x_int.float() + 0.5) * width_corrections[i]
237
+ y = (y_int.float() + 0.5) * height_corrections[i]
238
+
239
+ xy_preds[i, :, 0] = x + offset_x[i]
240
+ xy_preds[i, :, 1] = y + offset_y[i]
241
+ xy_preds[i, :, 2] = roi_map[keypoints_idx, y_int, x_int]
242
+ xy_preds[i, :, 3] = roi_map_scores[keypoints_idx, y_int, x_int]
243
+
244
+ return xy_preds
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/mask_overlap_removal.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from typing import Dict, List
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ try:
9
+ from pycocotools import mask as mask_utils
10
+ except Exception:
11
+ mask_utils = None
12
+
13
+
14
+ def mask_intersection(
15
+ masks1: torch.Tensor, masks2: torch.Tensor, block_size: int = 16
16
+ ) -> torch.Tensor:
17
+ assert masks1.shape[1:] == masks2.shape[1:]
18
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
19
+ N, M = masks1.shape[0], masks2.shape[0]
20
+ out = torch.zeros(N, M, device=masks1.device, dtype=torch.long)
21
+ for i in range(0, N, block_size):
22
+ for j in range(0, M, block_size):
23
+ a = masks1[i : i + block_size]
24
+ b = masks2[j : j + block_size]
25
+ inter = (a[:, None] & b[None, :]).flatten(-2).sum(-1)
26
+ out[i : i + block_size, j : j + block_size] = inter
27
+ return out
28
+
29
+
30
+ def mask_iom(masks1: torch.Tensor, masks2: torch.Tensor) -> torch.Tensor:
31
+ assert masks1.shape[1:] == masks2.shape[1:]
32
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
33
+ inter = mask_intersection(masks1, masks2)
34
+ area1 = masks1.flatten(-2).sum(-1) # (N,)
35
+ area2 = masks2.flatten(-2).sum(-1) # (M,)
36
+ min_area = torch.min(area1[:, None], area2[None, :]).clamp_min(1)
37
+ return inter.float() / (min_area.float() + 1e-8)
38
+
39
+
40
+ def _decode_single_mask(mask_repr, h: int, w: int) -> np.ndarray:
41
+ if isinstance(mask_repr, (list, tuple, np.ndarray)):
42
+ arr = np.array(mask_repr)
43
+ if arr.ndim != 2:
44
+ raise ValueError("Mask array must be 2D (H, W).")
45
+ return (arr > 0).astype(np.uint8)
46
+
47
+ if mask_utils is None:
48
+ raise ImportError(
49
+ "pycocotools is required to decode RLE mask strings. pip install pycocotools"
50
+ )
51
+
52
+ if not isinstance(mask_repr, (str, bytes)):
53
+ raise ValueError("Unsupported mask representation type for RLE decode.")
54
+
55
+ rle = {
56
+ "counts": mask_repr if isinstance(mask_repr, (str, bytes)) else str(mask_repr),
57
+ "size": [h, w],
58
+ }
59
+ decoded = mask_utils.decode(rle)
60
+ if decoded.ndim == 3:
61
+ decoded = decoded[:, :, 0]
62
+ return (decoded > 0).astype(np.uint8)
63
+
64
+
65
+ def _decode_masks_to_torch_bool(pred_masks: List, h: int, w: int) -> torch.Tensor:
66
+ bin_masks = [_decode_single_mask(m, h, w) for m in pred_masks]
67
+ masks_np = np.stack(bin_masks, axis=0).astype(np.uint8) # (N, H, W)
68
+ return torch.from_numpy(masks_np > 0)
69
+
70
+
71
+ def remove_overlapping_masks(sample: Dict, iom_thresh: float = 0.3) -> Dict:
72
+ """
73
+ Greedy keep: sort by score desc; keep a mask if IoM to all kept masks <= threshold.
74
+ If pred_masks has length 0 or 1, returns sample unchanged (no extra keys).
75
+ """
76
+ # Basic presence checks
77
+ if "pred_masks" not in sample or not isinstance(sample["pred_masks"], list):
78
+ return sample # nothing to do / preserve as-is
79
+
80
+ pred_masks = sample["pred_masks"]
81
+ N = len(pred_masks)
82
+
83
+ # --- Early exit: 0 or 1 mask -> do NOT modify the JSON at all ---
84
+ if N <= 1:
85
+ return sample
86
+
87
+ # From here on we have at least 2 masks
88
+ h = int(sample["orig_img_h"])
89
+ w = int(sample["orig_img_w"])
90
+ pred_scores = sample.get("pred_scores", [1.0] * N) # fallback if scores missing
91
+ pred_boxes = sample.get("pred_boxes", None)
92
+
93
+ assert N == len(pred_scores), "pred_masks and pred_scores must have same length"
94
+ if pred_boxes is not None:
95
+ assert N == len(pred_boxes), "pred_masks and pred_boxes must have same length"
96
+
97
+ masks_bool = _decode_masks_to_torch_bool(pred_masks, h, w) # (N, H, W)
98
+
99
+ order = sorted(range(N), key=lambda i: float(pred_scores[i]), reverse=True)
100
+ kept_idx: List[int] = []
101
+ kept_masks: List[torch.Tensor] = []
102
+
103
+ for i in order:
104
+ cand = masks_bool[i].unsqueeze(0) # (1, H, W)
105
+ if len(kept_masks) == 0:
106
+ kept_idx.append(i)
107
+ kept_masks.append(masks_bool[i])
108
+ continue
109
+
110
+ kept_stack = torch.stack(kept_masks, dim=0) # (K, H, W)
111
+ iom_vals = mask_iom(cand, kept_stack).squeeze(0) # (K,)
112
+ if torch.any(iom_vals > iom_thresh):
113
+ continue # overlaps too much with a higher-scored kept mask
114
+ kept_idx.append(i)
115
+ kept_masks.append(masks_bool[i])
116
+
117
+ kept_idx_sorted = sorted(kept_idx)
118
+
119
+ # Build filtered JSON (this *does* modify fields; only for N>=2 case)
120
+ out = dict(sample)
121
+ out["pred_masks"] = [pred_masks[i] for i in kept_idx_sorted]
122
+ out["pred_scores"] = [pred_scores[i] for i in kept_idx_sorted]
123
+ if pred_boxes is not None:
124
+ out["pred_boxes"] = [pred_boxes[i] for i in kept_idx_sorted]
125
+ out["kept_indices"] = kept_idx_sorted
126
+ out["removed_indices"] = [i for i in range(N) if i not in set(kept_idx_sorted)]
127
+ out["iom_threshold"] = float(iom_thresh)
128
+ return out
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/masks.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import copy
4
+ import itertools
5
+ from typing import Any, Iterator, List, Union
6
+
7
+ import numpy as np
8
+ import pycocotools.mask as mask_util
9
+ import torch
10
+ from torch import device
11
+
12
+ from .boxes import Boxes
13
+ from .memory import retry_if_cuda_oom
14
+
15
+ from .roi_align import ROIAlign
16
+
17
+
18
+ def polygon_area(x, y):
19
+ # Using the shoelace formula
20
+ # https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
21
+ return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
22
+
23
+
24
+ def polygons_to_bitmask(
25
+ polygons: List[np.ndarray], height: int, width: int
26
+ ) -> np.ndarray:
27
+ """
28
+ Args:
29
+ polygons (list[ndarray]): each array has shape (Nx2,)
30
+ height, width (int)
31
+
32
+ Returns:
33
+ ndarray: a bool mask of shape (height, width)
34
+ """
35
+ if len(polygons) == 0:
36
+ # COCOAPI does not support empty polygons
37
+ return np.zeros((height, width)).astype(bool)
38
+ rles = mask_util.frPyObjects(polygons, height, width)
39
+ rle = mask_util.merge(rles)
40
+ return mask_util.decode(rle).astype(bool)
41
+
42
+
43
+ def rasterize_polygons_within_box(
44
+ polygons: List[np.ndarray], box: np.ndarray, mask_size: int
45
+ ) -> torch.Tensor:
46
+ """
47
+ Rasterize the polygons into a mask image and
48
+ crop the mask content in the given box.
49
+ The cropped mask is resized to (mask_size, mask_size).
50
+
51
+ This function is used when generating training targets for mask head in Mask R-CNN.
52
+ Given original ground-truth masks for an image, new ground-truth mask
53
+ training targets in the size of `mask_size x mask_size`
54
+ must be provided for each predicted box. This function will be called to
55
+ produce such targets.
56
+
57
+ Args:
58
+ polygons (list[ndarray[float]]): a list of polygons, which represents an instance.
59
+ box: 4-element numpy array
60
+ mask_size (int):
61
+
62
+ Returns:
63
+ Tensor: BoolTensor of shape (mask_size, mask_size)
64
+ """
65
+ # 1. Shift the polygons w.r.t the boxes
66
+ w, h = box[2] - box[0], box[3] - box[1]
67
+
68
+ polygons = copy.deepcopy(polygons)
69
+ for p in polygons:
70
+ p[0::2] = p[0::2] - box[0]
71
+ p[1::2] = p[1::2] - box[1]
72
+
73
+ # 2. Rescale the polygons to the new box size
74
+ # max() to avoid division by small number
75
+ ratio_h = mask_size / max(h, 0.1)
76
+ ratio_w = mask_size / max(w, 0.1)
77
+
78
+ if ratio_h == ratio_w:
79
+ for p in polygons:
80
+ p *= ratio_h
81
+ else:
82
+ for p in polygons:
83
+ p[0::2] *= ratio_w
84
+ p[1::2] *= ratio_h
85
+
86
+ # 3. Rasterize the polygons with coco api
87
+ mask = polygons_to_bitmask(polygons, mask_size, mask_size)
88
+ mask = torch.from_numpy(mask)
89
+ return mask
90
+
91
+
92
+ class BitMasks:
93
+ """
94
+ This class stores the segmentation masks for all objects in one image, in
95
+ the form of bitmaps.
96
+
97
+ Attributes:
98
+ tensor: bool Tensor of N,H,W, representing N instances in the image.
99
+ """
100
+
101
+ def __init__(self, tensor: Union[torch.Tensor, np.ndarray]):
102
+ """
103
+ Args:
104
+ tensor: bool Tensor of N,H,W, representing N instances in the image.
105
+ """
106
+ if isinstance(tensor, torch.Tensor):
107
+ tensor = tensor.to(torch.bool)
108
+ else:
109
+ tensor = torch.as_tensor(
110
+ tensor, dtype=torch.bool, device=torch.device("cpu")
111
+ )
112
+ assert tensor.dim() == 3, tensor.size()
113
+ self.image_size = tensor.shape[1:]
114
+ self.tensor = tensor
115
+
116
+ @torch.jit.unused
117
+ def to(self, *args: Any, **kwargs: Any) -> "BitMasks":
118
+ return BitMasks(self.tensor.to(*args, **kwargs))
119
+
120
+ @property
121
+ def device(self) -> torch.device:
122
+ return self.tensor.device
123
+
124
+ @torch.jit.unused
125
+ def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "BitMasks":
126
+ """
127
+ Returns:
128
+ BitMasks: Create a new :class:`BitMasks` by indexing.
129
+
130
+ The following usage are allowed:
131
+
132
+ 1. `new_masks = masks[3]`: return a `BitMasks` which contains only one mask.
133
+ 2. `new_masks = masks[2:10]`: return a slice of masks.
134
+ 3. `new_masks = masks[vector]`, where vector is a torch.BoolTensor
135
+ with `length = len(masks)`. Nonzero elements in the vector will be selected.
136
+
137
+ Note that the returned object might share storage with this object,
138
+ subject to Pytorch's indexing semantics.
139
+ """
140
+ if isinstance(item, int):
141
+ return BitMasks(self.tensor[item].unsqueeze(0))
142
+ m = self.tensor[item]
143
+ assert (
144
+ m.dim() == 3
145
+ ), "Indexing on BitMasks with {} returns a tensor with shape {}!".format(
146
+ item, m.shape
147
+ )
148
+ return BitMasks(m)
149
+
150
+ @torch.jit.unused
151
+ def __iter__(self) -> torch.Tensor:
152
+ yield from self.tensor
153
+
154
+ @torch.jit.unused
155
+ def __repr__(self) -> str:
156
+ s = self.__class__.__name__ + "("
157
+ s += "num_instances={})".format(len(self.tensor))
158
+ return s
159
+
160
+ def __len__(self) -> int:
161
+ return self.tensor.shape[0]
162
+
163
+ def nonempty(self) -> torch.Tensor:
164
+ """
165
+ Find masks that are non-empty.
166
+
167
+ Returns:
168
+ Tensor: a BoolTensor which represents
169
+ whether each mask is empty (False) or non-empty (True).
170
+ """
171
+ return self.tensor.flatten(1).any(dim=1)
172
+
173
+ @staticmethod
174
+ def from_polygon_masks(
175
+ polygon_masks: Union["PolygonMasks", List[List[np.ndarray]]],
176
+ height: int,
177
+ width: int,
178
+ ) -> "BitMasks":
179
+ """
180
+ Args:
181
+ polygon_masks (list[list[ndarray]] or PolygonMasks)
182
+ height, width (int)
183
+ """
184
+ if isinstance(polygon_masks, PolygonMasks):
185
+ polygon_masks = polygon_masks.polygons
186
+ masks = [polygons_to_bitmask(p, height, width) for p in polygon_masks]
187
+ if len(masks):
188
+ return BitMasks(torch.stack([torch.from_numpy(x) for x in masks]))
189
+ else:
190
+ return BitMasks(torch.empty(0, height, width, dtype=torch.bool))
191
+
192
+ @staticmethod
193
+ def from_roi_masks(roi_masks: "ROIMasks", height: int, width: int) -> "BitMasks":
194
+ """
195
+ Args:
196
+ roi_masks:
197
+ height, width (int):
198
+ """
199
+ return roi_masks.to_bitmasks(height, width)
200
+
201
+ def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:
202
+ """
203
+ Crop each bitmask by the given box, and resize results to (mask_size, mask_size).
204
+ This can be used to prepare training targets for Mask R-CNN.
205
+ It has less reconstruction error compared to rasterization with polygons.
206
+ However we observe no difference in accuracy,
207
+ but BitMasks requires more memory to store all the masks.
208
+
209
+ Args:
210
+ boxes (Tensor): Nx4 tensor storing the boxes for each mask
211
+ mask_size (int): the size of the rasterized mask.
212
+
213
+ Returns:
214
+ Tensor:
215
+ A bool tensor of shape (N, mask_size, mask_size), where
216
+ N is the number of predicted boxes for this image.
217
+ """
218
+ assert len(boxes) == len(self), "{} != {}".format(len(boxes), len(self))
219
+ device = self.tensor.device
220
+
221
+ batch_inds = torch.arange(len(boxes), device=device).to(dtype=boxes.dtype)[
222
+ :, None
223
+ ]
224
+ rois = torch.cat([batch_inds, boxes], dim=1) # Nx5
225
+
226
+ bit_masks = self.tensor.to(dtype=torch.float32)
227
+ rois = rois.to(device=device)
228
+ output = (
229
+ ROIAlign((mask_size, mask_size), 1.0, 0, aligned=True)
230
+ .forward(bit_masks[:, None, :, :], rois)
231
+ .squeeze(1)
232
+ )
233
+ output = output >= 0.5
234
+ return output
235
+
236
+ def get_bounding_boxes(self) -> Boxes:
237
+ """
238
+ Returns:
239
+ Boxes: tight bounding boxes around bitmasks.
240
+ If a mask is empty, it's bounding box will be all zero.
241
+ """
242
+ boxes = torch.zeros(self.tensor.shape[0], 4, dtype=torch.float32)
243
+ x_any = torch.any(self.tensor, dim=1)
244
+ y_any = torch.any(self.tensor, dim=2)
245
+ for idx in range(self.tensor.shape[0]):
246
+ x = torch.where(x_any[idx, :])[0]
247
+ y = torch.where(y_any[idx, :])[0]
248
+ if len(x) > 0 and len(y) > 0:
249
+ boxes[idx, :] = torch.as_tensor(
250
+ [x[0], y[0], x[-1] + 1, y[-1] + 1], dtype=torch.float32
251
+ )
252
+ return Boxes(boxes)
253
+
254
+ @staticmethod
255
+ def cat(bitmasks_list: List["BitMasks"]) -> "BitMasks":
256
+ """
257
+ Concatenates a list of BitMasks into a single BitMasks
258
+
259
+ Arguments:
260
+ bitmasks_list (list[BitMasks])
261
+
262
+ Returns:
263
+ BitMasks: the concatenated BitMasks
264
+ """
265
+ assert isinstance(bitmasks_list, (list, tuple))
266
+ assert len(bitmasks_list) > 0
267
+ assert all(isinstance(bitmask, BitMasks) for bitmask in bitmasks_list)
268
+
269
+ cat_bitmasks = type(bitmasks_list[0])(
270
+ torch.cat([bm.tensor for bm in bitmasks_list], dim=0)
271
+ )
272
+ return cat_bitmasks
273
+
274
+
275
+ class PolygonMasks:
276
+ """
277
+ This class stores the segmentation masks for all objects in one image, in the form of polygons.
278
+
279
+ Attributes:
280
+ polygons: list[list[ndarray]]. Each ndarray is a float64 vector representing a polygon.
281
+ """
282
+
283
+ def __init__(self, polygons: List[List[Union[torch.Tensor, np.ndarray]]]):
284
+ """
285
+ Arguments:
286
+ polygons (list[list[np.ndarray]]): The first
287
+ level of the list correspond to individual instances,
288
+ the second level to all the polygons that compose the
289
+ instance, and the third level to the polygon coordinates.
290
+ The third level array should have the format of
291
+ [x0, y0, x1, y1, ..., xn, yn] (n >= 3).
292
+ """
293
+ if not isinstance(polygons, list):
294
+ raise ValueError(
295
+ "Cannot create PolygonMasks: Expect a list of list of polygons per image. "
296
+ "Got '{}' instead.".format(type(polygons))
297
+ )
298
+
299
+ def _make_array(t: Union[torch.Tensor, np.ndarray]) -> np.ndarray:
300
+ # Use float64 for higher precision, because why not?
301
+ # Always put polygons on CPU (self.to is a no-op) since they
302
+ # are supposed to be small tensors.
303
+ # May need to change this assumption if GPU placement becomes useful
304
+ if isinstance(t, torch.Tensor):
305
+ t = t.cpu().numpy()
306
+ return np.asarray(t).astype("float64")
307
+
308
+ def process_polygons(
309
+ polygons_per_instance: List[Union[torch.Tensor, np.ndarray]],
310
+ ) -> List[np.ndarray]:
311
+ if not isinstance(polygons_per_instance, list):
312
+ raise ValueError(
313
+ "Cannot create polygons: Expect a list of polygons per instance. "
314
+ "Got '{}' instead.".format(type(polygons_per_instance))
315
+ )
316
+ # transform each polygon to a numpy array
317
+ polygons_per_instance = [_make_array(p) for p in polygons_per_instance]
318
+ for polygon in polygons_per_instance:
319
+ if len(polygon) % 2 != 0 or len(polygon) < 6:
320
+ raise ValueError(
321
+ f"Cannot create a polygon from {len(polygon)} coordinates."
322
+ )
323
+ return polygons_per_instance
324
+
325
+ self.polygons: List[List[np.ndarray]] = [
326
+ process_polygons(polygons_per_instance)
327
+ for polygons_per_instance in polygons
328
+ ]
329
+
330
+ def to(self, *args: Any, **kwargs: Any) -> "PolygonMasks":
331
+ return self
332
+
333
+ @property
334
+ def device(self) -> torch.device:
335
+ return torch.device("cpu")
336
+
337
+ def get_bounding_boxes(self) -> Boxes:
338
+ """
339
+ Returns:
340
+ Boxes: tight bounding boxes around polygon masks.
341
+ """
342
+ boxes = torch.zeros(len(self.polygons), 4, dtype=torch.float32)
343
+ for idx, polygons_per_instance in enumerate(self.polygons):
344
+ minxy = torch.as_tensor([float("inf"), float("inf")], dtype=torch.float32)
345
+ maxxy = torch.zeros(2, dtype=torch.float32)
346
+ for polygon in polygons_per_instance:
347
+ coords = torch.from_numpy(polygon).view(-1, 2).to(dtype=torch.float32)
348
+ minxy = torch.min(minxy, torch.min(coords, dim=0).values)
349
+ maxxy = torch.max(maxxy, torch.max(coords, dim=0).values)
350
+ boxes[idx, :2] = minxy
351
+ boxes[idx, 2:] = maxxy
352
+ return Boxes(boxes)
353
+
354
+ def nonempty(self) -> torch.Tensor:
355
+ """
356
+ Find masks that are non-empty.
357
+
358
+ Returns:
359
+ Tensor:
360
+ a BoolTensor which represents whether each mask is empty (False) or not (True).
361
+ """
362
+ keep = [1 if len(polygon) > 0 else 0 for polygon in self.polygons]
363
+ return torch.from_numpy(np.asarray(keep, dtype=bool))
364
+
365
+ def __getitem__(
366
+ self, item: Union[int, slice, List[int], torch.BoolTensor]
367
+ ) -> "PolygonMasks":
368
+ """
369
+ Support indexing over the instances and return a `PolygonMasks` object.
370
+ `item` can be:
371
+
372
+ 1. An integer. It will return an object with only one instance.
373
+ 2. A slice. It will return an object with the selected instances.
374
+ 3. A list[int]. It will return an object with the selected instances,
375
+ correpsonding to the indices in the list.
376
+ 4. A vector mask of type BoolTensor, whose length is num_instances.
377
+ It will return an object with the instances whose mask is nonzero.
378
+ """
379
+ if isinstance(item, int):
380
+ selected_polygons = [self.polygons[item]]
381
+ elif isinstance(item, slice):
382
+ selected_polygons = self.polygons[item]
383
+ elif isinstance(item, list):
384
+ selected_polygons = [self.polygons[i] for i in item]
385
+ elif isinstance(item, torch.Tensor):
386
+ # Polygons is a list, so we have to move the indices back to CPU.
387
+ if item.dtype == torch.bool:
388
+ assert item.dim() == 1, item.shape
389
+ item = item.nonzero().squeeze(1).cpu().numpy().tolist()
390
+ elif item.dtype in [torch.int32, torch.int64]:
391
+ item = item.cpu().numpy().tolist()
392
+ else:
393
+ raise ValueError(
394
+ "Unsupported tensor dtype={} for indexing!".format(item.dtype)
395
+ )
396
+ selected_polygons = [self.polygons[i] for i in item]
397
+ return PolygonMasks(selected_polygons)
398
+
399
+ def __iter__(self) -> Iterator[List[np.ndarray]]:
400
+ """
401
+ Yields:
402
+ list[ndarray]: the polygons for one instance.
403
+ Each Tensor is a float64 vector representing a polygon.
404
+ """
405
+ return iter(self.polygons)
406
+
407
+ def __repr__(self) -> str:
408
+ s = self.__class__.__name__ + "("
409
+ s += "num_instances={})".format(len(self.polygons))
410
+ return s
411
+
412
+ def __len__(self) -> int:
413
+ return len(self.polygons)
414
+
415
+ def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:
416
+ """
417
+ Crop each mask by the given box, and resize results to (mask_size, mask_size).
418
+ This can be used to prepare training targets for Mask R-CNN.
419
+
420
+ Args:
421
+ boxes (Tensor): Nx4 tensor storing the boxes for each mask
422
+ mask_size (int): the size of the rasterized mask.
423
+
424
+ Returns:
425
+ Tensor: A bool tensor of shape (N, mask_size, mask_size), where
426
+ N is the number of predicted boxes for this image.
427
+ """
428
+ assert len(boxes) == len(self), "{} != {}".format(len(boxes), len(self))
429
+
430
+ device = boxes.device
431
+ # Put boxes on the CPU, as the polygon representation is not efficient GPU-wise
432
+ # (several small tensors for representing a single instance mask)
433
+ boxes = boxes.to(torch.device("cpu"))
434
+
435
+ results = [
436
+ rasterize_polygons_within_box(poly, box.numpy(), mask_size)
437
+ for poly, box in zip(self.polygons, boxes)
438
+ ]
439
+ """
440
+ poly: list[list[float]], the polygons for one instance
441
+ box: a tensor of shape (4,)
442
+ """
443
+ if len(results) == 0:
444
+ return torch.empty(0, mask_size, mask_size, dtype=torch.bool, device=device)
445
+ return torch.stack(results, dim=0).to(device=device)
446
+
447
+ def area(self):
448
+ """
449
+ Computes area of the mask.
450
+ Only works with Polygons, using the shoelace formula:
451
+ https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
452
+
453
+ Returns:
454
+ Tensor: a vector, area for each instance
455
+ """
456
+
457
+ area = []
458
+ for polygons_per_instance in self.polygons:
459
+ area_per_instance = 0
460
+ for p in polygons_per_instance:
461
+ area_per_instance += polygon_area(p[0::2], p[1::2])
462
+ area.append(area_per_instance)
463
+
464
+ return torch.tensor(area)
465
+
466
+ @staticmethod
467
+ def cat(polymasks_list: List["PolygonMasks"]) -> "PolygonMasks":
468
+ """
469
+ Concatenates a list of PolygonMasks into a single PolygonMasks
470
+
471
+ Arguments:
472
+ polymasks_list (list[PolygonMasks])
473
+
474
+ Returns:
475
+ PolygonMasks: the concatenated PolygonMasks
476
+ """
477
+ assert isinstance(polymasks_list, (list, tuple))
478
+ assert len(polymasks_list) > 0
479
+ assert all(isinstance(polymask, PolygonMasks) for polymask in polymasks_list)
480
+
481
+ cat_polymasks = type(polymasks_list[0])(
482
+ list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list))
483
+ )
484
+ return cat_polymasks
485
+
486
+
487
+ class ROIMasks:
488
+ """
489
+ Represent masks by N smaller masks defined in some ROIs. Once ROI boxes are given,
490
+ full-image bitmask can be obtained by "pasting" the mask on the region defined
491
+ by the corresponding ROI box.
492
+ """
493
+
494
+ def __init__(self, tensor: torch.Tensor):
495
+ """
496
+ Args:
497
+ tensor: (N, M, M) mask tensor that defines the mask within each ROI.
498
+ """
499
+ if tensor.dim() != 3:
500
+ raise ValueError("ROIMasks must take a masks of 3 dimension.")
501
+ self.tensor = tensor
502
+
503
+ def to(self, device: torch.device) -> "ROIMasks":
504
+ return ROIMasks(self.tensor.to(device))
505
+
506
+ @property
507
+ def device(self) -> device:
508
+ return self.tensor.device
509
+
510
+ def __len__(self):
511
+ return self.tensor.shape[0]
512
+
513
+ def __getitem__(self, item) -> "ROIMasks":
514
+ """
515
+ Returns:
516
+ ROIMasks: Create a new :class:`ROIMasks` by indexing.
517
+
518
+ The following usage are allowed:
519
+
520
+ 1. `new_masks = masks[2:10]`: return a slice of masks.
521
+ 2. `new_masks = masks[vector]`, where vector is a torch.BoolTensor
522
+ with `length = len(masks)`. Nonzero elements in the vector will be selected.
523
+
524
+ Note that the returned object might share storage with this object,
525
+ subject to Pytorch's indexing semantics.
526
+ """
527
+ t = self.tensor[item]
528
+ if t.dim() != 3:
529
+ raise ValueError(
530
+ f"Indexing on ROIMasks with {item} returns a tensor with shape {t.shape}!"
531
+ )
532
+ return ROIMasks(t)
533
+
534
+ @torch.jit.unused
535
+ def __repr__(self) -> str:
536
+ s = self.__class__.__name__ + "("
537
+ s += "num_instances={})".format(len(self.tensor))
538
+ return s
539
+
540
+ @torch.jit.unused
541
+ def to_bitmasks(self, boxes: torch.Tensor, height, width, threshold=0.5):
542
+ """
543
+ Args: see documentation of :func:`paste_masks_in_image`.
544
+ """
545
+ from detectron2.layers.mask_ops import (
546
+ _paste_masks_tensor_shape,
547
+ paste_masks_in_image,
548
+ )
549
+
550
+ if torch.jit.is_tracing():
551
+ if isinstance(height, torch.Tensor):
552
+ paste_func = _paste_masks_tensor_shape
553
+ else:
554
+ paste_func = paste_masks_in_image
555
+ else:
556
+ paste_func = retry_if_cuda_oom(paste_masks_in_image)
557
+ bitmasks = paste_func(
558
+ self.tensor, boxes.tensor, (height, width), threshold=threshold
559
+ )
560
+ return BitMasks(bitmasks)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/memory.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ from contextlib import contextmanager
5
+ from functools import wraps
6
+
7
+ import torch
8
+
9
+ __all__ = ["retry_if_cuda_oom"]
10
+
11
+
12
+ @contextmanager
13
+ def _ignore_torch_cuda_oom():
14
+ """
15
+ A context which ignores CUDA OOM exception from pytorch.
16
+ """
17
+ try:
18
+ yield
19
+ except RuntimeError as e:
20
+ # NOTE: the string may change?
21
+ if "CUDA out of memory. " in str(e):
22
+ pass
23
+ else:
24
+ raise
25
+
26
+
27
+ def retry_if_cuda_oom(func):
28
+ """
29
+ Makes a function retry itself after encountering
30
+ pytorch's CUDA OOM error.
31
+ It will first retry after calling `torch.cuda.empty_cache()`.
32
+
33
+ If that still fails, it will then retry by trying to convert inputs to CPUs.
34
+ In this case, it expects the function to dispatch to CPU implementation.
35
+ The return values may become CPU tensors as well and it's user's
36
+ responsibility to convert it back to CUDA tensor if needed.
37
+
38
+ Args:
39
+ func: a stateless callable that takes tensor-like objects as arguments
40
+
41
+ Returns:
42
+ a callable which retries `func` if OOM is encountered.
43
+
44
+ Examples:
45
+ ::
46
+ output = retry_if_cuda_oom(some_torch_function)(input1, input2)
47
+ # output may be on CPU even if inputs are on GPU
48
+
49
+ Note:
50
+ 1. When converting inputs to CPU, it will only look at each argument and check
51
+ if it has `.device` and `.to` for conversion. Nested structures of tensors
52
+ are not supported.
53
+
54
+ 2. Since the function might be called more than once, it has to be
55
+ stateless.
56
+ """
57
+
58
+ def maybe_to_cpu(x):
59
+ try:
60
+ like_gpu_tensor = x.device.type == "cuda" and hasattr(x, "to")
61
+ except AttributeError:
62
+ like_gpu_tensor = False
63
+ if like_gpu_tensor:
64
+ return x.to(device="cpu")
65
+ else:
66
+ return x
67
+
68
+ @wraps(func)
69
+ def wrapped(*args, **kwargs):
70
+ with _ignore_torch_cuda_oom():
71
+ return func(*args, **kwargs)
72
+
73
+ # Clear cache and retry
74
+ torch.cuda.empty_cache()
75
+ with _ignore_torch_cuda_oom():
76
+ return func(*args, **kwargs)
77
+
78
+ # Try on CPU. This slows down the code significantly, therefore print a notice.
79
+ logger = logging.getLogger(__name__)
80
+ logger.info(
81
+ "Attempting to copy inputs of {} to CPU due to CUDA OOM".format(str(func))
82
+ )
83
+ new_args = (maybe_to_cpu(x) for x in args)
84
+ new_kwargs = {k: maybe_to_cpu(v) for k, v in kwargs.items()}
85
+ return func(*new_args, **new_kwargs)
86
+
87
+ return wrapped
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/rle.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """Some utilities for RLE encoding that doesn't require downloading the masks to the cpu"""
4
+
5
+ import numpy as np
6
+ import torch
7
+ from pycocotools import mask as mask_util
8
+
9
+
10
+ @torch.no_grad()
11
+ def rle_encode(orig_mask, return_areas=False):
12
+ """Encodes a collection of masks in RLE format
13
+
14
+ This function emulates the behavior of the COCO API's encode function, but
15
+ is executed partially on the GPU for faster execution.
16
+
17
+ Args:
18
+ mask (torch.Tensor): A mask of shape (N, H, W) with dtype=torch.bool
19
+ return_areas (bool): If True, add the areas of the masks as a part of
20
+ the RLE output dict under the "area" key. Default is False.
21
+
22
+ Returns:
23
+ str: The RLE encoded masks
24
+ """
25
+ assert orig_mask.ndim == 3, "Mask must be of shape (N, H, W)"
26
+ assert orig_mask.dtype == torch.bool, "Mask must have dtype=torch.bool"
27
+
28
+ if orig_mask.numel() == 0:
29
+ return []
30
+
31
+ # First, transpose the spatial dimensions.
32
+ # This is necessary because the COCO API uses Fortran order
33
+ mask = orig_mask.transpose(1, 2)
34
+
35
+ # Flatten the mask
36
+ flat_mask = mask.reshape(mask.shape[0], -1)
37
+ if return_areas:
38
+ mask_areas = flat_mask.sum(-1).tolist()
39
+ # Find the indices where the mask changes
40
+ differences = torch.ones(
41
+ mask.shape[0], flat_mask.shape[1] + 1, device=mask.device, dtype=torch.bool
42
+ )
43
+ differences[:, 1:-1] = flat_mask[:, :-1] != flat_mask[:, 1:]
44
+ differences[:, 0] = flat_mask[:, 0]
45
+ _, change_indices = torch.where(differences)
46
+
47
+ try:
48
+ boundaries = torch.cumsum(differences.sum(-1), 0).cpu()
49
+ except RuntimeError as _:
50
+ boundaries = torch.cumsum(differences.cpu().sum(-1), 0)
51
+
52
+ change_indices_clone = change_indices.clone()
53
+ # First pass computes the RLEs on GPU, in a flatten format
54
+ for i in range(mask.shape[0]):
55
+ # Get the change indices for this batch item
56
+ beg = 0 if i == 0 else boundaries[i - 1].item()
57
+ end = boundaries[i].item()
58
+ change_indices[beg + 1 : end] -= change_indices_clone[beg : end - 1]
59
+
60
+ # Now we can split the RLES of each batch item, and convert them to strings
61
+ # No more gpu at this point
62
+ change_indices = change_indices.tolist()
63
+
64
+ batch_rles = []
65
+ # Process each mask in the batch separately
66
+ for i in range(mask.shape[0]):
67
+ beg = 0 if i == 0 else boundaries[i - 1].item()
68
+ end = boundaries[i].item()
69
+ run_lengths = change_indices[beg:end]
70
+
71
+ uncompressed_rle = {"counts": run_lengths, "size": list(orig_mask.shape[1:])}
72
+ h, w = uncompressed_rle["size"]
73
+ rle = mask_util.frPyObjects(uncompressed_rle, h, w)
74
+ rle["counts"] = rle["counts"].decode("utf-8")
75
+ if return_areas:
76
+ rle["area"] = mask_areas[i]
77
+ batch_rles.append(rle)
78
+
79
+ return batch_rles
80
+
81
+
82
+ def robust_rle_encode(masks):
83
+ """Encodes a collection of masks in RLE format. Uses the gpu version fist, falls back to the cpu version if it fails"""
84
+
85
+ assert masks.ndim == 3, "Mask must be of shape (N, H, W)"
86
+ assert masks.dtype == torch.bool, "Mask must have dtype=torch.bool"
87
+
88
+ try:
89
+ return rle_encode(masks)
90
+ except RuntimeError as _:
91
+ masks = masks.cpu().numpy()
92
+ rles = [
93
+ mask_util.encode(
94
+ np.array(mask[:, :, np.newaxis], dtype=np.uint8, order="F")
95
+ )[0]
96
+ for mask in masks
97
+ ]
98
+ for rle in rles:
99
+ rle["counts"] = rle["counts"].decode("utf-8")
100
+ return rles
101
+
102
+
103
+ def ann_to_rle(segm, im_info):
104
+ """Convert annotation which can be polygons, uncompressed RLE to RLE.
105
+ Args:
106
+ ann (dict) : annotation object
107
+ Returns:
108
+ ann (rle)
109
+ """
110
+ h, w = im_info["height"], im_info["width"]
111
+ if isinstance(segm, list):
112
+ # polygon -- a single object might consist of multiple parts
113
+ # we merge all parts into one mask rle code
114
+ rles = mask_util.frPyObjects(segm, h, w)
115
+ rle = mask_util.merge(rles)
116
+ elif isinstance(segm["counts"], list):
117
+ # uncompressed RLE
118
+ rle = mask_util.frPyObjects(segm, h, w)
119
+ else:
120
+ # rle
121
+ rle = segm
122
+ return rle
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/roi_align.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from torch import nn
4
+ from torchvision.ops import roi_align
5
+
6
+
7
+ # NOTE: torchvision's RoIAlign has a different default aligned=False
8
+ class ROIAlign(nn.Module):
9
+ def __init__(self, output_size, spatial_scale, sampling_ratio, aligned=True):
10
+ """
11
+ Args:
12
+ output_size (tuple): h, w
13
+ spatial_scale (float): scale the input boxes by this number
14
+ sampling_ratio (int): number of inputs samples to take for each output
15
+ sample. 0 to take samples densely.
16
+ aligned (bool): if False, use the legacy implementation in
17
+ Detectron. If True, align the results more perfectly.
18
+
19
+ Note:
20
+ The meaning of aligned=True:
21
+
22
+ Given a continuous coordinate c, its two neighboring pixel indices (in our
23
+ pixel model) are computed by floor(c - 0.5) and ceil(c - 0.5). For example,
24
+ c=1.3 has pixel neighbors with discrete indices [0] and [1] (which are sampled
25
+ from the underlying signal at continuous coordinates 0.5 and 1.5). But the original
26
+ roi_align (aligned=False) does not subtract the 0.5 when computing neighboring
27
+ pixel indices and therefore it uses pixels with a slightly incorrect alignment
28
+ (relative to our pixel model) when performing bilinear interpolation.
29
+
30
+ With `aligned=True`,
31
+ we first appropriately scale the ROI and then shift it by -0.5
32
+ prior to calling roi_align. This produces the correct neighbors; see
33
+ detectron2/tests/test_roi_align.py for verification.
34
+
35
+ The difference does not make a difference to the model's performance if
36
+ ROIAlign is used together with conv layers.
37
+ """
38
+ super().__init__()
39
+ self.output_size = output_size
40
+ self.spatial_scale = spatial_scale
41
+ self.sampling_ratio = sampling_ratio
42
+ self.aligned = aligned
43
+
44
+ from torchvision import __version__
45
+
46
+ version = tuple(int(x) for x in __version__.split(".")[:2])
47
+ # https://github.com/pytorch/vision/pull/2438
48
+ assert version >= (0, 7), "Require torchvision >= 0.7"
49
+
50
+ def forward(self, input, rois):
51
+ """
52
+ Args:
53
+ input: NCHW images
54
+ rois: Bx5 boxes. First column is the index into N. The other 4 columns are xyxy.
55
+ """
56
+ assert rois.dim() == 2 and rois.size(1) == 5
57
+ if input.is_quantized:
58
+ input = input.dequantize()
59
+ return roi_align(
60
+ input,
61
+ rois.to(dtype=input.dtype),
62
+ self.output_size,
63
+ self.spatial_scale,
64
+ self.sampling_ratio,
65
+ self.aligned,
66
+ )
67
+
68
+ def __repr__(self):
69
+ tmpstr = self.__class__.__name__ + "("
70
+ tmpstr += "output_size=" + str(self.output_size)
71
+ tmpstr += ", spatial_scale=" + str(self.spatial_scale)
72
+ tmpstr += ", sampling_ratio=" + str(self.sampling_ratio)
73
+ tmpstr += ", aligned=" + str(self.aligned)
74
+ tmpstr += ")"
75
+ return tmpstr
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/rotated_boxes.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from __future__ import absolute_import, division, print_function, unicode_literals
4
+
5
+ import math
6
+ from typing import List, Tuple
7
+
8
+ import torch
9
+
10
+ # from detectron2.layers.rotated_boxes import pairwise_iou_rotated
11
+
12
+ from .boxes import Boxes
13
+
14
+
15
+ def pairwise_iou_rotated(boxes1, boxes2):
16
+ """
17
+ Return intersection-over-union (Jaccard index) of boxes.
18
+
19
+ Both sets of boxes are expected to be in
20
+ (x_center, y_center, width, height, angle) format.
21
+
22
+ Arguments:
23
+ boxes1 (Tensor[N, 5])
24
+ boxes2 (Tensor[M, 5])
25
+
26
+ Returns:
27
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
28
+ IoU values for every element in boxes1 and boxes2
29
+ """
30
+ return torch.ops.detectron2.box_iou_rotated(boxes1, boxes2)
31
+
32
+
33
+ class RotatedBoxes(Boxes):
34
+ """
35
+ This structure stores a list of rotated boxes as a Nx5 torch.Tensor.
36
+ It supports some common methods about boxes
37
+ (`area`, `clip`, `nonempty`, etc),
38
+ and also behaves like a Tensor
39
+ (support indexing, `to(device)`, `.device`, and iteration over all boxes)
40
+ """
41
+
42
+ def __init__(self, tensor: torch.Tensor):
43
+ """
44
+ Args:
45
+ tensor (Tensor[float]): a Nx5 matrix. Each row is
46
+ (x_center, y_center, width, height, angle),
47
+ in which angle is represented in degrees.
48
+ While there's no strict range restriction for it,
49
+ the recommended principal range is between [-180, 180) degrees.
50
+
51
+ Assume we have a horizontal box B = (x_center, y_center, width, height),
52
+ where width is along the x-axis and height is along the y-axis.
53
+ The rotated box B_rot (x_center, y_center, width, height, angle)
54
+ can be seen as:
55
+
56
+ 1. When angle == 0:
57
+ B_rot == B
58
+ 2. When angle > 0:
59
+ B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CCW;
60
+ 3. When angle < 0:
61
+ B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CW.
62
+
63
+ Mathematically, since the right-handed coordinate system for image space
64
+ is (y, x), where y is top->down and x is left->right, the 4 vertices of the
65
+ rotated rectangle :math:`(yr_i, xr_i)` (i = 1, 2, 3, 4) can be obtained from
66
+ the vertices of the horizontal rectangle :math:`(y_i, x_i)` (i = 1, 2, 3, 4)
67
+ in the following way (:math:`\\theta = angle*\\pi/180` is the angle in radians,
68
+ :math:`(y_c, x_c)` is the center of the rectangle):
69
+
70
+ .. math::
71
+
72
+ yr_i = \\cos(\\theta) (y_i - y_c) - \\sin(\\theta) (x_i - x_c) + y_c,
73
+
74
+ xr_i = \\sin(\\theta) (y_i - y_c) + \\cos(\\theta) (x_i - x_c) + x_c,
75
+
76
+ which is the standard rigid-body rotation transformation.
77
+
78
+ Intuitively, the angle is
79
+ (1) the rotation angle from y-axis in image space
80
+ to the height vector (top->down in the box's local coordinate system)
81
+ of the box in CCW, and
82
+ (2) the rotation angle from x-axis in image space
83
+ to the width vector (left->right in the box's local coordinate system)
84
+ of the box in CCW.
85
+
86
+ More intuitively, consider the following horizontal box ABCD represented
87
+ in (x1, y1, x2, y2): (3, 2, 7, 4),
88
+ covering the [3, 7] x [2, 4] region of the continuous coordinate system
89
+ which looks like this:
90
+
91
+ .. code:: none
92
+
93
+ O--------> x
94
+ |
95
+ | A---B
96
+ | | |
97
+ | D---C
98
+ |
99
+ v y
100
+
101
+ Note that each capital letter represents one 0-dimensional geometric point
102
+ instead of a 'square pixel' here.
103
+
104
+ In the example above, using (x, y) to represent a point we have:
105
+
106
+ .. math::
107
+
108
+ O = (0, 0), A = (3, 2), B = (7, 2), C = (7, 4), D = (3, 4)
109
+
110
+ We name vector AB = vector DC as the width vector in box's local coordinate system, and
111
+ vector AD = vector BC as the height vector in box's local coordinate system. Initially,
112
+ when angle = 0 degree, they're aligned with the positive directions of x-axis and y-axis
113
+ in the image space, respectively.
114
+
115
+ For better illustration, we denote the center of the box as E,
116
+
117
+ .. code:: none
118
+
119
+ O--------> x
120
+ |
121
+ | A---B
122
+ | | E |
123
+ | D---C
124
+ |
125
+ v y
126
+
127
+ where the center E = ((3+7)/2, (2+4)/2) = (5, 3).
128
+
129
+ Also,
130
+
131
+ .. math::
132
+
133
+ width = |AB| = |CD| = 7 - 3 = 4,
134
+ height = |AD| = |BC| = 4 - 2 = 2.
135
+
136
+ Therefore, the corresponding representation for the same shape in rotated box in
137
+ (x_center, y_center, width, height, angle) format is:
138
+
139
+ (5, 3, 4, 2, 0),
140
+
141
+ Now, let's consider (5, 3, 4, 2, 90), which is rotated by 90 degrees
142
+ CCW (counter-clockwise) by definition. It looks like this:
143
+
144
+ .. code:: none
145
+
146
+ O--------> x
147
+ | B-C
148
+ | | |
149
+ | |E|
150
+ | | |
151
+ | A-D
152
+ v y
153
+
154
+ The center E is still located at the same point (5, 3), while the vertices
155
+ ABCD are rotated by 90 degrees CCW with regard to E:
156
+ A = (4, 5), B = (4, 1), C = (6, 1), D = (6, 5)
157
+
158
+ Here, 90 degrees can be seen as the CCW angle to rotate from y-axis to
159
+ vector AD or vector BC (the top->down height vector in box's local coordinate system),
160
+ or the CCW angle to rotate from x-axis to vector AB or vector DC (the left->right
161
+ width vector in box's local coordinate system).
162
+
163
+ .. math::
164
+
165
+ width = |AB| = |CD| = 5 - 1 = 4,
166
+ height = |AD| = |BC| = 6 - 4 = 2.
167
+
168
+ Next, how about (5, 3, 4, 2, -90), which is rotated by 90 degrees CW (clockwise)
169
+ by definition? It looks like this:
170
+
171
+ .. code:: none
172
+
173
+ O--------> x
174
+ | D-A
175
+ | | |
176
+ | |E|
177
+ | | |
178
+ | C-B
179
+ v y
180
+
181
+ The center E is still located at the same point (5, 3), while the vertices
182
+ ABCD are rotated by 90 degrees CW with regard to E:
183
+ A = (6, 1), B = (6, 5), C = (4, 5), D = (4, 1)
184
+
185
+ .. math::
186
+
187
+ width = |AB| = |CD| = 5 - 1 = 4,
188
+ height = |AD| = |BC| = 6 - 4 = 2.
189
+
190
+ This covers exactly the same region as (5, 3, 4, 2, 90) does, and their IoU
191
+ will be 1. However, these two will generate different RoI Pooling results and
192
+ should not be treated as an identical box.
193
+
194
+ On the other hand, it's easy to see that (X, Y, W, H, A) is identical to
195
+ (X, Y, W, H, A+360N), for any integer N. For example (5, 3, 4, 2, 270) would be
196
+ identical to (5, 3, 4, 2, -90), because rotating the shape 270 degrees CCW is
197
+ equivalent to rotating the same shape 90 degrees CW.
198
+
199
+ We could rotate further to get (5, 3, 4, 2, 180), or (5, 3, 4, 2, -180):
200
+
201
+ .. code:: none
202
+
203
+ O--------> x
204
+ |
205
+ | C---D
206
+ | | E |
207
+ | B---A
208
+ |
209
+ v y
210
+
211
+ .. math::
212
+
213
+ A = (7, 4), B = (3, 4), C = (3, 2), D = (7, 2),
214
+
215
+ width = |AB| = |CD| = 7 - 3 = 4,
216
+ height = |AD| = |BC| = 4 - 2 = 2.
217
+
218
+ Finally, this is a very inaccurate (heavily quantized) illustration of
219
+ how (5, 3, 4, 2, 60) looks like in case anyone wonders:
220
+
221
+ .. code:: none
222
+
223
+ O--------> x
224
+ | B\
225
+ | / C
226
+ | /E /
227
+ | A /
228
+ | `D
229
+ v y
230
+
231
+ It's still a rectangle with center of (5, 3), width of 4 and height of 2,
232
+ but its angle (and thus orientation) is somewhere between
233
+ (5, 3, 4, 2, 0) and (5, 3, 4, 2, 90).
234
+ """
235
+ device = (
236
+ tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu")
237
+ )
238
+ tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)
239
+ if tensor.numel() == 0:
240
+ # Use reshape, so we don't end up creating a new tensor that does not depend on
241
+ # the inputs (and consequently confuses jit)
242
+ tensor = tensor.reshape((0, 5)).to(dtype=torch.float32, device=device)
243
+ assert tensor.dim() == 2 and tensor.size(-1) == 5, tensor.size()
244
+
245
+ self.tensor = tensor
246
+
247
+ def clone(self) -> "RotatedBoxes":
248
+ """
249
+ Clone the RotatedBoxes.
250
+
251
+ Returns:
252
+ RotatedBoxes
253
+ """
254
+ return RotatedBoxes(self.tensor.clone())
255
+
256
+ def to(self, device: torch.device, non_blocking: bool = False):
257
+ # Boxes are assumed float32 and does not support to(dtype)
258
+ return RotatedBoxes(self.tensor.to(device=device, non_blocking=non_blocking))
259
+
260
+ def area(self) -> torch.Tensor:
261
+ """
262
+ Computes the area of all the boxes.
263
+
264
+ Returns:
265
+ torch.Tensor: a vector with areas of each box.
266
+ """
267
+ box = self.tensor
268
+ area = box[:, 2] * box[:, 3]
269
+ return area
270
+
271
+ # Avoid in-place operations so that we can torchscript; NOTE: this creates a new tensor
272
+ def normalize_angles(self) -> None:
273
+ """
274
+ Restrict angles to the range of [-180, 180) degrees
275
+ """
276
+ angle_tensor = (self.tensor[:, 4] + 180.0) % 360.0 - 180.0
277
+ self.tensor = torch.cat((self.tensor[:, :4], angle_tensor[:, None]), dim=1)
278
+
279
+ def clip(
280
+ self, box_size: Tuple[int, int], clip_angle_threshold: float = 1.0
281
+ ) -> None:
282
+ """
283
+ Clip (in place) the boxes by limiting x coordinates to the range [0, width]
284
+ and y coordinates to the range [0, height].
285
+
286
+ For RRPN:
287
+ Only clip boxes that are almost horizontal with a tolerance of
288
+ clip_angle_threshold to maintain backward compatibility.
289
+
290
+ Rotated boxes beyond this threshold are not clipped for two reasons:
291
+
292
+ 1. There are potentially multiple ways to clip a rotated box to make it
293
+ fit within the image.
294
+ 2. It's tricky to make the entire rectangular box fit within the image
295
+ and still be able to not leave out pixels of interest.
296
+
297
+ Therefore we rely on ops like RoIAlignRotated to safely handle this.
298
+
299
+ Args:
300
+ box_size (height, width): The clipping box's size.
301
+ clip_angle_threshold:
302
+ Iff. abs(normalized(angle)) <= clip_angle_threshold (in degrees),
303
+ we do the clipping as horizontal boxes.
304
+ """
305
+ h, w = box_size
306
+
307
+ # normalize angles to be within (-180, 180] degrees
308
+ self.normalize_angles()
309
+
310
+ idx = torch.where(torch.abs(self.tensor[:, 4]) <= clip_angle_threshold)[0]
311
+
312
+ # convert to (x1, y1, x2, y2)
313
+ x1 = self.tensor[idx, 0] - self.tensor[idx, 2] / 2.0
314
+ y1 = self.tensor[idx, 1] - self.tensor[idx, 3] / 2.0
315
+ x2 = self.tensor[idx, 0] + self.tensor[idx, 2] / 2.0
316
+ y2 = self.tensor[idx, 1] + self.tensor[idx, 3] / 2.0
317
+
318
+ # clip
319
+ x1.clamp_(min=0, max=w)
320
+ y1.clamp_(min=0, max=h)
321
+ x2.clamp_(min=0, max=w)
322
+ y2.clamp_(min=0, max=h)
323
+
324
+ # convert back to (xc, yc, w, h)
325
+ self.tensor[idx, 0] = (x1 + x2) / 2.0
326
+ self.tensor[idx, 1] = (y1 + y2) / 2.0
327
+ # make sure widths and heights do not increase due to numerical errors
328
+ self.tensor[idx, 2] = torch.min(self.tensor[idx, 2], x2 - x1)
329
+ self.tensor[idx, 3] = torch.min(self.tensor[idx, 3], y2 - y1)
330
+
331
+ def nonempty(self, threshold: float = 0.0) -> torch.Tensor:
332
+ """
333
+ Find boxes that are non-empty.
334
+ A box is considered empty, if either of its side is no larger than threshold.
335
+
336
+ Returns:
337
+ Tensor: a binary vector which represents
338
+ whether each box is empty (False) or non-empty (True).
339
+ """
340
+ box = self.tensor
341
+ widths = box[:, 2]
342
+ heights = box[:, 3]
343
+ keep = (widths > threshold) & (heights > threshold)
344
+ return keep
345
+
346
+ def __getitem__(self, item) -> "RotatedBoxes":
347
+ """
348
+ Returns:
349
+ RotatedBoxes: Create a new :class:`RotatedBoxes` by indexing.
350
+
351
+ The following usage are allowed:
352
+
353
+ 1. `new_boxes = boxes[3]`: return a `RotatedBoxes` which contains only one box.
354
+ 2. `new_boxes = boxes[2:10]`: return a slice of boxes.
355
+ 3. `new_boxes = boxes[vector]`, where vector is a torch.ByteTensor
356
+ with `length = len(boxes)`. Nonzero elements in the vector will be selected.
357
+
358
+ Note that the returned RotatedBoxes might share storage with this RotatedBoxes,
359
+ subject to Pytorch's indexing semantics.
360
+ """
361
+ if isinstance(item, int):
362
+ return RotatedBoxes(self.tensor[item].view(1, -1))
363
+ b = self.tensor[item]
364
+ assert (
365
+ b.dim() == 2
366
+ ), "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
367
+ return RotatedBoxes(b)
368
+
369
+ def __len__(self) -> int:
370
+ return self.tensor.shape[0]
371
+
372
+ def __repr__(self) -> str:
373
+ return "RotatedBoxes(" + str(self.tensor) + ")"
374
+
375
+ def inside_box(
376
+ self, box_size: Tuple[int, int], boundary_threshold: int = 0
377
+ ) -> torch.Tensor:
378
+ """
379
+ Args:
380
+ box_size (height, width): Size of the reference box covering
381
+ [0, width] x [0, height]
382
+ boundary_threshold (int): Boxes that extend beyond the reference box
383
+ boundary by more than boundary_threshold are considered "outside".
384
+
385
+ For RRPN, it might not be necessary to call this function since it's common
386
+ for rotated box to extend to outside of the image boundaries
387
+ (the clip function only clips the near-horizontal boxes)
388
+
389
+ Returns:
390
+ a binary vector, indicating whether each box is inside the reference box.
391
+ """
392
+ height, width = box_size
393
+
394
+ cnt_x = self.tensor[..., 0]
395
+ cnt_y = self.tensor[..., 1]
396
+ half_w = self.tensor[..., 2] / 2.0
397
+ half_h = self.tensor[..., 3] / 2.0
398
+ a = self.tensor[..., 4]
399
+ c = torch.abs(torch.cos(a * math.pi / 180.0))
400
+ s = torch.abs(torch.sin(a * math.pi / 180.0))
401
+ # This basically computes the horizontal bounding rectangle of the rotated box
402
+ max_rect_dx = c * half_w + s * half_h
403
+ max_rect_dy = c * half_h + s * half_w
404
+
405
+ inds_inside = (
406
+ (cnt_x - max_rect_dx >= -boundary_threshold)
407
+ & (cnt_y - max_rect_dy >= -boundary_threshold)
408
+ & (cnt_x + max_rect_dx < width + boundary_threshold)
409
+ & (cnt_y + max_rect_dy < height + boundary_threshold)
410
+ )
411
+
412
+ return inds_inside
413
+
414
+ def get_centers(self) -> torch.Tensor:
415
+ """
416
+ Returns:
417
+ The box centers in a Nx2 array of (x, y).
418
+ """
419
+ return self.tensor[:, :2]
420
+
421
+ def scale(self, scale_x: float, scale_y: float) -> None:
422
+ """
423
+ Scale the rotated box with horizontal and vertical scaling factors
424
+ Note: when scale_factor_x != scale_factor_y,
425
+ the rotated box does not preserve the rectangular shape when the angle
426
+ is not a multiple of 90 degrees under resize transformation.
427
+ Instead, the shape is a parallelogram (that has skew)
428
+ Here we make an approximation by fitting a rotated rectangle to the parallelogram.
429
+ """
430
+ self.tensor[:, 0] *= scale_x
431
+ self.tensor[:, 1] *= scale_y
432
+ theta = self.tensor[:, 4] * math.pi / 180.0
433
+ c = torch.cos(theta)
434
+ s = torch.sin(theta)
435
+
436
+ # In image space, y is top->down and x is left->right
437
+ # Consider the local coordintate system for the rotated box,
438
+ # where the box center is located at (0, 0), and the four vertices ABCD are
439
+ # A(-w / 2, -h / 2), B(w / 2, -h / 2), C(w / 2, h / 2), D(-w / 2, h / 2)
440
+ # the midpoint of the left edge AD of the rotated box E is:
441
+ # E = (A+D)/2 = (-w / 2, 0)
442
+ # the midpoint of the top edge AB of the rotated box F is:
443
+ # F(0, -h / 2)
444
+ # To get the old coordinates in the global system, apply the rotation transformation
445
+ # (Note: the right-handed coordinate system for image space is yOx):
446
+ # (old_x, old_y) = (s * y + c * x, c * y - s * x)
447
+ # E(old) = (s * 0 + c * (-w/2), c * 0 - s * (-w/2)) = (-c * w / 2, s * w / 2)
448
+ # F(old) = (s * (-h / 2) + c * 0, c * (-h / 2) - s * 0) = (-s * h / 2, -c * h / 2)
449
+ # After applying the scaling factor (sfx, sfy):
450
+ # E(new) = (-sfx * c * w / 2, sfy * s * w / 2)
451
+ # F(new) = (-sfx * s * h / 2, -sfy * c * h / 2)
452
+ # The new width after scaling tranformation becomes:
453
+
454
+ # w(new) = |E(new) - O| * 2
455
+ # = sqrt[(sfx * c * w / 2)^2 + (sfy * s * w / 2)^2] * 2
456
+ # = sqrt[(sfx * c)^2 + (sfy * s)^2] * w
457
+ # i.e., scale_factor_w = sqrt[(sfx * c)^2 + (sfy * s)^2]
458
+ #
459
+ # For example,
460
+ # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_w == scale_factor_x;
461
+ # when |angle| = 90, c = 0, |s| = 1, scale_factor_w == scale_factor_y
462
+ self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2)
463
+
464
+ # h(new) = |F(new) - O| * 2
465
+ # = sqrt[(sfx * s * h / 2)^2 + (sfy * c * h / 2)^2] * 2
466
+ # = sqrt[(sfx * s)^2 + (sfy * c)^2] * h
467
+ # i.e., scale_factor_h = sqrt[(sfx * s)^2 + (sfy * c)^2]
468
+ #
469
+ # For example,
470
+ # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_h == scale_factor_y;
471
+ # when |angle| = 90, c = 0, |s| = 1, scale_factor_h == scale_factor_x
472
+ self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2)
473
+
474
+ # The angle is the rotation angle from y-axis in image space to the height
475
+ # vector (top->down in the box's local coordinate system) of the box in CCW.
476
+ #
477
+ # angle(new) = angle_yOx(O - F(new))
478
+ # = angle_yOx( (sfx * s * h / 2, sfy * c * h / 2) )
479
+ # = atan2(sfx * s * h / 2, sfy * c * h / 2)
480
+ # = atan2(sfx * s, sfy * c)
481
+ #
482
+ # For example,
483
+ # when sfx == sfy, angle(new) == atan2(s, c) == angle(old)
484
+ self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi
485
+
486
+ @classmethod
487
+ def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes":
488
+ """
489
+ Concatenates a list of RotatedBoxes into a single RotatedBoxes
490
+
491
+ Arguments:
492
+ boxes_list (list[RotatedBoxes])
493
+
494
+ Returns:
495
+ RotatedBoxes: the concatenated RotatedBoxes
496
+ """
497
+ assert isinstance(boxes_list, (list, tuple))
498
+ if len(boxes_list) == 0:
499
+ return cls(torch.empty(0))
500
+ assert all([isinstance(box, RotatedBoxes) for box in boxes_list])
501
+
502
+ # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input
503
+ cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))
504
+ return cat_boxes
505
+
506
+ @property
507
+ def device(self) -> torch.device:
508
+ return self.tensor.device
509
+
510
+ @torch.jit.unused
511
+ def __iter__(self):
512
+ """
513
+ Yield a box as a Tensor of shape (5,) at a time.
514
+ """
515
+ yield from self.tensor
516
+
517
+
518
+ def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None:
519
+ """
520
+ Given two lists of rotated boxes of size N and M,
521
+ compute the IoU (intersection over union)
522
+ between **all** N x M pairs of boxes.
523
+ The box order must be (x_center, y_center, width, height, angle).
524
+
525
+ Args:
526
+ boxes1, boxes2 (RotatedBoxes):
527
+ two `RotatedBoxes`. Contains N & M rotated boxes, respectively.
528
+
529
+ Returns:
530
+ Tensor: IoU, sized [N,M].
531
+ """
532
+
533
+ return pairwise_iou_rotated(boxes1.tensor, boxes2.tensor)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/som_utils.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import colorsys
4
+ from dataclasses import dataclass
5
+ from typing import List, Tuple
6
+
7
+ import cv2
8
+ import matplotlib as mpl
9
+ import matplotlib.colors as mplc
10
+ import numpy as np
11
+ import pycocotools.mask as mask_utils
12
+
13
+
14
+ def rgb_to_hex(rgb_color):
15
+ """
16
+ Convert a rgb color to hex color.
17
+
18
+ Args:
19
+ rgb_color (tuple/list of ints): RGB color in tuple or list format.
20
+
21
+ Returns:
22
+ str: Hex color.
23
+
24
+ Example:
25
+ ```
26
+ >>> rgb_to_hex((255, 0, 244))
27
+ '#ff00ff'
28
+ ```
29
+ """
30
+ return "#" + "".join([hex(c)[2:].zfill(2) for c in rgb_color])
31
+
32
+
33
+ # DEFAULT_COLOR_HEX_TO_NAME = {
34
+ # rgb_to_hex((255, 0, 0)): "red",
35
+ # rgb_to_hex((0, 255, 0)): "lime",
36
+ # rgb_to_hex((0, 0, 255)): "blue",
37
+ # rgb_to_hex((255, 255, 0)): "yellow",
38
+ # rgb_to_hex((255, 0, 255)): "fuchsia",
39
+ # rgb_to_hex((0, 255, 255)): "aqua",
40
+ # rgb_to_hex((255, 165, 0)): "orange",
41
+ # rgb_to_hex((128, 0, 128)): "purple",
42
+ # rgb_to_hex((255, 215, 0)): "gold",
43
+ # }
44
+
45
+ # Assuming rgb_to_hex is a function that converts an (R, G, B) tuple to a hex string.
46
+ # For example: def rgb_to_hex(rgb): return '#%02x%02x%02x' % rgb
47
+
48
+ DEFAULT_COLOR_HEX_TO_NAME = {
49
+ # The top 20 approved colors
50
+ rgb_to_hex((255, 255, 0)): "yellow",
51
+ rgb_to_hex((0, 255, 0)): "lime",
52
+ rgb_to_hex((0, 255, 255)): "cyan",
53
+ rgb_to_hex((255, 0, 255)): "magenta",
54
+ rgb_to_hex((255, 0, 0)): "red",
55
+ rgb_to_hex((255, 127, 0)): "orange",
56
+ rgb_to_hex((127, 255, 0)): "chartreuse",
57
+ rgb_to_hex((0, 255, 127)): "spring green",
58
+ rgb_to_hex((255, 0, 127)): "rose",
59
+ rgb_to_hex((127, 0, 255)): "violet",
60
+ rgb_to_hex((192, 255, 0)): "electric lime",
61
+ rgb_to_hex((255, 192, 0)): "vivid orange",
62
+ rgb_to_hex((0, 255, 192)): "turquoise",
63
+ rgb_to_hex((192, 0, 255)): "bright violet",
64
+ rgb_to_hex((255, 0, 192)): "bright pink",
65
+ rgb_to_hex((255, 64, 0)): "fiery orange",
66
+ rgb_to_hex((64, 255, 0)): "bright chartreuse",
67
+ rgb_to_hex((0, 255, 64)): "malachite",
68
+ rgb_to_hex((64, 0, 255)): "deep violet",
69
+ rgb_to_hex((255, 0, 64)): "hot pink",
70
+ }
71
+
72
+
73
+ DEFAULT_COLOR_PALETTE = list(DEFAULT_COLOR_HEX_TO_NAME.keys())
74
+
75
+
76
+ def _validate_color_hex(color_hex: str):
77
+ color_hex = color_hex.lstrip("#")
78
+ if not all(c in "0123456789abcdefABCDEF" for c in color_hex):
79
+ raise ValueError("Invalid characters in color hash")
80
+ if len(color_hex) not in (3, 6):
81
+ raise ValueError("Invalid length of color hash")
82
+
83
+
84
+ # copied from https://github.com/roboflow/supervision/blob/c8f557af0c61b5c03392bad2cc36c8835598b1e1/supervision/draw/color.py
85
+ @dataclass
86
+ class Color:
87
+ """
88
+ Represents a color in RGB format.
89
+
90
+ Attributes:
91
+ r (int): Red channel.
92
+ g (int): Green channel.
93
+ b (int): Blue channel.
94
+ """
95
+
96
+ r: int
97
+ g: int
98
+ b: int
99
+
100
+ @classmethod
101
+ def from_hex(cls, color_hex: str):
102
+ """
103
+ Create a Color instance from a hex string.
104
+
105
+ Args:
106
+ color_hex (str): Hex string of the color.
107
+
108
+ Returns:
109
+ Color: Instance representing the color.
110
+
111
+ Example:
112
+ ```
113
+ >>> Color.from_hex('#ff00ff')
114
+ Color(r=255, g=0, b=255)
115
+ ```
116
+ """
117
+ _validate_color_hex(color_hex)
118
+ color_hex = color_hex.lstrip("#")
119
+ if len(color_hex) == 3:
120
+ color_hex = "".join(c * 2 for c in color_hex)
121
+ r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2))
122
+ return cls(r, g, b)
123
+
124
+ @classmethod
125
+ def to_hex(cls, color):
126
+ """
127
+ Convert a Color instance to a hex string.
128
+
129
+ Args:
130
+ color (Color): Color instance of color.
131
+
132
+ Returns:
133
+ Color: a hex string.
134
+ """
135
+ return rgb_to_hex((color.r, color.g, color.b))
136
+
137
+ def as_rgb(self) -> Tuple[int, int, int]:
138
+ """
139
+ Returns the color as an RGB tuple.
140
+
141
+ Returns:
142
+ Tuple[int, int, int]: RGB tuple.
143
+
144
+ Example:
145
+ ```
146
+ >>> color.as_rgb()
147
+ (255, 0, 255)
148
+ ```
149
+ """
150
+ return self.r, self.g, self.b
151
+
152
+ def as_bgr(self) -> Tuple[int, int, int]:
153
+ """
154
+ Returns the color as a BGR tuple.
155
+
156
+ Returns:
157
+ Tuple[int, int, int]: BGR tuple.
158
+
159
+ Example:
160
+ ```
161
+ >>> color.as_bgr()
162
+ (255, 0, 255)
163
+ ```
164
+ """
165
+ return self.b, self.g, self.r
166
+
167
+ @classmethod
168
+ def white(cls):
169
+ return Color.from_hex(color_hex="#ffffff")
170
+
171
+ @classmethod
172
+ def black(cls):
173
+ return Color.from_hex(color_hex="#000000")
174
+
175
+ @classmethod
176
+ def red(cls):
177
+ return Color.from_hex(color_hex="#ff0000")
178
+
179
+ @classmethod
180
+ def green(cls):
181
+ return Color.from_hex(color_hex="#00ff00")
182
+
183
+ @classmethod
184
+ def blue(cls):
185
+ return Color.from_hex(color_hex="#0000ff")
186
+
187
+
188
+ @dataclass
189
+ class ColorPalette:
190
+ colors: List[Color]
191
+
192
+ @classmethod
193
+ def default(cls):
194
+ """
195
+ Returns a default color palette.
196
+
197
+ Returns:
198
+ ColorPalette: A ColorPalette instance with default colors.
199
+
200
+ Example:
201
+ ```
202
+ >>> ColorPalette.default()
203
+ ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...])
204
+ ```
205
+ """
206
+ return ColorPalette.from_hex(color_hex_list=DEFAULT_COLOR_PALETTE)
207
+
208
+ @classmethod
209
+ def from_hex(cls, color_hex_list: List[str]):
210
+ """
211
+ Create a ColorPalette instance from a list of hex strings.
212
+
213
+ Args:
214
+ color_hex_list (List[str]): List of color hex strings.
215
+
216
+ Returns:
217
+ ColorPalette: A ColorPalette instance.
218
+
219
+ Example:
220
+ ```
221
+ >>> ColorPalette.from_hex(['#ff0000', '#00ff00', '#0000ff'])
222
+ ColorPalette(colors=[Color(r=255, g=0, b=0), Color(r=0, g=255, b=0), ...])
223
+ ```
224
+ """
225
+ colors = [Color.from_hex(color_hex) for color_hex in color_hex_list]
226
+ return cls(colors)
227
+
228
+ def by_idx(self, idx: int) -> Color:
229
+ """
230
+ Return the color at a given index in the palette.
231
+
232
+ Args:
233
+ idx (int): Index of the color in the palette.
234
+
235
+ Returns:
236
+ Color: Color at the given index.
237
+
238
+ Example:
239
+ ```
240
+ >>> color_palette.by_idx(1)
241
+ Color(r=0, g=255, b=0)
242
+ ```
243
+ """
244
+ if idx < 0:
245
+ raise ValueError("idx argument should not be negative")
246
+ idx = idx % len(self.colors)
247
+ return self.colors[idx]
248
+
249
+ def find_farthest_color(self, img_array):
250
+ """
251
+ Return the color that is the farthest from the given color.
252
+
253
+ Args:
254
+ img_array (np array): any *x3 np array, 3 is the RGB color channel.
255
+
256
+ Returns:
257
+ Color: Farthest color.
258
+
259
+ """
260
+ # Reshape the image array for broadcasting
261
+ img_array = img_array.reshape((-1, 3))
262
+
263
+ # Convert colors dictionary to a NumPy array
264
+ color_values = np.array([[c.r, c.g, c.b] for c in self.colors])
265
+
266
+ # Calculate the Euclidean distance between the colors and each pixel in the image
267
+ # Broadcasting happens here: img_array shape is (num_pixels, 3), color_values shape is (num_colors, 3)
268
+ distances = np.sqrt(
269
+ np.sum((img_array[:, np.newaxis, :] - color_values) ** 2, axis=2)
270
+ )
271
+
272
+ # Average the distances for each color
273
+ mean_distances = np.mean(distances, axis=0)
274
+
275
+ # return the farthest color
276
+ farthest_idx = np.argmax(mean_distances)
277
+ farthest_color = self.colors[farthest_idx]
278
+ farthest_color_hex = Color.to_hex(farthest_color)
279
+ if farthest_color_hex in DEFAULT_COLOR_HEX_TO_NAME:
280
+ farthest_color_name = DEFAULT_COLOR_HEX_TO_NAME[farthest_color_hex]
281
+ else:
282
+ farthest_color_name = "unknown"
283
+
284
+ return farthest_color, farthest_color_name
285
+
286
+
287
+ def draw_box(ax, box_coord, alpha=0.8, edge_color="g", line_style="-", linewidth=2.0):
288
+ x0, y0, width, height = box_coord
289
+ ax.add_patch(
290
+ mpl.patches.Rectangle(
291
+ (x0, y0),
292
+ width,
293
+ height,
294
+ fill=False,
295
+ edgecolor=edge_color,
296
+ linewidth=linewidth,
297
+ alpha=alpha,
298
+ linestyle=line_style,
299
+ )
300
+ )
301
+
302
+
303
+ def draw_text(
304
+ ax,
305
+ text,
306
+ position,
307
+ font_size=None,
308
+ color="g",
309
+ horizontal_alignment="left",
310
+ rotation=0,
311
+ ):
312
+ if not font_size:
313
+ font_size = mpl.rcParams["font.size"]
314
+
315
+ color = np.maximum(list(mplc.to_rgb(color)), 0.2)
316
+ color[np.argmax(color)] = max(0.8, np.max(color))
317
+
318
+ x, y = position
319
+ ax.text(
320
+ x,
321
+ y,
322
+ text,
323
+ size=font_size,
324
+ family="sans-serif",
325
+ bbox={"facecolor": "none", "alpha": 0.5, "pad": 0.7, "edgecolor": "none"},
326
+ verticalalignment="top",
327
+ horizontalalignment=horizontal_alignment,
328
+ color=color,
329
+ rotation=rotation,
330
+ )
331
+
332
+
333
+ def draw_mask(
334
+ ax, rle, color, show_holes=True, alpha=0.15, upsample_factor=1.0, rle_upsampled=None
335
+ ):
336
+ if isinstance(rle, dict):
337
+ mask = mask_utils.decode(rle)
338
+ elif isinstance(rle, np.ndarray):
339
+ mask = rle
340
+ else:
341
+ raise ValueError(f"Unsupported type for rle: {type(rle)}")
342
+
343
+ mask_upsampled = None
344
+ if upsample_factor > 1.0 and show_holes:
345
+ assert rle_upsampled is not None
346
+ if isinstance(rle_upsampled, dict):
347
+ mask_upsampled = mask_utils.decode(rle_upsampled)
348
+ elif isinstance(rle_upsampled, np.ndarray):
349
+ mask_upsampled = rle_upsampled
350
+ else:
351
+ raise ValueError(f"Unsupported type for rle: {type(rle)}")
352
+
353
+ if show_holes:
354
+ if mask_upsampled is None:
355
+ mask_upsampled = mask
356
+ h, w = mask_upsampled.shape
357
+ mask_img = np.zeros((h, w, 4))
358
+ mask_img[:, :, :-1] = color[np.newaxis, np.newaxis, :]
359
+ mask_img[:, :, -1] = mask_upsampled * alpha
360
+ ax.imshow(mask_img)
361
+
362
+ *_, contours, _ = cv2.findContours(
363
+ mask.astype(np.uint8).copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
364
+ )
365
+ upsampled_contours = [(cont + 0.5) * upsample_factor - 0.5 for cont in contours]
366
+ facecolor = (0, 0, 0, 0) if show_holes else color
367
+ if alpha > 0.8:
368
+ edge_color = _change_color_brightness(color, brightness_factor=-0.7)
369
+ else:
370
+ edge_color = color
371
+ for cont in upsampled_contours:
372
+ polygon = mpl.patches.Polygon(
373
+ [el[0] for el in cont],
374
+ edgecolor=edge_color,
375
+ linewidth=2.0,
376
+ facecolor=facecolor,
377
+ )
378
+ ax.add_patch(polygon)
379
+
380
+
381
+ def _change_color_brightness(color, brightness_factor):
382
+ """
383
+ Depending on the brightness_factor, gives a lighter or darker color i.e. a color with
384
+ less or more saturation than the original color.
385
+
386
+ Args:
387
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
388
+ formats that are accepted.
389
+ brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of
390
+ 0 will correspond to no change, a factor in [-1.0, 0) range will result in
391
+ a darker color and a factor in (0, 1.0] range will result in a lighter color.
392
+
393
+ Returns:
394
+ modified_color (tuple[double]): a tuple containing the RGB values of the
395
+ modified color. Each value in the tuple is in the [0.0, 1.0] range.
396
+ """
397
+ assert brightness_factor >= -1.0 and brightness_factor <= 1.0
398
+ color = mplc.to_rgb(color)
399
+ polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
400
+ modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])
401
+ modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
402
+ modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
403
+ modified_color = colorsys.hls_to_rgb(
404
+ polygon_color[0], modified_lightness, polygon_color[2]
405
+ )
406
+ return modified_color
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/visualizer.py ADDED
@@ -0,0 +1,1662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import colorsys
4
+ import logging
5
+ import math
6
+ import random
7
+ from enum import Enum, unique
8
+
9
+ import cv2
10
+ import matplotlib as mpl
11
+ import matplotlib.colors as mplc
12
+ import matplotlib.figure as mplfigure
13
+ import numpy as np
14
+ import pycocotools.mask as mask_util
15
+ import torch
16
+ from iopath.common.file_io import PathManager
17
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
18
+ from PIL import Image
19
+
20
+ from .boxes import Boxes, BoxMode
21
+
22
+ from .color_map import random_color
23
+ from .keypoints import Keypoints
24
+ from .masks import BitMasks, PolygonMasks
25
+ from .rotated_boxes import RotatedBoxes
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ __all__ = ["ColorMode", "VisImage", "Visualizer"]
31
+
32
+
33
+ _SMALL_OBJECT_AREA_THRESH = 1000
34
+ _LARGE_MASK_AREA_THRESH = 120000
35
+ _OFF_WHITE = (1.0, 1.0, 240.0 / 255)
36
+ _BLACK = (0, 0, 0)
37
+ _RED = (1.0, 0, 0)
38
+
39
+ _KEYPOINT_THRESHOLD = 0.05
40
+
41
+
42
+ @unique
43
+ class ColorMode(Enum):
44
+ """
45
+ Enum of different color modes to use for instance visualizations.
46
+ """
47
+
48
+ IMAGE = 0
49
+ """
50
+ Picks a random color for every instance and overlay segmentations with low opacity.
51
+ """
52
+ SEGMENTATION = 1
53
+ """
54
+ Let instances of the same category have similar colors
55
+ (from metadata.thing_colors), and overlay them with
56
+ high opacity. This provides more attention on the quality of segmentation.
57
+ """
58
+ IMAGE_BW = 2
59
+ """
60
+ Same as IMAGE, but convert all areas without masks to gray-scale.
61
+ Only available for drawing per-instance mask predictions.
62
+ """
63
+
64
+
65
+ class GenericMask:
66
+ """
67
+ Attribute:
68
+ polygons (list[ndarray]): list[ndarray]: polygons for this mask.
69
+ Each ndarray has format [x, y, x, y, ...]
70
+ mask (ndarray): a binary mask
71
+ """
72
+
73
+ def __init__(self, mask_or_polygons, height, width):
74
+ self._mask = self._polygons = self._has_holes = None
75
+ self.height = height
76
+ self.width = width
77
+
78
+ m = mask_or_polygons
79
+ if isinstance(m, dict):
80
+ # RLEs
81
+ assert "counts" in m and "size" in m
82
+ if isinstance(m["counts"], list): # uncompressed RLEs
83
+ h, w = m["size"]
84
+ assert h == height and w == width
85
+ m = mask_util.frPyObjects(m, h, w)
86
+ self._mask = mask_util.decode(m)[:, :]
87
+ return
88
+
89
+ if isinstance(m, list): # list[ndarray]
90
+ self._polygons = [np.asarray(x).reshape(-1) for x in m]
91
+ return
92
+
93
+ if isinstance(m, np.ndarray): # assumed to be a binary mask
94
+ assert m.shape[1] != 2, m.shape
95
+ assert m.shape == (
96
+ height,
97
+ width,
98
+ ), f"mask shape: {m.shape}, target dims: {height}, {width}"
99
+ self._mask = m.astype("uint8")
100
+ return
101
+
102
+ raise ValueError(
103
+ "GenericMask cannot handle object {} of type '{}'".format(m, type(m))
104
+ )
105
+
106
+ @property
107
+ def mask(self):
108
+ if self._mask is None:
109
+ self._mask = self.polygons_to_mask(self._polygons)
110
+ return self._mask
111
+
112
+ @property
113
+ def polygons(self):
114
+ if self._polygons is None:
115
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
116
+ return self._polygons
117
+
118
+ @property
119
+ def has_holes(self):
120
+ if self._has_holes is None:
121
+ if self._mask is not None:
122
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
123
+ else:
124
+ self._has_holes = (
125
+ False # if original format is polygon, does not have holes
126
+ )
127
+ return self._has_holes
128
+
129
+ def mask_to_polygons(self, mask):
130
+ # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level
131
+ # hierarchy. External contours (boundary) of the object are placed in hierarchy-1.
132
+ # Internal contours (holes) are placed in hierarchy-2.
133
+ # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours.
134
+ mask = np.ascontiguousarray(
135
+ mask
136
+ ) # some versions of cv2 does not support incontiguous arr
137
+ res = cv2.findContours(
138
+ mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE
139
+ )
140
+ hierarchy = res[-1]
141
+ if hierarchy is None: # empty mask
142
+ return [], False
143
+ has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
144
+ res = res[-2]
145
+ res = [x.flatten() for x in res]
146
+ # These coordinates from OpenCV are integers in range [0, W-1 or H-1].
147
+ # We add 0.5 to turn them into real-value coordinate space. A better solution
148
+ # would be to first +0.5 and then dilate the returned polygon by 0.5.
149
+ res = [x + 0.5 for x in res if len(x) >= 6]
150
+ return res, has_holes
151
+
152
+ def polygons_to_mask(self, polygons):
153
+ rle = mask_util.frPyObjects(polygons, self.height, self.width)
154
+ rle = mask_util.merge(rle)
155
+ return mask_util.decode(rle)[:, :]
156
+
157
+ def area(self):
158
+ return self.mask.sum()
159
+
160
+ def bbox(self):
161
+ p = mask_util.frPyObjects(self.polygons, self.height, self.width)
162
+ p = mask_util.merge(p)
163
+ bbox = mask_util.toBbox(p)
164
+ bbox[2] += bbox[0]
165
+ bbox[3] += bbox[1]
166
+ return bbox
167
+
168
+
169
+ class _PanopticPrediction:
170
+ """
171
+ Unify different panoptic annotation/prediction formats
172
+ """
173
+
174
+ def __init__(self, panoptic_seg, segments_info, metadata=None):
175
+ if segments_info is None:
176
+ assert metadata is not None
177
+ # If "segments_info" is None, we assume "panoptic_img" is a
178
+ # H*W int32 image storing the panoptic_id in the format of
179
+ # category_id * label_divisor + instance_id. We reserve -1 for
180
+ # VOID label.
181
+ label_divisor = metadata.label_divisor
182
+ segments_info = []
183
+ for panoptic_label in np.unique(panoptic_seg.numpy()):
184
+ if panoptic_label == -1:
185
+ # VOID region.
186
+ continue
187
+ pred_class = panoptic_label // label_divisor
188
+ isthing = (
189
+ pred_class in metadata.thing_dataset_id_to_contiguous_id.values()
190
+ )
191
+ segments_info.append(
192
+ {
193
+ "id": int(panoptic_label),
194
+ "category_id": int(pred_class),
195
+ "isthing": bool(isthing),
196
+ }
197
+ )
198
+ del metadata
199
+
200
+ self._seg = panoptic_seg
201
+
202
+ self._sinfo = {s["id"]: s for s in segments_info} # seg id -> seg info
203
+ segment_ids, areas = torch.unique(panoptic_seg, sorted=True, return_counts=True)
204
+ areas = areas.numpy()
205
+ sorted_idxs = np.argsort(-areas)
206
+ self._seg_ids, self._seg_areas = segment_ids[sorted_idxs], areas[sorted_idxs]
207
+ self._seg_ids = self._seg_ids.tolist()
208
+ for sid, area in zip(self._seg_ids, self._seg_areas):
209
+ if sid in self._sinfo:
210
+ self._sinfo[sid]["area"] = float(area)
211
+
212
+ def non_empty_mask(self):
213
+ """
214
+ Returns:
215
+ (H, W) array, a mask for all pixels that have a prediction
216
+ """
217
+ empty_ids = []
218
+ for id in self._seg_ids:
219
+ if id not in self._sinfo:
220
+ empty_ids.append(id)
221
+ if len(empty_ids) == 0:
222
+ return np.zeros(self._seg.shape, dtype=np.uint8)
223
+ assert (
224
+ len(empty_ids) == 1
225
+ ), ">1 ids corresponds to no labels. This is currently not supported"
226
+ return (self._seg != empty_ids[0]).numpy().astype(np.bool)
227
+
228
+ def semantic_masks(self):
229
+ for sid in self._seg_ids:
230
+ sinfo = self._sinfo.get(sid)
231
+ if sinfo is None or sinfo["isthing"]:
232
+ # Some pixels (e.g. id 0 in PanopticFPN) have no instance or semantic predictions.
233
+ continue
234
+ yield (self._seg == sid).numpy().astype(np.bool), sinfo
235
+
236
+ def instance_masks(self):
237
+ for sid in self._seg_ids:
238
+ sinfo = self._sinfo.get(sid)
239
+ if sinfo is None or not sinfo["isthing"]:
240
+ continue
241
+ mask = (self._seg == sid).numpy().astype(np.bool)
242
+ if mask.sum() > 0:
243
+ yield mask, sinfo
244
+
245
+
246
+ def _create_text_labels(classes, scores, class_names, is_crowd=None):
247
+ """
248
+ Args:
249
+ classes (list[int] or None):
250
+ scores (list[float] or None):
251
+ class_names (list[str] or None):
252
+ is_crowd (list[bool] or None):
253
+
254
+ Returns:
255
+ list[str] or None
256
+ """
257
+ labels = None
258
+ if classes is not None:
259
+ if class_names is not None and len(class_names) > 0:
260
+ labels = [class_names[i] for i in classes]
261
+ else:
262
+ labels = [str(i) for i in classes]
263
+ if scores is not None:
264
+ if labels is None:
265
+ labels = ["{:.0f}%".format(s * 100) for s in scores]
266
+ else:
267
+ labels = ["{} {:.0f}%".format(l, s * 100) for l, s in zip(labels, scores)]
268
+ if labels is not None and is_crowd is not None:
269
+ labels = [l + ("|crowd" if crowd else "") for l, crowd in zip(labels, is_crowd)]
270
+ return labels
271
+
272
+
273
+ class VisImage:
274
+ def __init__(self, img, scale=1.0):
275
+ """
276
+ Args:
277
+ img (ndarray): an RGB image of shape (H, W, 3) in range [0, 255].
278
+ scale (float): scale the input image
279
+ """
280
+ self.img = img
281
+ self.scale = scale
282
+ self.width, self.height = img.shape[1], img.shape[0]
283
+ self._setup_figure(img)
284
+
285
+ def _setup_figure(self, img):
286
+ """
287
+ Args:
288
+ Same as in :meth:`__init__()`.
289
+
290
+ Returns:
291
+ fig (matplotlib.pyplot.figure): top level container for all the image plot elements.
292
+ ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system.
293
+ """
294
+ fig = mplfigure.Figure(frameon=False)
295
+ self.dpi = fig.get_dpi()
296
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
297
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
298
+ fig.set_size_inches(
299
+ (self.width * self.scale + 1e-2) / self.dpi,
300
+ (self.height * self.scale + 1e-2) / self.dpi,
301
+ )
302
+ self.canvas = FigureCanvasAgg(fig)
303
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
304
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
305
+ ax.axis("off")
306
+ self.fig = fig
307
+ self.ax = ax
308
+ self.reset_image(img)
309
+
310
+ def reset_image(self, img):
311
+ """
312
+ Args:
313
+ img: same as in __init__
314
+ """
315
+ img = img.astype("uint8")
316
+ self.ax.imshow(
317
+ img, extent=(0, self.width, self.height, 0), interpolation="nearest"
318
+ )
319
+
320
+ def save(self, filepath):
321
+ """
322
+ Args:
323
+ filepath (str): a string that contains the absolute path, including the file name, where
324
+ the visualized image will be saved.
325
+ """
326
+ self.fig.savefig(filepath)
327
+
328
+ def get_image(self):
329
+ """
330
+ Returns:
331
+ ndarray:
332
+ the visualized image of shape (H, W, 3) (RGB) in uint8 type.
333
+ The shape is scaled w.r.t the input image using the given `scale` argument.
334
+ """
335
+ canvas = self.canvas
336
+ s, (width, height) = canvas.print_to_buffer()
337
+ # buf = io.BytesIO() # works for cairo backend
338
+ # canvas.print_rgba(buf)
339
+ # width, height = self.width, self.height
340
+ # s = buf.getvalue()
341
+
342
+ buffer = np.frombuffer(s, dtype="uint8")
343
+
344
+ img_rgba = buffer.reshape(height, width, 4)
345
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
346
+ return rgb.astype("uint8")
347
+
348
+
349
+ class Visualizer:
350
+ """
351
+ Visualizer that draws data about detection/segmentation on images.
352
+
353
+ It contains methods like `draw_{text,box,circle,line,binary_mask,polygon}`
354
+ that draw primitive objects to images, as well as high-level wrappers like
355
+ `draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict}`
356
+ that draw composite data in some pre-defined style.
357
+
358
+ Note that the exact visualization style for the high-level wrappers are subject to change.
359
+ Style such as color, opacity, label contents, visibility of labels, or even the visibility
360
+ of objects themselves (e.g. when the object is too small) may change according
361
+ to different heuristics, as long as the results still look visually reasonable.
362
+
363
+ To obtain a consistent style, you can implement custom drawing functions with the
364
+ abovementioned primitive methods instead. If you need more customized visualization
365
+ styles, you can process the data yourself following their format documented in
366
+ tutorials (:doc:`/tutorials/models`, :doc:`/tutorials/datasets`). This class does not
367
+ intend to satisfy everyone's preference on drawing styles.
368
+
369
+ This visualizer focuses on high rendering quality rather than performance. It is not
370
+ designed to be used for real-time applications.
371
+ """
372
+
373
+ def __init__(
374
+ self,
375
+ img_rgb,
376
+ metadata=None,
377
+ scale=1.0,
378
+ instance_mode=ColorMode.IMAGE,
379
+ font_size_multiplier=1.3,
380
+ boarder_width_multiplier=1.5,
381
+ ):
382
+ """
383
+ Args:
384
+ img_rgb: a numpy array of shape (H, W, C), where H and W correspond to
385
+ the height and width of the image respectively. C is the number of
386
+ color channels. The image is required to be in RGB format since that
387
+ is a requirement of the Matplotlib library. The image is also expected
388
+ to be in the range [0, 255].
389
+ metadata (Metadata): dataset metadata (e.g. class names and colors)
390
+ instance_mode (ColorMode): defines one of the pre-defined style for drawing
391
+ instances on an image.
392
+ """
393
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
394
+ self.boarder_width_multiplier = boarder_width_multiplier
395
+ # if metadata is None:
396
+ # metadata = MetadataCatalog.get("__nonexist__")
397
+ # self.metadata = metadata
398
+ self.output = VisImage(self.img, scale=scale)
399
+ self.cpu_device = torch.device("cpu")
400
+
401
+ # too small texts are useless, therefore clamp to 9
402
+ self._default_font_size = (
403
+ max(np.sqrt(self.output.height * self.output.width) // 60, 15 // scale)
404
+ * font_size_multiplier
405
+ )
406
+ # self._default_font_size = 18
407
+ self._instance_mode = instance_mode
408
+ self.keypoint_threshold = _KEYPOINT_THRESHOLD
409
+
410
+ import matplotlib.colors as mcolors
411
+
412
+ css4_colors = mcolors.CSS4_COLORS
413
+ self.color_proposals = [
414
+ list(mcolors.hex2color(color)) for color in css4_colors.values()
415
+ ]
416
+
417
+ def draw_instance_predictions(self, predictions):
418
+ """
419
+ Draw instance-level prediction results on an image.
420
+
421
+ Args:
422
+ predictions (Instances): the output of an instance detection/segmentation
423
+ model. Following fields will be used to draw:
424
+ "pred_boxes", "pred_classes", "scores", "pred_masks" (or "pred_masks_rle").
425
+
426
+ Returns:
427
+ output (VisImage): image object with visualizations.
428
+ """
429
+ boxes = predictions.pred_boxes if predictions.has("pred_boxes") else None
430
+ scores = predictions.scores if predictions.has("scores") else None
431
+ classes = (
432
+ predictions.pred_classes.tolist()
433
+ if predictions.has("pred_classes")
434
+ else None
435
+ )
436
+ labels = _create_text_labels(
437
+ classes, scores, self.metadata.get("thing_classes", None)
438
+ )
439
+ keypoints = (
440
+ predictions.pred_keypoints if predictions.has("pred_keypoints") else None
441
+ )
442
+
443
+ keep = (scores > 0.5).cpu()
444
+ boxes = boxes[keep]
445
+ scores = scores[keep]
446
+ classes = np.array(classes)
447
+ classes = classes[np.array(keep)]
448
+ labels = np.array(labels)
449
+ labels = labels[np.array(keep)]
450
+
451
+ if predictions.has("pred_masks"):
452
+ masks = np.asarray(predictions.pred_masks)
453
+ masks = masks[np.array(keep)]
454
+ masks = [
455
+ GenericMask(x, self.output.height, self.output.width) for x in masks
456
+ ]
457
+ else:
458
+ masks = None
459
+
460
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get(
461
+ "thing_colors"
462
+ ):
463
+ # if self.metadata.get("thing_colors"):
464
+ colors = [
465
+ self._jitter([x / 255 for x in self.metadata.thing_colors[c]])
466
+ for c in classes
467
+ ]
468
+ alpha = 0.4
469
+ else:
470
+ colors = None
471
+ alpha = 0.4
472
+
473
+ if self._instance_mode == ColorMode.IMAGE_BW:
474
+ self.output.reset_image(
475
+ self._create_grayscale_image(
476
+ (predictions.pred_masks.any(dim=0) > 0).numpy()
477
+ if predictions.has("pred_masks")
478
+ else None
479
+ )
480
+ )
481
+ alpha = 0.3
482
+
483
+ self.overlay_instances(
484
+ masks=masks,
485
+ boxes=boxes,
486
+ labels=labels,
487
+ keypoints=keypoints,
488
+ assigned_colors=colors,
489
+ alpha=alpha,
490
+ )
491
+ return self.output
492
+
493
+ def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.7):
494
+ """
495
+ Draw semantic segmentation predictions/labels.
496
+
497
+ Args:
498
+ sem_seg (Tensor or ndarray): the segmentation of shape (H, W).
499
+ Each value is the integer label of the pixel.
500
+ area_threshold (int): segments with less than `area_threshold` are not drawn.
501
+ alpha (float): the larger it is, the more opaque the segmentations are.
502
+
503
+ Returns:
504
+ output (VisImage): image object with visualizations.
505
+ """
506
+ if isinstance(sem_seg, torch.Tensor):
507
+ sem_seg = sem_seg.numpy()
508
+ labels, areas = np.unique(sem_seg, return_counts=True)
509
+ sorted_idxs = np.argsort(-areas).tolist()
510
+ labels = labels[sorted_idxs]
511
+ for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels):
512
+ try:
513
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[label]]
514
+ except (AttributeError, IndexError):
515
+ mask_color = None
516
+
517
+ binary_mask = (sem_seg == label).astype(np.uint8)
518
+ text = self.metadata.stuff_classes[label]
519
+ self.draw_binary_mask(
520
+ binary_mask,
521
+ color=mask_color,
522
+ edge_color=_OFF_WHITE,
523
+ text=text,
524
+ alpha=alpha,
525
+ area_threshold=area_threshold,
526
+ )
527
+ return self.output
528
+
529
+ def draw_panoptic_seg(
530
+ self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7
531
+ ):
532
+ """
533
+ Draw panoptic prediction annotations or results.
534
+
535
+ Args:
536
+ panoptic_seg (Tensor): of shape (height, width) where the values are ids for each
537
+ segment.
538
+ segments_info (list[dict] or None): Describe each segment in `panoptic_seg`.
539
+ If it is a ``list[dict]``, each dict contains keys "id", "category_id".
540
+ If None, category id of each pixel is computed by
541
+ ``pixel // metadata.label_divisor``.
542
+ area_threshold (int): stuff segments with less than `area_threshold` are not drawn.
543
+
544
+ Returns:
545
+ output (VisImage): image object with visualizations.
546
+ """
547
+ pred = _PanopticPrediction(panoptic_seg, segments_info, self.metadata)
548
+
549
+ if self._instance_mode == ColorMode.IMAGE_BW:
550
+ self.output.reset_image(self._create_grayscale_image(pred.non_empty_mask()))
551
+
552
+ # draw mask for all semantic segments first i.e. "stuff"
553
+ for mask, sinfo in pred.semantic_masks():
554
+ category_idx = sinfo["category_id"]
555
+ try:
556
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]]
557
+ except AttributeError:
558
+ mask_color = None
559
+
560
+ text = (
561
+ self.metadata.stuff_classes[category_idx]
562
+ .replace("-other", "")
563
+ .replace("-merged", "")
564
+ )
565
+ self.draw_binary_mask(
566
+ mask,
567
+ color=mask_color,
568
+ edge_color=_OFF_WHITE,
569
+ text=text,
570
+ alpha=alpha,
571
+ area_threshold=area_threshold,
572
+ )
573
+
574
+ # draw mask for all instances second
575
+ all_instances = list(pred.instance_masks())
576
+ if len(all_instances) == 0:
577
+ return self.output
578
+ masks, sinfo = list(zip(*all_instances))
579
+ category_ids = [x["category_id"] for x in sinfo]
580
+
581
+ try:
582
+ scores = [x["score"] for x in sinfo]
583
+ except KeyError:
584
+ scores = None
585
+ class_names = [
586
+ name.replace("-other", "").replace("-merged", "")
587
+ for name in self.metadata.thing_classes
588
+ ]
589
+ labels = _create_text_labels(
590
+ category_ids, scores, class_names, [x.get("iscrowd", 0) for x in sinfo]
591
+ )
592
+
593
+ try:
594
+ colors = [
595
+ self._jitter([x / 255 for x in self.metadata.thing_colors[c]])
596
+ for c in category_ids
597
+ ]
598
+ except AttributeError:
599
+ colors = None
600
+ self.overlay_instances(
601
+ masks=masks, labels=labels, assigned_colors=colors, alpha=alpha
602
+ )
603
+
604
+ return self.output
605
+
606
+ draw_panoptic_seg_predictions = draw_panoptic_seg # backward compatibility
607
+
608
+ def draw_dataset_dict(self, dic):
609
+ """
610
+ Draw annotations/segmentaions in Detectron2 Dataset format.
611
+
612
+ Args:
613
+ dic (dict): annotation/segmentation data of one image, in Detectron2 Dataset format.
614
+
615
+ Returns:
616
+ output (VisImage): image object with visualizations.
617
+ """
618
+ annos = dic.get("annotations", None)
619
+ if annos:
620
+ if "segmentation" in annos[0]:
621
+ masks = [x["segmentation"] for x in annos]
622
+ else:
623
+ masks = None
624
+ if "keypoints" in annos[0]:
625
+ keypts = [x["keypoints"] for x in annos]
626
+ keypts = np.array(keypts).reshape(len(annos), -1, 3)
627
+ else:
628
+ keypts = None
629
+
630
+ boxes = [
631
+ (
632
+ BoxMode.convert(x["bbox"], x["bbox_mode"], BoxMode.XYXY_ABS)
633
+ if len(x["bbox"]) == 4
634
+ else x["bbox"]
635
+ )
636
+ for x in annos
637
+ ]
638
+
639
+ colors = None
640
+ category_ids = [x["category_id"] for x in annos]
641
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get(
642
+ "thing_colors"
643
+ ):
644
+ colors = [
645
+ self._jitter([x / 255 for x in self.metadata.thing_colors[c]])
646
+ for c in category_ids
647
+ ]
648
+ names = self.metadata.get("thing_classes", None)
649
+ labels = _create_text_labels(
650
+ category_ids,
651
+ scores=None,
652
+ class_names=names,
653
+ is_crowd=[x.get("iscrowd", 0) for x in annos],
654
+ )
655
+ self.overlay_instances(
656
+ labels=labels,
657
+ boxes=boxes,
658
+ masks=masks,
659
+ keypoints=keypts,
660
+ assigned_colors=colors,
661
+ )
662
+
663
+ sem_seg = dic.get("sem_seg", None)
664
+ if sem_seg is None and "sem_seg_file_name" in dic:
665
+ with PathManager.open(dic["sem_seg_file_name"], "rb") as f:
666
+ sem_seg = Image.open(f)
667
+ sem_seg = np.asarray(sem_seg, dtype="uint8")
668
+ if sem_seg is not None:
669
+ self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.4)
670
+
671
+ pan_seg = dic.get("pan_seg", None)
672
+ if pan_seg is None and "pan_seg_file_name" in dic:
673
+ with PathManager.open(dic["pan_seg_file_name"], "rb") as f:
674
+ pan_seg = Image.open(f)
675
+ pan_seg = np.asarray(pan_seg)
676
+ from panopticapi.utils import rgb2id
677
+
678
+ pan_seg = rgb2id(pan_seg)
679
+ if pan_seg is not None:
680
+ segments_info = dic["segments_info"]
681
+ pan_seg = torch.tensor(pan_seg)
682
+ self.draw_panoptic_seg(pan_seg, segments_info, area_threshold=0, alpha=0.7)
683
+ return self.output
684
+
685
+ def overlay_instances(
686
+ self,
687
+ *,
688
+ boxes=None,
689
+ labels=None,
690
+ masks=None,
691
+ keypoints=None,
692
+ assigned_colors=None,
693
+ binary_masks=None,
694
+ alpha=0.5,
695
+ label_mode="1",
696
+ ):
697
+ """
698
+ Args:
699
+ boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,
700
+ or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,
701
+ or a :class:`RotatedBoxes`,
702
+ or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format
703
+ for the N objects in a single image,
704
+ labels (list[str]): the text to be displayed for each instance.
705
+ masks (masks-like object): Supported types are:
706
+
707
+ * :class:`detectron2.structures.PolygonMasks`,
708
+ :class:`detectron2.structures.BitMasks`.
709
+ * list[list[ndarray]]: contains the segmentation masks for all objects in one image.
710
+ The first level of the list corresponds to individual instances. The second
711
+ level to all the polygon that compose the instance, and the third level
712
+ to the polygon coordinates. The third level should have the format of
713
+ [x0, y0, x1, y1, ..., xn, yn] (n >= 3).
714
+ * list[ndarray]: each ndarray is a binary mask of shape (H, W).
715
+ * list[dict]: each dict is a COCO-style RLE.
716
+ keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),
717
+ where the N is the number of instances and K is the number of keypoints.
718
+ The last dimension corresponds to (x, y, visibility or score).
719
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
720
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
721
+ for full list of formats that the colors are accepted in.
722
+ Returns:
723
+ output (VisImage): image object with visualizations.
724
+ """
725
+ num_instances = 0
726
+ if boxes is not None:
727
+ boxes = self._convert_boxes(boxes)
728
+ num_instances = len(boxes)
729
+ if masks is not None:
730
+ masks = self._convert_masks(masks)
731
+ if num_instances:
732
+ assert len(masks) == num_instances
733
+ else:
734
+ num_instances = len(masks)
735
+ if keypoints is not None:
736
+ if num_instances:
737
+ assert len(keypoints) == num_instances
738
+ else:
739
+ num_instances = len(keypoints)
740
+ keypoints = self._convert_keypoints(keypoints)
741
+ if labels is not None:
742
+ assert len(labels) == num_instances
743
+ if assigned_colors is None:
744
+ assigned_colors = [
745
+ random_color(rgb=True, maximum=1) for _ in range(num_instances)
746
+ ]
747
+ if num_instances == 0:
748
+ return labels, [], []
749
+ if boxes is not None and boxes.shape[1] == 5:
750
+ return self.overlay_rotated_instances(
751
+ boxes=boxes, labels=labels, assigned_colors=assigned_colors
752
+ )
753
+
754
+ # Display in largest to smallest order to reduce occlusion.
755
+ areas = None
756
+ if boxes is not None:
757
+ areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)
758
+ elif masks is not None:
759
+ areas = np.asarray([x.area() for x in masks])
760
+
761
+ # if areas is not None:
762
+ # # sorted_idxs = np.argsort(areas).tolist()
763
+ # sorted_idxs = np.argsort(-areas).tolist()
764
+ # # Re-order overlapped instances in descending order.
765
+ # boxes = boxes[sorted_idxs] if boxes is not None else None
766
+ # labels = [labels[k] for k in sorted_idxs] if labels is not None else None
767
+ # masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None
768
+ # binary_masks = (
769
+ # [binary_masks[idx] for idx in sorted_idxs]
770
+ # if binary_masks is not None
771
+ # else None
772
+ # )
773
+ # assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]
774
+ # keypoints = keypoints[sorted_idxs] if keypoints is not None else None
775
+
776
+ marks = []
777
+ marks_position = []
778
+ added_positions = set()
779
+ for i in range(num_instances):
780
+ color = assigned_colors[i]
781
+ if boxes is not None:
782
+ self.draw_box(boxes[i], alpha=1, edge_color=color)
783
+ if binary_masks is None:
784
+ # draw number for non-mask instances
785
+ mark = self._draw_number_in_box(
786
+ boxes[i], i + 1, color=color, label_mode=label_mode
787
+ )
788
+ marks.append(mark)
789
+
790
+ if binary_masks is not None:
791
+ mark, mask_position = self._draw_number_in_mask(
792
+ binary_mask=binary_masks[i].astype("uint8"),
793
+ text=i + 1,
794
+ color=color,
795
+ added_positions=added_positions,
796
+ label_mode=label_mode,
797
+ )
798
+ marks.append(mark)
799
+ marks_position.append(mask_position)
800
+
801
+ self.draw_binary_mask(
802
+ binary_masks[i],
803
+ color=color,
804
+ edge_color=_OFF_WHITE,
805
+ alpha=alpha,
806
+ )
807
+
808
+ if masks is not None:
809
+ for segment in masks[i].polygons:
810
+ self.draw_polygon(
811
+ segment.reshape(-1, 2), color, alpha=0
812
+ ) # alpha=0 so holes in masks are not colored
813
+
814
+ # draw keypoints
815
+ if keypoints is not None:
816
+ for keypoints_per_instance in keypoints:
817
+ self.draw_and_connect_keypoints(keypoints_per_instance)
818
+
819
+ # return labels, marks, sorted_idxs, marks_position
820
+ return labels, marks, marks_position
821
+
822
+ def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None):
823
+ """
824
+ Args:
825
+ boxes (ndarray): an Nx5 numpy array of
826
+ (x_center, y_center, width, height, angle_degrees) format
827
+ for the N objects in a single image.
828
+ labels (list[str]): the text to be displayed for each instance.
829
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
830
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
831
+ for full list of formats that the colors are accepted in.
832
+
833
+ Returns:
834
+ output (VisImage): image object with visualizations.
835
+ """
836
+ num_instances = len(boxes)
837
+
838
+ if assigned_colors is None:
839
+ assigned_colors = [
840
+ random_color(rgb=True, maximum=1) for _ in range(num_instances)
841
+ ]
842
+ if num_instances == 0:
843
+ return self.output
844
+
845
+ # Display in largest to smallest order to reduce occlusion.
846
+ if boxes is not None:
847
+ areas = boxes[:, 2] * boxes[:, 3]
848
+
849
+ sorted_idxs = np.argsort(-areas).tolist()
850
+ # Re-order overlapped instances in descending order.
851
+ boxes = boxes[sorted_idxs]
852
+ labels = [labels[k] for k in sorted_idxs] if labels is not None else None
853
+ colors = [assigned_colors[idx] for idx in sorted_idxs]
854
+
855
+ for i in range(num_instances):
856
+ self.draw_rotated_box_with_label(
857
+ boxes[i],
858
+ edge_color=colors[i],
859
+ label=labels[i] if labels is not None else None,
860
+ )
861
+
862
+ return self.output
863
+
864
+ def draw_and_connect_keypoints(self, keypoints):
865
+ """
866
+ Draws keypoints of an instance and follows the rules for keypoint connections
867
+ to draw lines between appropriate keypoints. This follows color heuristics for
868
+ line color.
869
+
870
+ Args:
871
+ keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints
872
+ and the last dimension corresponds to (x, y, probability).
873
+
874
+ Returns:
875
+ output (VisImage): image object with visualizations.
876
+ """
877
+ visible = {}
878
+ keypoint_names = self.metadata.get("keypoint_names")
879
+ for idx, keypoint in enumerate(keypoints):
880
+ # draw keypoint
881
+ x, y, prob = keypoint
882
+ if prob > self.keypoint_threshold:
883
+ self.draw_circle((x, y), color=_RED)
884
+ if keypoint_names:
885
+ keypoint_name = keypoint_names[idx]
886
+ visible[keypoint_name] = (x, y)
887
+
888
+ if self.metadata.get("keypoint_connection_rules"):
889
+ for kp0, kp1, color in self.metadata.keypoint_connection_rules:
890
+ if kp0 in visible and kp1 in visible:
891
+ x0, y0 = visible[kp0]
892
+ x1, y1 = visible[kp1]
893
+ color = tuple(x / 255.0 for x in color)
894
+ self.draw_line([x0, x1], [y0, y1], color=color)
895
+
896
+ # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip
897
+ # Note that this strategy is specific to person keypoints.
898
+ # For other keypoints, it should just do nothing
899
+ try:
900
+ ls_x, ls_y = visible["left_shoulder"]
901
+ rs_x, rs_y = visible["right_shoulder"]
902
+ mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2
903
+ except KeyError:
904
+ pass
905
+ else:
906
+ # draw line from nose to mid-shoulder
907
+ nose_x, nose_y = visible.get("nose", (None, None))
908
+ if nose_x is not None:
909
+ self.draw_line(
910
+ [nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED
911
+ )
912
+
913
+ try:
914
+ # draw line from mid-shoulder to mid-hip
915
+ lh_x, lh_y = visible["left_hip"]
916
+ rh_x, rh_y = visible["right_hip"]
917
+ except KeyError:
918
+ pass
919
+ else:
920
+ mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2
921
+ self.draw_line(
922
+ [mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED
923
+ )
924
+ return self.output
925
+
926
+ def mask_dims_from_binary(self, binary_mask):
927
+ ind_y, ind_x = np.where(binary_mask == 1)
928
+ min_ind_x = np.min(ind_x)
929
+ max_ind_x = np.max(ind_x)
930
+ min_ind_y = np.min(ind_y)
931
+ max_ind_y = np.max(ind_y)
932
+ return (max_ind_x - min_ind_x), (max_ind_y - min_ind_y)
933
+
934
+ def reposition_label(self, position, cur, binary_mask, move_count):
935
+ img_width, img_height = self.output.width, self.output.height
936
+ mask_width, mask_height = self.mask_dims_from_binary(binary_mask)
937
+
938
+ # set resposition thresholds
939
+ mask_width_limit, mask_height_limit = (
940
+ 25,
941
+ 25,
942
+ ) # limit for width and height size for object covering
943
+ location_diff_threshold = 15 # limit for the distance between two labels
944
+ x_boundry_limit, y_boundry_limit = (
945
+ 20,
946
+ 20,
947
+ ) # limit for the distancing the label from edges
948
+
949
+ offset_x = 15 # move in x direction
950
+ offset_y = 15 # move in y direction
951
+
952
+ x1, y1 = position
953
+
954
+ if (
955
+ mask_width < mask_width_limit
956
+ and mask_height < mask_height_limit
957
+ and move_count == 0
958
+ ):
959
+ move_x = offset_x if offset_x + x1 < img_width else -offset_x
960
+ move_y = offset_y if offset_y + y1 < img_height else -offset_y
961
+ return (True, move_x, move_y)
962
+
963
+ for x2, y2 in cur:
964
+ if abs(x1 - x2) + abs(y1 - y2) < location_diff_threshold:
965
+ move_x = offset_x if x1 >= x2 else -offset_x
966
+ move_y = offset_y if y1 >= y2 else -offset_y
967
+ move_x = (
968
+ 0
969
+ if x1 + move_x > img_width - x_boundry_limit
970
+ or x1 + move_x < x_boundry_limit
971
+ else move_x
972
+ )
973
+ move_y = (
974
+ 0
975
+ if y1 + move_y > img_height - y_boundry_limit
976
+ or y1 + move_y < y_boundry_limit
977
+ else move_y
978
+ )
979
+ return (
980
+ True,
981
+ move_x,
982
+ move_y,
983
+ )
984
+ return (False, 0, 0)
985
+
986
+ def locate_label_position(self, original_position, added_positions, binary_mask):
987
+ if added_positions is None or binary_mask is None:
988
+ return original_position
989
+
990
+ x, y = original_position
991
+
992
+ move_count = 0
993
+ reposition, x_move, y_move = self.reposition_label(
994
+ (x, y), added_positions, binary_mask, move_count
995
+ )
996
+ while reposition and move_count < 10:
997
+ x += x_move
998
+ y += y_move
999
+ move_count += 1
1000
+ reposition, x_move, y_move = self.reposition_label(
1001
+ (x, y), added_positions, binary_mask, move_count
1002
+ )
1003
+ added_positions.add((x, y))
1004
+ return x, y
1005
+
1006
+ """
1007
+ Primitive drawing functions:
1008
+ """
1009
+
1010
+ def draw_text(
1011
+ self,
1012
+ text,
1013
+ position,
1014
+ added_positions=None,
1015
+ binary_mask=None,
1016
+ *,
1017
+ font_size=None,
1018
+ color="g",
1019
+ horizontal_alignment="center",
1020
+ rotation=0,
1021
+ ):
1022
+ """
1023
+ Args:
1024
+ text (str): class label
1025
+ position (tuple): a tuple of the x and y coordinates to place text on image.
1026
+ font_size (int, optional): font of the text. If not provided, a font size
1027
+ proportional to the image width is calculated and used.
1028
+ color: color of the text. Refer to `matplotlib.colors` for full list
1029
+ of formats that are accepted.
1030
+ horizontal_alignment (str): see `matplotlib.text.Text`
1031
+ rotation: rotation angle in degrees CCW
1032
+
1033
+ Returns:
1034
+ output (VisImage): image object with text drawn.
1035
+ """
1036
+ if not font_size:
1037
+ font_size = self._default_font_size
1038
+
1039
+ # since the text background is dark, we don't want the text to be dark
1040
+ color = np.maximum(list(mplc.to_rgb(color)), 0.15)
1041
+ color[np.argmax(color)] = max(0.8, np.max(color))
1042
+
1043
+ def contrasting_color(rgb):
1044
+ """Returns 'white' or 'black' depending on which color contrasts more with the given RGB value."""
1045
+
1046
+ # Decompose the RGB tuple
1047
+ R, G, B = rgb
1048
+
1049
+ # Calculate the Y value
1050
+ Y = 0.299 * R + 0.587 * G + 0.114 * B
1051
+
1052
+ # If Y value is greater than 128, it's closer to white so return black. Otherwise, return white.
1053
+ return "black" if Y > 128 else "white"
1054
+
1055
+ bbox_background = contrasting_color(color * 255)
1056
+
1057
+ x, y = self.locate_label_position(
1058
+ original_position=position,
1059
+ added_positions=added_positions,
1060
+ binary_mask=binary_mask,
1061
+ )
1062
+
1063
+ self.output.ax.text(
1064
+ x,
1065
+ y,
1066
+ text,
1067
+ size=font_size * self.output.scale,
1068
+ family="sans-serif",
1069
+ bbox={
1070
+ "facecolor": bbox_background,
1071
+ "alpha": 0.8,
1072
+ "pad": 0.7,
1073
+ "edgecolor": "none",
1074
+ },
1075
+ verticalalignment="top",
1076
+ horizontalalignment=horizontal_alignment,
1077
+ color=color,
1078
+ zorder=10,
1079
+ rotation=rotation,
1080
+ )
1081
+ return self.output
1082
+
1083
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
1084
+ """
1085
+ Args:
1086
+ box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0
1087
+ are the coordinates of the image's top left corner. x1 and y1 are the
1088
+ coordinates of the image's bottom right corner.
1089
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1090
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
1091
+ for full list of formats that are accepted.
1092
+ line_style (string): the string to use to create the outline of the boxes.
1093
+
1094
+ Returns:
1095
+ output (VisImage): image object with box drawn.
1096
+ """
1097
+ x0, y0, x1, y1 = box_coord
1098
+ width = x1 - x0
1099
+ height = y1 - y0
1100
+
1101
+ linewidth = max(self._default_font_size / 12, 1) * self.boarder_width_multiplier
1102
+
1103
+ self.output.ax.add_patch(
1104
+ mpl.patches.Rectangle(
1105
+ (x0, y0),
1106
+ width,
1107
+ height,
1108
+ fill=False,
1109
+ edgecolor=edge_color,
1110
+ linewidth=linewidth * self.output.scale,
1111
+ alpha=alpha,
1112
+ linestyle=line_style,
1113
+ )
1114
+ )
1115
+ return self.output
1116
+
1117
+ def draw_rotated_box_with_label(
1118
+ self, rotated_box, alpha=0.5, edge_color="g", line_style="-", label=None
1119
+ ):
1120
+ """
1121
+ Draw a rotated box with label on its top-left corner.
1122
+
1123
+ Args:
1124
+ rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle),
1125
+ where cnt_x and cnt_y are the center coordinates of the box.
1126
+ w and h are the width and height of the box. angle represents how
1127
+ many degrees the box is rotated CCW with regard to the 0-degree box.
1128
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1129
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
1130
+ for full list of formats that are accepted.
1131
+ line_style (string): the string to use to create the outline of the boxes.
1132
+ label (string): label for rotated box. It will not be rendered when set to None.
1133
+
1134
+ Returns:
1135
+ output (VisImage): image object with box drawn.
1136
+ """
1137
+ cnt_x, cnt_y, w, h, angle = rotated_box
1138
+ area = w * h
1139
+ # use thinner lines when the box is small
1140
+ linewidth = self._default_font_size / (
1141
+ 6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3
1142
+ )
1143
+
1144
+ theta = angle * math.pi / 180.0
1145
+ c = math.cos(theta)
1146
+ s = math.sin(theta)
1147
+ rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)]
1148
+ # x: left->right ; y: top->down
1149
+ rotated_rect = [
1150
+ (s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect
1151
+ ]
1152
+ for k in range(4):
1153
+ j = (k + 1) % 4
1154
+ self.draw_line(
1155
+ [rotated_rect[k][0], rotated_rect[j][0]],
1156
+ [rotated_rect[k][1], rotated_rect[j][1]],
1157
+ color=edge_color,
1158
+ linestyle="--" if k == 1 else line_style,
1159
+ linewidth=linewidth,
1160
+ )
1161
+
1162
+ if label is not None:
1163
+ text_pos = rotated_rect[1] # topleft corner
1164
+
1165
+ height_ratio = h / np.sqrt(self.output.height * self.output.width)
1166
+ label_color = self._change_color_brightness(
1167
+ edge_color, brightness_factor=0.7
1168
+ )
1169
+ font_size = (
1170
+ np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)
1171
+ * 0.5
1172
+ * self._default_font_size
1173
+ )
1174
+ self.draw_text(
1175
+ label, text_pos, color=label_color, font_size=font_size, rotation=angle
1176
+ )
1177
+
1178
+ return self.output
1179
+
1180
+ def draw_circle(self, circle_coord, color, radius=3):
1181
+ """
1182
+ Args:
1183
+ circle_coord (list(int) or tuple(int)): contains the x and y coordinates
1184
+ of the center of the circle.
1185
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1186
+ formats that are accepted.
1187
+ radius (int): radius of the circle.
1188
+
1189
+ Returns:
1190
+ output (VisImage): image object with box drawn.
1191
+ """
1192
+ x, y = circle_coord
1193
+ self.output.ax.add_patch(
1194
+ mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color)
1195
+ )
1196
+ return self.output
1197
+
1198
+ def draw_line(self, x_data, y_data, color, linestyle="-", linewidth=None):
1199
+ """
1200
+ Args:
1201
+ x_data (list[int]): a list containing x values of all the points being drawn.
1202
+ Length of list should match the length of y_data.
1203
+ y_data (list[int]): a list containing y values of all the points being drawn.
1204
+ Length of list should match the length of x_data.
1205
+ color: color of the line. Refer to `matplotlib.colors` for a full list of
1206
+ formats that are accepted.
1207
+ linestyle: style of the line. Refer to `matplotlib.lines.Line2D`
1208
+ for a full list of formats that are accepted.
1209
+ linewidth (float or None): width of the line. When it's None,
1210
+ a default value will be computed and used.
1211
+
1212
+ Returns:
1213
+ output (VisImage): image object with line drawn.
1214
+ """
1215
+ if linewidth is None:
1216
+ linewidth = self._default_font_size / 3
1217
+ linewidth = max(linewidth, 1)
1218
+ self.output.ax.add_line(
1219
+ mpl.lines.Line2D(
1220
+ x_data,
1221
+ y_data,
1222
+ linewidth=linewidth * self.output.scale,
1223
+ color=color,
1224
+ linestyle=linestyle,
1225
+ )
1226
+ )
1227
+ return self.output
1228
+
1229
+ def draw_binary_mask(
1230
+ self,
1231
+ binary_mask,
1232
+ color=None,
1233
+ *,
1234
+ edge_color=None,
1235
+ text=None,
1236
+ alpha=0.7,
1237
+ area_threshold=10,
1238
+ ):
1239
+ """
1240
+ Args:
1241
+ binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and
1242
+ W is the image width. Each value in the array is either a 0 or 1 value of uint8
1243
+ type.
1244
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1245
+ formats that are accepted. If None, will pick a random color.
1246
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1247
+ full list of formats that are accepted.
1248
+ text (str): if None, will be drawn on the object
1249
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1250
+ area_threshold (float): a connected component smaller than this area will not be shown.
1251
+
1252
+ Returns:
1253
+ output (VisImage): image object with mask drawn.
1254
+ """
1255
+ if color is None:
1256
+ color = random_color(rgb=True, maximum=1)
1257
+ color = mplc.to_rgb(color)
1258
+
1259
+ has_valid_segment = False
1260
+ binary_mask = binary_mask.astype("uint8") # opencv needs uint8
1261
+ mask = GenericMask(binary_mask, self.output.height, self.output.width)
1262
+ shape2d = (binary_mask.shape[0], binary_mask.shape[1])
1263
+
1264
+ if not mask.has_holes:
1265
+ # draw polygons for regular masks
1266
+ for segment in mask.polygons:
1267
+ area = mask_util.area(
1268
+ mask_util.frPyObjects([segment], shape2d[0], shape2d[1])
1269
+ )
1270
+ if area < (area_threshold or 0):
1271
+ continue
1272
+ has_valid_segment = True
1273
+ segment = segment.reshape(-1, 2)
1274
+ self.draw_polygon(
1275
+ segment, color=color, edge_color=edge_color, alpha=alpha
1276
+ )
1277
+ else:
1278
+ # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon
1279
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1280
+ rgba[:, :, :3] = color
1281
+ rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha
1282
+ has_valid_segment = True
1283
+ self.output.ax.imshow(
1284
+ rgba, extent=(0, self.output.width, self.output.height, 0)
1285
+ )
1286
+
1287
+ if text is not None and has_valid_segment:
1288
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1289
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1290
+ return self.output
1291
+
1292
+ def draw_binary_mask_with_number(
1293
+ self,
1294
+ binary_mask,
1295
+ color=None,
1296
+ *,
1297
+ edge_color=None,
1298
+ text=None,
1299
+ label_mode="1",
1300
+ alpha=0.1,
1301
+ anno_mode=["Mask"],
1302
+ area_threshold=10,
1303
+ ):
1304
+ """
1305
+ Args:
1306
+ binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and
1307
+ W is the image width. Each value in the array is either a 0 or 1 value of uint8
1308
+ type.
1309
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1310
+ formats that are accepted. If None, will pick a random color.
1311
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1312
+ full list of formats that are accepted.
1313
+ text (str): if None, will be drawn on the object
1314
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1315
+ area_threshold (float): a connected component smaller than this area will not be shown.
1316
+
1317
+ Returns:
1318
+ output (VisImage): image object with mask drawn.
1319
+ """
1320
+ if color is None:
1321
+ randint = random.randint(0, len(self.color_proposals) - 1)
1322
+ color = self.color_proposals[randint]
1323
+ color = mplc.to_rgb(color)
1324
+
1325
+ has_valid_segment = True
1326
+ binary_mask = binary_mask.astype("uint8") # opencv needs uint8
1327
+ mask = GenericMask(binary_mask, self.output.height, self.output.width)
1328
+ shape2d = (binary_mask.shape[0], binary_mask.shape[1])
1329
+ bbox = mask.bbox()
1330
+
1331
+ if "Mask" in anno_mode:
1332
+ if not mask.has_holes:
1333
+ # draw polygons for regular masks
1334
+ for segment in mask.polygons:
1335
+ area = mask_util.area(
1336
+ mask_util.frPyObjects([segment], shape2d[0], shape2d[1])
1337
+ )
1338
+ if area < (area_threshold or 0):
1339
+ continue
1340
+ has_valid_segment = True
1341
+ segment = segment.reshape(-1, 2)
1342
+ self.draw_polygon(
1343
+ segment, color=color, edge_color=edge_color, alpha=alpha
1344
+ )
1345
+ else:
1346
+ # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon
1347
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1348
+ rgba[:, :, :3] = color
1349
+ rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha
1350
+ has_valid_segment = True
1351
+ self.output.ax.imshow(
1352
+ rgba, extent=(0, self.output.width, self.output.height, 0)
1353
+ )
1354
+
1355
+ if "Box" in anno_mode:
1356
+ self.draw_box(bbox, edge_color=color, alpha=0.75)
1357
+
1358
+ if "Mark" in anno_mode:
1359
+ has_valid_segment = True
1360
+ else:
1361
+ has_valid_segment = False
1362
+
1363
+ if text is not None and has_valid_segment:
1364
+ # lighter_color = tuple([x*0.2 for x in color])
1365
+ lighter_color = [
1366
+ 1,
1367
+ 1,
1368
+ 1,
1369
+ ] # self._change_color_brightness(color, brightness_factor=0.7)
1370
+ self._draw_number_in_mask(
1371
+ binary_mask=binary_mask,
1372
+ text=text,
1373
+ color=lighter_color,
1374
+ label_mode=label_mode,
1375
+ )
1376
+ return self.output
1377
+
1378
+ def draw_soft_mask(self, soft_mask, color=None, *, text=None, alpha=0.5):
1379
+ """
1380
+ Args:
1381
+ soft_mask (ndarray): float array of shape (H, W), each value in [0, 1].
1382
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1383
+ formats that are accepted. If None, will pick a random color.
1384
+ text (str): if None, will be drawn on the object
1385
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1386
+
1387
+ Returns:
1388
+ output (VisImage): image object with mask drawn.
1389
+ """
1390
+ if color is None:
1391
+ color = random_color(rgb=True, maximum=1)
1392
+ color = mplc.to_rgb(color)
1393
+
1394
+ shape2d = (soft_mask.shape[0], soft_mask.shape[1])
1395
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1396
+ rgba[:, :, :3] = color
1397
+ rgba[:, :, 3] = soft_mask * alpha
1398
+ self.output.ax.imshow(
1399
+ rgba, extent=(0, self.output.width, self.output.height, 0)
1400
+ )
1401
+
1402
+ if text is not None:
1403
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1404
+ binary_mask = (soft_mask > 0.5).astype("uint8")
1405
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1406
+ return self.output
1407
+
1408
+ def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):
1409
+ """
1410
+ Args:
1411
+ segment: numpy array of shape Nx2, containing all the points in the polygon.
1412
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1413
+ formats that are accepted.
1414
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1415
+ full list of formats that are accepted. If not provided, a darker shade
1416
+ of the polygon color will be used instead.
1417
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1418
+
1419
+ Returns:
1420
+ output (VisImage): image object with polygon drawn.
1421
+ """
1422
+ if edge_color is None:
1423
+ # make edge color darker than the polygon color
1424
+ if alpha > 0.8:
1425
+ edge_color = self._change_color_brightness(
1426
+ color, brightness_factor=-0.7
1427
+ )
1428
+ else:
1429
+ edge_color = color
1430
+ edge_color = mplc.to_rgb(edge_color) + (1,)
1431
+
1432
+ polygon = mpl.patches.Polygon(
1433
+ segment,
1434
+ fill=True,
1435
+ facecolor=mplc.to_rgb(color) + (alpha,),
1436
+ edgecolor=edge_color,
1437
+ linewidth=max(self._default_font_size // 15 * self.output.scale, 1),
1438
+ )
1439
+ self.output.ax.add_patch(polygon)
1440
+ return self.output
1441
+
1442
+ """
1443
+ Internal methods:
1444
+ """
1445
+
1446
+ def _jitter(self, color):
1447
+ """
1448
+ Randomly modifies given color to produce a slightly different color than the color given.
1449
+
1450
+ Args:
1451
+ color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color
1452
+ picked. The values in the list are in the [0.0, 1.0] range.
1453
+
1454
+ Returns:
1455
+ jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the
1456
+ color after being jittered. The values in the list are in the [0.0, 1.0] range.
1457
+ """
1458
+ color = mplc.to_rgb(color)
1459
+ # np.random.seed(0)
1460
+ vec = np.random.rand(3)
1461
+ # better to do it in another color space
1462
+ vec = vec / np.linalg.norm(vec) * 0.5
1463
+ res = np.clip(vec + color, 0, 1)
1464
+ return tuple(res)
1465
+
1466
+ def _create_grayscale_image(self, mask=None):
1467
+ """
1468
+ Create a grayscale version of the original image.
1469
+ The colors in masked area, if given, will be kept.
1470
+ """
1471
+ img_bw = self.img.astype("f4").mean(axis=2)
1472
+ img_bw = np.stack([img_bw] * 3, axis=2)
1473
+ if mask is not None:
1474
+ img_bw[mask] = self.img[mask]
1475
+ return img_bw
1476
+
1477
+ def _change_color_brightness(self, color, brightness_factor):
1478
+ """
1479
+ Depending on the brightness_factor, gives a lighter or darker color i.e. a color with
1480
+ less or more saturation than the original color.
1481
+
1482
+ Args:
1483
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1484
+ formats that are accepted.
1485
+ brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of
1486
+ 0 will correspond to no change, a factor in [-1.0, 0) range will result in
1487
+ a darker color and a factor in (0, 1.0] range will result in a lighter color.
1488
+
1489
+ Returns:
1490
+ modified_color (tuple[double]): a tuple containing the RGB values of the
1491
+ modified color. Each value in the tuple is in the [0.0, 1.0] range.
1492
+ """
1493
+ assert brightness_factor >= -1.0 and brightness_factor <= 1.0
1494
+ color = mplc.to_rgb(color)
1495
+ polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
1496
+ modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])
1497
+ modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
1498
+ modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
1499
+ modified_color = colorsys.hls_to_rgb(
1500
+ polygon_color[0], modified_lightness, polygon_color[2]
1501
+ )
1502
+ return modified_color
1503
+
1504
+ def _convert_boxes(self, boxes):
1505
+ """
1506
+ Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension.
1507
+ """
1508
+ if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):
1509
+ return boxes.tensor.detach().numpy()
1510
+ else:
1511
+ return np.asarray(boxes)
1512
+
1513
+ def _convert_masks(self, masks_or_polygons):
1514
+ """
1515
+ Convert different format of masks or polygons to a tuple of masks and polygons.
1516
+
1517
+ Returns:
1518
+ list[GenericMask]:
1519
+ """
1520
+
1521
+ m = masks_or_polygons
1522
+ if isinstance(m, PolygonMasks):
1523
+ m = m.polygons
1524
+ if isinstance(m, BitMasks):
1525
+ m = m.tensor.numpy()
1526
+ if isinstance(m, torch.Tensor):
1527
+ m = m.numpy()
1528
+ ret = []
1529
+ for x in m:
1530
+ if isinstance(x, GenericMask):
1531
+ ret.append(x)
1532
+ else:
1533
+ ret.append(GenericMask(x, self.output.height, self.output.width))
1534
+ return ret
1535
+
1536
+ def _draw_number_in_box(self, box, text, color, label_mode="1"):
1537
+ """
1538
+ Find proper places to draw text given a box.
1539
+ """
1540
+ x0, y0, x1, y1 = box
1541
+ text_pos = (x0, y0) # if drawing boxes, put text on the box corner.
1542
+ horiz_align = "left"
1543
+ # for small objects, draw text at the side to avoid occlusion
1544
+ instance_area = (y1 - y0) * (x1 - x0)
1545
+ if (
1546
+ instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale
1547
+ or y1 - y0 < 40 * self.output.scale
1548
+ ):
1549
+ if y1 >= self.output.height - 5:
1550
+ text_pos = (x1, y0)
1551
+ else:
1552
+ text_pos = (x0, y1)
1553
+
1554
+ height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)
1555
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1556
+ font_size = (
1557
+ np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)
1558
+ * 0.65
1559
+ * self._default_font_size
1560
+ )
1561
+ if label_mode == "a":
1562
+ text = self.number_to_string(int(text))
1563
+ else:
1564
+ text = text
1565
+ self.draw_text(
1566
+ text,
1567
+ text_pos,
1568
+ color=lighter_color,
1569
+ horizontal_alignment=horiz_align,
1570
+ font_size=font_size,
1571
+ )
1572
+
1573
+ return str(text)
1574
+
1575
+ @staticmethod
1576
+ def number_to_string(n):
1577
+ chars = []
1578
+ while n:
1579
+ n, remainder = divmod(n - 1, 26)
1580
+ chars.append(chr(97 + remainder))
1581
+ return "".join(reversed(chars))
1582
+
1583
+ def _draw_number_in_mask(
1584
+ self, binary_mask, text, color, added_positions=None, label_mode="1"
1585
+ ):
1586
+ """
1587
+ Find proper places to draw text given a binary mask.
1588
+ """
1589
+ binary_mask = np.pad(binary_mask, ((1, 1), (1, 1)), "constant")
1590
+ mask_dt = cv2.distanceTransform(binary_mask, cv2.DIST_L2, 0)
1591
+ mask_dt = mask_dt[1:-1, 1:-1]
1592
+ max_dist = np.max(mask_dt)
1593
+ coords_y, coords_x = np.where(mask_dt == max_dist) # coords is [y, x]
1594
+
1595
+ if label_mode == "a":
1596
+ text = self.number_to_string(int(text))
1597
+ else:
1598
+ text = text
1599
+
1600
+ text_position = (
1601
+ coords_x[len(coords_x) // 2] + 2,
1602
+ coords_y[len(coords_y) // 2] - 6,
1603
+ )
1604
+ self.draw_text(
1605
+ text,
1606
+ text_position,
1607
+ added_positions=added_positions,
1608
+ binary_mask=binary_mask,
1609
+ color=color,
1610
+ )
1611
+
1612
+ return str(text), text_position
1613
+
1614
+ # _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)
1615
+ # if stats[1:, -1].size == 0:
1616
+ # return
1617
+ # largest_component_id = np.argmax(stats[1:, -1]) + 1
1618
+
1619
+ # # draw text on the largest component, as well as other very large components.
1620
+ # for cid in range(1, _num_cc):
1621
+ # if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:
1622
+ # # median is more stable than centroid
1623
+ # # center = centroids[largest_component_id]
1624
+ # center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]
1625
+ # # bottom=np.max((cc_labels == cid).nonzero(), axis=1)[::-1]
1626
+ # # center[1]=bottom[1]+2
1627
+ # self.draw_text(text, center, color=color)
1628
+
1629
+ def _draw_text_in_mask(self, binary_mask, text, color):
1630
+ """
1631
+ Find proper places to draw text given a binary mask.
1632
+ """
1633
+ _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(
1634
+ binary_mask, 8
1635
+ )
1636
+ if stats[1:, -1].size == 0:
1637
+ return
1638
+ largest_component_id = np.argmax(stats[1:, -1]) + 1
1639
+
1640
+ # draw text on the largest component, as well as other very large components.
1641
+ for cid in range(1, _num_cc):
1642
+ if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:
1643
+ # median is more stable than centroid
1644
+ # center = centroids[largest_component_id]
1645
+ center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]
1646
+ bottom = np.max((cc_labels == cid).nonzero(), axis=1)[::-1]
1647
+ center[1] = bottom[1] + 2
1648
+ self.draw_text(text, center, color=color)
1649
+
1650
+ def _convert_keypoints(self, keypoints):
1651
+ if isinstance(keypoints, Keypoints):
1652
+ keypoints = keypoints.tensor
1653
+ keypoints = np.asarray(keypoints)
1654
+ return keypoints
1655
+
1656
+ def get_output(self):
1657
+ """
1658
+ Returns:
1659
+ output (VisImage): the image output containing the visualizations added
1660
+ to the image.
1661
+ """
1662
+ return self.output
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/helpers/zoom_in.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import io
4
+ import math
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+ import pycocotools.mask as mask_utils
9
+ from PIL import Image
10
+
11
+ from .som_utils import ColorPalette, draw_box, draw_mask, draw_text
12
+
13
+
14
+ def render_zoom_in(
15
+ object_data,
16
+ image_file,
17
+ show_box: bool = True,
18
+ show_text: bool = False,
19
+ show_holes: bool = True,
20
+ mask_alpha: float = 0.15,
21
+ ):
22
+ """
23
+ Render a two-panel visualization with a cropped original view (left/upper) and a zoomed-in
24
+ mask overlay (right/lower), then return it as a PIL.Image along with the chosen mask color (hex).
25
+
26
+ Parameters
27
+ ----------
28
+ object_data : dict
29
+ Dict containing "labels" and COCO RLE "segmentation".
30
+ Expected:
31
+ object_data["labels"][0]["noun_phrase"] : str
32
+ object_data["segmentation"] : COCO RLE (with "size": [H, W])
33
+ image_file : PIL.Image.Image
34
+ Source image (PIL).
35
+ show_box : bool
36
+ Whether to draw the bbox on the cropped original panel.
37
+ show_text : bool
38
+ Whether to draw the noun phrase label near the bbox.
39
+ show_holes : bool
40
+ Whether to render mask holes (passed through to draw_mask).
41
+ mask_alpha : float
42
+ Alpha for the mask overlay.
43
+
44
+ Returns
45
+ -------
46
+ pil_img : PIL.Image.Image
47
+ The composed visualization image.
48
+ color_hex : str
49
+ Hex string of the chosen mask color.
50
+ """
51
+
52
+ # ---- local constants (avoid module-level globals) ----
53
+ _AREA_LARGE = 0.25
54
+ _AREA_MEDIUM = 0.05
55
+
56
+ # ---- local helpers (avoid name collisions in a larger class) ----
57
+ def _get_shift(x, w, w_new, w_img):
58
+ assert 0 <= w_new <= w_img
59
+ shift = (w_new - w) / 2
60
+ if x - shift + w_new > w_img:
61
+ shift = x + w_new - w_img
62
+ return min(x, shift)
63
+
64
+ def _get_zoom_in_box(mask_box_xywh, img_h, img_w, mask_area):
65
+ box_w, box_h = mask_box_xywh[2], mask_box_xywh[3]
66
+ w_new = min(box_w + max(0.2 * box_w, 16), img_w)
67
+ h_new = min(box_h + max(0.2 * box_h, 16), img_h)
68
+
69
+ mask_relative_area = mask_area / (w_new * h_new)
70
+
71
+ # zoom-in (larger box if mask is relatively big)
72
+ w_new_large, h_new_large = w_new, h_new
73
+ if mask_relative_area > _AREA_LARGE:
74
+ ratio_large = math.sqrt(mask_relative_area / _AREA_LARGE)
75
+ w_new_large = min(w_new * ratio_large, img_w)
76
+ h_new_large = min(h_new * ratio_large, img_h)
77
+
78
+ w_shift_large = _get_shift(
79
+ mask_box_xywh[0], mask_box_xywh[2], w_new_large, img_w
80
+ )
81
+ h_shift_large = _get_shift(
82
+ mask_box_xywh[1], mask_box_xywh[3], h_new_large, img_h
83
+ )
84
+ zoom_in_box = [
85
+ mask_box_xywh[0] - w_shift_large,
86
+ mask_box_xywh[1] - h_shift_large,
87
+ w_new_large,
88
+ h_new_large,
89
+ ]
90
+
91
+ # crop box for the original/cropped image
92
+ w_new_medium, h_new_medium = w_new, h_new
93
+ if mask_relative_area > _AREA_MEDIUM:
94
+ ratio_med = math.sqrt(mask_relative_area / _AREA_MEDIUM)
95
+ w_new_medium = min(w_new * ratio_med, img_w)
96
+ h_new_medium = min(h_new * ratio_med, img_h)
97
+
98
+ w_shift_medium = _get_shift(
99
+ mask_box_xywh[0], mask_box_xywh[2], w_new_medium, img_w
100
+ )
101
+ h_shift_medium = _get_shift(
102
+ mask_box_xywh[1], mask_box_xywh[3], h_new_medium, img_h
103
+ )
104
+ img_crop_box = [
105
+ mask_box_xywh[0] - w_shift_medium,
106
+ mask_box_xywh[1] - h_shift_medium,
107
+ w_new_medium,
108
+ h_new_medium,
109
+ ]
110
+ return zoom_in_box, img_crop_box
111
+
112
+ # ---- main body ----
113
+ # Input parsing
114
+ object_label = object_data["labels"][0]["noun_phrase"]
115
+ img = image_file.convert("RGB")
116
+ bbox_xywh = mask_utils.toBbox(object_data["segmentation"]) # [x, y, w, h]
117
+
118
+ # Choose a stable, visually distant color based on crop
119
+ bbox_xyxy = [
120
+ bbox_xywh[0],
121
+ bbox_xywh[1],
122
+ bbox_xywh[0] + bbox_xywh[2],
123
+ bbox_xywh[1] + bbox_xywh[3],
124
+ ]
125
+ crop_img = img.crop(bbox_xyxy)
126
+ color_palette = ColorPalette.default()
127
+ color_obj, _ = color_palette.find_farthest_color(np.array(crop_img))
128
+ color = np.array([color_obj.r / 255, color_obj.g / 255, color_obj.b / 255])
129
+ color_hex = f"#{color_obj.r:02x}{color_obj.g:02x}{color_obj.b:02x}"
130
+
131
+ # Compute zoom-in / crop boxes
132
+ img_h, img_w = object_data["segmentation"]["size"]
133
+ mask_area = mask_utils.area(object_data["segmentation"])
134
+ zoom_in_box, img_crop_box = _get_zoom_in_box(bbox_xywh, img_h, img_w, mask_area)
135
+
136
+ # Layout choice
137
+ w, h = img_crop_box[2], img_crop_box[3]
138
+ if w < h:
139
+ fig, (ax1, ax2) = plt.subplots(1, 2)
140
+ else:
141
+ fig, (ax1, ax2) = plt.subplots(2, 1)
142
+
143
+ # Panel 1: cropped original with optional box/text
144
+ img_crop_box_xyxy = [
145
+ img_crop_box[0],
146
+ img_crop_box[1],
147
+ img_crop_box[0] + img_crop_box[2],
148
+ img_crop_box[1] + img_crop_box[3],
149
+ ]
150
+ img1 = img.crop(img_crop_box_xyxy)
151
+ bbox_xywh_rel = [
152
+ bbox_xywh[0] - img_crop_box[0],
153
+ bbox_xywh[1] - img_crop_box[1],
154
+ bbox_xywh[2],
155
+ bbox_xywh[3],
156
+ ]
157
+ ax1.imshow(img1)
158
+ ax1.axis("off")
159
+ if show_box:
160
+ draw_box(ax1, bbox_xywh_rel, edge_color=color)
161
+ if show_text:
162
+ x0, y0 = bbox_xywh_rel[0] + 2, bbox_xywh_rel[1] + 2
163
+ draw_text(ax1, object_label, [x0, y0], color=color)
164
+
165
+ # Panel 2: zoomed-in mask overlay
166
+ binary_mask = mask_utils.decode(object_data["segmentation"])
167
+ alpha = Image.fromarray((binary_mask * 255).astype("uint8"))
168
+ img_rgba = img.convert("RGBA")
169
+ img_rgba.putalpha(alpha)
170
+ zoom_in_box_xyxy = [
171
+ zoom_in_box[0],
172
+ zoom_in_box[1],
173
+ zoom_in_box[0] + zoom_in_box[2],
174
+ zoom_in_box[1] + zoom_in_box[3],
175
+ ]
176
+ img_with_alpha_zoomin = img_rgba.crop(zoom_in_box_xyxy)
177
+ alpha_zoomin = img_with_alpha_zoomin.split()[3]
178
+ binary_mask_zoomin = np.array(alpha_zoomin).astype(bool)
179
+
180
+ ax2.imshow(img_with_alpha_zoomin.convert("RGB"))
181
+ ax2.axis("off")
182
+ draw_mask(
183
+ ax2, binary_mask_zoomin, color=color, show_holes=show_holes, alpha=mask_alpha
184
+ )
185
+
186
+ plt.tight_layout()
187
+
188
+ # Buffer -> PIL.Image
189
+ buf = io.BytesIO()
190
+ fig.savefig(buf, format="png", bbox_inches="tight", pad_inches=0, dpi=100)
191
+ plt.close(fig)
192
+ buf.seek(0)
193
+ pil_img = Image.open(buf)
194
+
195
+ return pil_img, color_hex
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/system_prompts/system_prompt.txt ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful visual-concept grounding assistant capable of leveraging tool calls to ground concepts the user refers to, and providing structured JSON outputs and tool calls.
2
+ The user may provide you with a referring expression that matches some part(s) of the image, or a question whose answer points to some part(s) of the image.
3
+ You should observe and analyze the image along with the initial user input query very carefully, note all details in the image, think about what the user is actually referring to, how to leverage existing tools below to ground the target(s), and then call exactly one tool per turn.
4
+ At each turn, all available mask(s) will be renumbered and re-rendered on the most recent image provided to you. The numbering and coloring can be different from previous turns. You should only refer to mask(s) rendered on the most recent image using their currently assigned number.
5
+ If a tool call does not produce the intended output, do not give up; be creative and try calling the segment_phrase tool again with different parameters, or try a different tool. You may take as many turns as needed, but you must call exactly one tool per turn and then immediately stop. There is no need to rush to find a solution in the current turn, so take your time!
6
+
7
+
8
+ How you should understand the initial user input query and the raw input image:
9
+
10
+ 1. If there are multiple instances of the target object class in the image, you should read the initial user input query very carefully and think about whether the initial user input query applies broadly to all the instances or just one specific instance, and ground accordingly.
11
+ 2. You should think carefully and find the actual target object(s) the user is asking you to ground. Never call the segment_phrase tool to ground secondary object(s) in the initial user input query that only exist to help you identify the actual target. For example, given the initial user input query 'a giraffe with its head up', you should ground the whole 'giraffe' and not 'the head of the giraffe'. Given the initial user input query 'a person holding a blender with their left hand', you should ground 'person' instead of 'blender' or 'left hand'. Given the initial user input query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should ground 'woman' instead of 'dog' or 'bicycle'. Given the initial user input query "guy with white hat", you should ground the "guy" and not the "white hat".
12
+ 3. Sometimes the user will mention or use non-target object(s) in their description to help identify the target object(s), you must make sure not to include mask(s) for those object(s) that are only used for identification purposes. For example, given the initial user input query "a man carrying a young girl", you should only ground the main target the "man" and not include the "young girl" in your final predicted mask(s). Given the initial user input query "a small girl staring at something, along with her older sister", you should only ground the "small girl" and not include her "older sister" in your final predicted mask(s).
13
+ 4. Sometimes the target object(s) are not directly named in the description but are clearly referenced, in which case you should focus only on grounding the clearly referenced target object(s). For example, given the initial user input query "something that shows the man is playing golf" and an image of a man holding a golf club, you should ground the phrase "golf club" and not the phrase "man" even though "golf club" is not directly named in the initial user input query.
14
+ 5. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
15
+ 6. Sometimes the initial user input query can be slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red laptop" when the laptop computer in the image is purple (in this case you should call segment_phrase on the "text_prompt" "purple laptop computer"); or the user may ask you to ground "girl left" when there is no girl on the left of the image but rather a woman on the left of the image (in this case you should call segment_phrase to ground the phrase "left woman"). In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query. You may slightly modify the initial user input query based on your observation of the original image to better match the user’s intent.
16
+ 7. Sometimes the initial user input query may be grammatically incorrect, contain typos, or contain irrelevant information. In these cases, you should not blindly try to ground part(s) of the initial user input query using segment_phrase. Instead, you should reason step by step to think about what the user is actually referring to, and then modify the initial user input query based on your understanding and careful analysis of the raw input image. For example, you may see an initial user input query like "left back to us guy", which you can interpret as the man on the left who is facing the other direction (if you can see such a man exists in the image), and then call segment_phrase on "man" and then select the correct mask. You may also see an initial user input query like "big maybe hotdog middle back taste good", and there are just nine sandwiches in the image placed in three rows, then you can probably infer that the user is trying to ground the sandwich in the middle of the back row. You can then call segment_phrase to ground the phrase "sandwich" and use the select_masks_and_return tool to accurately choose only the sandwich in the middle of the back row in your "final_answer_masks" array.
17
+ 8. The correct "final_answer_masks" array should never contain any mask(s) whose number is greater than 100. For example, you may never select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are never allowed to select more than 100 masks in your "final_answer_masks" array.
18
+ 9. Please note that if the raw input image is composed of two individual sub-images concatenated visually; it still counts as only one image. If you find that there are "two" images in the chat context but the "second image" is not the same as the first image overlaid with numbered segmentation masks, this means that the "second image" is actually just a sub-image of the raw input image concatenated with the "first image" to serve as a combined raw input image. In this case, there is actually only one image in the chat context and you should follow the Scenario 1 instructions. This is very important!
19
+
20
+ You should always follow the response format defined below and complete the Steps for Each Turn as specified below. Never break the specified format for any reason.
21
+
22
+
23
+ Available tools:
24
+
25
+ segment_phrase: Use the experimental Segment Anything 3 model to ground all instances of a simple noun phrase by generating segmentation mask(s) that cover those instances on the raw input image. At the same time, all previously generated mask(s) will be deleted and cannot be referred to in future messages.
26
+ Use cases: "Given a simple, direct, and singular noun phrase (not a referring expression that requires additional understanding/reasoning), segment_phrase will try to locate all object instance(s) on the raw input image that match the simple noun phrase you provided. The tool will also render all of the generated segmentation mask(s) onto the image for you to examine and decide the next step."
27
+ Parameters for segment_phrase: {"type": "object", "properties": {"text_prompt": {"type": "string", "description": "A short and simple noun phrase, e.g., rope, bird beak, speed monitor, brown handbag, person torso"}}, "required": ["text_prompt"]}
28
+ Return type: A new image with differently colored segmentation mask(s) rendered on it, and a text message indicating the number of mask(s) generated by the experimental Segment Anything 3 model for this "text_prompt" only.
29
+ Important rules for using the segment_phrase tool:
30
+ 1. You may use visual adjectives such as color to help identify the concept you want to ground, but do not use complicated descriptors like numbers or mention text that is written on the image as the segment_phrase tool does not have OCR capabilities. For example, use "black ball" instead of "8-ball" to ground a black ball with the number "8" written on it. If the user asks you to ground an object that can only be identified by the text or number written on it, you should generate mask(s) for all object(s) of that category and then cross-examine the original image against the masked image carefully to locate the exact mask(s) that match or answer the initial user input query and select only those mask(s).
31
+ 2. Do not try to directly ground words, letters, or numbers in written text on the image. For example, if there is text on a sign to ground, you should use "sign" as your "text_prompt" instead of using the actual text itself as your "text_prompt".
32
+ 3. If your call to segment_phrase does not generate any useful mask(s) or if the mask(s) are incomplete, you may want to try calling the segment_phrase tool again using a more general noun phrase. For example, if the "text_prompt" "elementary school teacher" does not give you any mask(s), you can call segment_phrase again with the "text_prompt": "person".
33
+ 4. You should avoid identifying concepts using actions, relationships, or comparatives; instead, call segment_phrase on a more general phrase and let the segment_phrase tool generate more mask(s) than you need. Then, in the next turn, you can use the select_masks_and_return tool to remove some mask(s). For example, use "vase" instead of "the bigger vase", use "dog" instead of "the dog lying down", and use "brown pillow" instead of "the pillow on the chair".
34
+ 5. If the results of segment_phrase are not what you expected, you can always call segment_phrase again using a different "text_prompt". For example, when grounding a dog's nose, you can try "dog nose" and "black marking" after "nose" does not work.
35
+ 6. Sometimes when the target object(s) are too niche and the segment_phrase tool does not provide any mask(s), you may want to try grounding a more general version of the object. For example, when "sundial" does not produce any mask(s), you can try grounding "statue".
36
+ 7. Be concise and get the right keywords; don't make your "text_prompt" long.
37
+ 8. Do not ever use the exact same "text_prompt" more than once. This is very important!
38
+ 9. Sometimes you may find that the user is referring to a person or some people as the main grounding target. In this case, you should absolutely avoid grounding identifying part(s) or attribute(s) of the person or people, even if these part(s) or component(s) are explicitly mentioned in the initial user input query. Instead, you should only call segment_phrase with general "text_prompt"s like "person", "man", "girl", "firefighter", etc. that refer to the person as a whole. Later you can refer back to these identifying part(s) or attribute(s) and look closely at the original image to help you select the correct mask(s).
39
+ 10. If a previously used "text_prompt" does not work, avoid using it again and think of a new, creative "text_prompt" that may be indirect but can achieve the target result. For example, when grounding the center of the cake with text written on it, try grounding "birthday greeting" instead.
40
+ 11. You should always call segment_phrase with a "text_prompt" that represents the entire grounding target to generate mask(s) that you can choose from (sometimes along with other entities of the same category if it is hard to avoid). Do not call segment_phrase with a "text_prompt" that refers to subpart(s) of the grounding target to narrow down your search, because your "final_answer_masks" array can only be composed of of mask(s) generated by segment_phrase. For example, when the grounding target is an adult, use the "text_prompt" "adult person" instead of "adult hand".
41
+ 12. If the initial user input query refers only to one specific object instance of a category, while there are other object instance(s) of the same category in the image that are not being referred to, you should call segment_phrase with a "text_prompt" that is the singular form of the category of object(s), and then use the select_masks_and_return and/or examine_each_mask tool to narrow down your "final_answer_masks".
42
+ 13. Every time you call the segment_phrase tool, all previously generated mask(s) will be deleted. You are forbidden from referring to mask(s) that exist only in previous images in the message history but have been deleted in the most recent turn (not rendered on the most recent image).
43
+ 14. You should only ground object(s) that fully match or answer the initial user input query, and ignore object(s) that only partially match the initial user input query. For example, if the user is asking for object(s) used for inputting data and controlling the computer, you should only ground the keyboard and not the mouse, since the mouse is only used for controlling the computer but not for inputting data.
44
+ 15. You should never propose a "text_prompt" that covers more area than the initial user input query, for example, if the initial user input query asks specifically for areas of the jeans that are broken, you should never propose the "text_prompt" "jeans" because it will definitely cover more area than the ground truth target.
45
+ 16. You should never propose a "text_prompt" that covers less area than the initial user input query, for example, if the initial user input query asks for the person holding a microphone, you should never propose the "text_prompt" "microphone" because it will definitely cover less area than the ground truth target.
46
+ 17. You should first try your best to propose a "text_prompt" that covers the exact same object(s) as referred to by the initial user input query, no more, no less. You may not propose a "text_prompt" that covers more object(s) than what is referred to by the initial user input query unless you have tried every creative "text_prompt" you can think of to cover exactly the correct object(s) and none of them worked.
47
+ 18. Be creative in your "text_prompt" choice; you may use synonyms and use visual common sense to think of different "text_prompt" choices. You have unlimited turns to call each tool, so take your time!
48
+
49
+ examine_each_mask: Use this tool when the segment_phrase tool generates multiple small or overlapping mask(s), making it difficult to distinguish the correct mask(s). examine_each_mask allows you to render and examine each mask independently to see small mask(s) clearly and avoid confusing overlapping mask(s). (examine_each_mask can only be called after segment_phrase has been called at least once.)
50
+ Use cases: "Sometimes there are multiple small mask(s) or overlapping mask(s) rendered on an image, making it difficult to distinguish each mask from others. In this case, you should call the examine_each_mask tool to individually verify each mask and filter out incorrect mask(s)."
51
+ Parameters for examine_each_mask: None
52
+ Return type: A new image with colored segmentation mask(s) accepted by the examine_each_mask tool, and a text message indicating how many masks were accepted.
53
+ Important rules for using the examine_each_mask tool:
54
+ 1. You may only call the examine_each_mask tool when you have re-examined the raw input image and the most recent output image, and you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, and there are no missing correct mask(s). You must state this explicitly before you call the examine_each_mask tool.
55
+ 2. Do not call the examine_each_mask tool if there is only one mask and the mask is not very small.
56
+ 3. Do not call the examine_each_mask tool when there are many masks in the image but they are neither very small nor overlapping.
57
+ 4. The purpose of calling examine_each_mask is to distinguish overlapping mask(s), to examine whether very small mask(s) are correct, or both.
58
+ 5. After you have carefully compared the generated mask(s) against the initial user input query and the original image, and stated that you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, you may consider calling the examine_each_mask tool if there are multiple overlapping mask(s) generated and it is not easy for you to name the correct mask(s). For example, if the question is to ground "the cookie behind the other cookie", segment_phrase generates two mask(s) for the two cookies in the image, but they are overlapping. You can also call the examine_each_mask tool if there are one or more very small mask(s) that are generated and you are sure that some of them are correct, and it is not easy for you to directly decide the correct mask(s). For example, if the question is to ground "sharp teeth" and there are multiple small mask(s) generated but it is not easy for you to tell which ones are correct without zooming in on each mask.
59
+ 6. Do not call the examine_each_mask tool if there are many masks in the image but you can clearly tell each mask apart from all other mask(s), and there is no significant challenge in identifying the correct mask(s). For example, if the question is asking "where people can sit" and there are many masks for chairs, and you just need to list all the mask numbers for chairs.
60
+ 7. You may not call the examine_each_mask tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
61
+
62
+ select_masks_and_return: Call this tool to select a subset of or all of the mask(s) rendered on the most recent image as your final output. When calling select_masks_and_return, you cannot select any mask(s) generated by previous rounds other than the most recent round in your "final_answer_masks". You can only use mask(s) from the most recent image in your message history. (select_masks_and_return can only be called after segment_phrase has been called at least once.)
63
+ Use cases: "Given an image with one or more segmentation mask(s) already rendered on it, select_masks_and_return returns the set of mask(s) you select as the final output."
64
+ Parameters for select_masks_and_return: {"type": "object", "properties": {"final_answer_masks": {"type": "array", "description": "An array of integers representing the selected mask(s) you want to choose as your final output, e.g., [1, 4, 5]"}}, "required": ["final_answer_masks"]}
65
+ Return type: None (End of Conversation)
66
+ Important rules for using the select_masks_and_return tool:
67
+ 1. Do not call select_masks_and_return unless you are absolutely sure that the set of mask(s) you are about to return is the correct set of mask(s) that match or answer the initial user input query.
68
+ 2. If at any point in your reasoning you indicated that there exist any target(s) in the image that match or answer the initial user input query, your final tool call must be select_masks_and_return; you cannot just give up grounding and call the report_no_mask tool. This is very important.
69
+ 3. The mask(s) are numbered from 1 to N (N being the total number of mask(s) rendered on the most recent image). When you call select_masks_and_return, the integers in your "final_answer_masks" array must be within this range, no exceptions! Make sure of this!
70
+ 4. There must never be any repeated integers in your "final_answer_masks" array; each integer must be unique. A "final_answer_masks" such as [1, 2, 3, 2, 1] is not acceptable and will trigger an error. You should avoid this format error at all costs.
71
+ 5. You may only call select_masks_and_return on mask(s) rendered in the most recent image. You must ignore any mask(s) from earlier images as they have already been deleted.
72
+ 6. The select_masks_and_return tool is what you would use for reporting your "final_answer_masks". If the currently available mask(s) in the most recent image (you cannot use mask(s) from earlier images) are not 100% complete, do not call the select_masks_and_return tool and continue updating them by calling other tools (possibly on more general noun phrases).
73
+ 7. Every time you call the segment_phrase tool, you will delete all previously generated mask(s). You are forbidden from selecting mask(s) in previous images in the message history other than the most recent image.
74
+ 8. Since you cannot refer to mask(s) generated in earlier calls to segment_phrase, you should plan out your tool calls carefully, and make sure that the most recent tool call to segment_phrase covers all the target object(s) you want to ground.
75
+ 9. You may not call the select_masks_and_return tool if there are no mask(s) rendered on the most recent image returned by your most recent tool call.
76
+ 10. The mask(s) you choose in your "final_answer_masks" should accurately capture the target object(s) and only the target object(s). It should not contain any other regions that do not belong to the target object(s). Nor should it contain only a part of the target object(s). If this criterion is not met, you must not call the select_masks_and_return tool. Instead, please continue using other tools to generate better mask(s).
77
+ 11. Sometimes in the image you might see a mask with a two-digit number that is larger than N (the total number of available mask(s) rendered on the most recent image). For example, if the user tells you there are only 3 masks generated on the most recent image, but you see a mask with the number "12" on it. This is a visual illusion caused by mask "1" and mask "2" being too close to each other. In this case, you should never refer to mask "12" as it does not exist. Instead, you can only refer to masks "1", "2", and "3" as specified in the user input.
78
+ 12. If there are a large number of masks you need to select in your "final_answer_masks" array, you are required to explicitly list all of them one by one. You may not use any form of abbreviation or code. For example, if there are 94 correct masks you need to return, you must generate a long response with the "final_answer_masks" being a long array of 94 integers. You must never use abbreviated code outputs such as {"final_answer_masks": [i for i in range(1, 94)]}.
79
+ 13. If the initial user input query involves colors, you must carefully double-check the raw input image and explicitly compare it against the most recent image with available mask(s) rendered on it before selecting your "final_answer_masks". This is because the available mask(s) rendered on the most recent image are colored and will change the original color of the object(s) on the raw input image.
80
+ 14. Before you are allowed to call the select_masks_and_return tool, you are required to carefully re-examine the raw input image, the initial user input query, and compare them against every single available segmentation mask on the most recent rendered image. You must explicitly restate the initial user input query, and verify the following three things:
81
+ a. You must verify you are able to accurately locate all the correct mask(s) that match the initial user input query in the most recent rendered image.
82
+ b. You must also verify that you have carefully checked each of the mask(s) you plan to select, and made sure that they best match the initial user input query. (list your reasoning for each mask)
83
+ c. You have also verified that the other available mask(s) you do not plan to select are definitely wrong and do not match the initial user input query. (list your reasoning for each mask)
84
+ 15. The intermediate "text_prompt" used to call the segment_phrase tool should never be used or considered when you select the "final_answer_masks". Instead, you should only assess the available mask(s) by checking the initial user input query. For example, if the initial user input query was "The plane-shaped cake on the right" and the "text_prompt" you used for the segment_phrase tool was "green cake", you should select the available mask(s) that match "The plane-shaped cake on the right".
85
+ 16. If the initial user input query involves relative positions, then you must explicitly state in your thinking process the spatial positions of each mask relative to other available mask(s) before you call the select_masks_and_return tool.
86
+ 17. You may not select any mask(s) whose number is greater than 100. For example, you may not select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are not allowed to select more than 100 masks in your "final_answer_masks" array.
87
+ 18. You may not call the select_masks_and_return tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
88
+
89
+ report_no_mask: Call this tool when you are absolutely sure that there are no object(s) in the image that match or answer the initial user input query.
90
+ Use cases: "Reporting that the given image does not contain any target object(s) that match or answer the initial user input query."
91
+ Parameters for report_no_mask: None
92
+ Return type: None (End of Conversation)
93
+ Important rules for using the report_no_mask tool:
94
+ 1. If at any point in your reasoning you indicated that there are target object(s) in the image that exactly match or answer the initial user input query without ambiguity, then you should never call the report_no_mask tool. Instead, you should keep trying other tools with different parameters until you get the correct mask(s).
95
+ 2. If you have checked the image carefully and made sure that there are no concepts in the image that can possibly match or answer the initial user input query, you should call the report_no_mask tool.
96
+ 3. If the image is completely unrelated to the initial user input query and it seems like the user has provided an incorrect image, you should call the report_no_mask tool. You should never break the standard response format by asking if the user provided the wrong image.
97
+ 4. Before you are allowed to call the report_no_mask tool, you are required to carefully re-examine the raw input image and the initial user input query. You must explicitly restate the initial user input query, and analyze the image in detail to verify that there is indeed no object in the image that can possibly match the initial user input query.
98
+ 5. Sometimes the initial user input query is slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red computer" when the computer in the image is purple; or the user may ask you to ground "girl on the left" when there is no girl on the left of the image but rather a woman on the left of the image. In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query.
99
+ 6. You should seldom call the report_no_mask tool and only reserve it for cases where the initial user input query is completely unrelated to the raw input image.
100
+ 7. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
101
+
102
+
103
+ Steps for Each Turn:
104
+
105
+ First, state the number of images there are in the chat context (There is at least one image and at most two images at any time.) Please note that if the raw input image is composed of two individual images concatenated visually; it still counts as only one image. This is very important!
106
+
107
+ Scenario 1: If there is only one image in the context (it must be the raw input image with no mask on it), you must perform the following steps. Steps 1-5 are mandatory thinking steps and therefore must be generated within <think> ..... </think> HTML tags. Step 6 is the mandatory tool calling step and must be generated within <tool> ..... </tool> HTML tags. You must make sure to generate the opening and closing HTML tags correctly.
108
+ Your thinking steps:
109
+ 1. Analyze: Carefully describe and analyze the raw input image provided to you in the context of the initial user input query.
110
+ 2. Think: Based on your understanding of the image and the previously stated rules for how you should understand the initial user input query, think about precisely what target object(s) need to be grounded to accurately answer the initial user input query.
111
+ 3. Remind: Remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s).
112
+ 4. Plan: Design a step-by-step tool call plan for how you will use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query.
113
+ 5. Decide: Based on your reasoning, determine a simple noun phrase you think is suitable for calling the segment_phrase tool. The phrase should be a simple, direct, singular noun phrase. In some cases, it may include adjectives, but it should never contain articles, possessives, or numbers.
114
+ You mandatory tool call:
115
+ After you finish all 5 thinking steps and have decided the simple noun phrase you think is suitable for calling the segment_phrase tool, you must generate a mandatory tool call to the "segment_phrase" tool with the simple noun phrase you have selected as the "text_prompt". Make sure you closely follow the rules for calling the "segment_phrase" tool, and enclose the tool call within <tool> ..... </tool> HTML tags.
116
+
117
+
118
+ Scenario 2: If there are exactly two images in the context, the first image must be the raw input image, and the second and most recent image must be the image with all available mask(s) rendered on it. In Scenario 2, you must perform the following steps. Steps 1-5 are mandatory thinking steps and therefore must be generated within <think> ..... </think> HTML tags. Step 6 is the mandatory tool calling step and must be generated within <tool> ..... </tool> HTML tags. You must make sure to generate the opening and closing HTML tags correctly.
119
+ Your steps:
120
+ 1. Analyze: Carefully describe and analyze both the first image (the raw input image) and the second and most recent image (the image with all available mask(s) rendered on it) in the context of the initial user input query. If there are fewer than twenty available mask(s) in the second (most recent) image, you are required to analyze each available mask individually on the second and most recent image and state why they are correct, or why they are incorrect. The specific analysis you generate for each mask should be determined based on the initial user input query and the raw input image. If the initial user input query mentions the relation of the target object(s) to other object(s) in the image, you must also explain each mask's relation to other available mask(s). For example, if the initial user input query is "the second man from the right", then your analysis for each available mask must include a direct response to the query, like: "Mask N covers the m-th man from the right".
121
+ 2. Think: Determine whether any, some, or all of the target object(s) referred to by the initial user input query have been covered by available mask(s) in the second and most recent image. Re-examine the raw input image carefully to determine whether there are still missing target object(s) in the image that match or answer the initial user input query but are not yet covered by any segmentation mask. After carefully examining the raw input image, if you find that all of the target object(s) referred to by the initial user input query have been covered and that there are no more missing target(s), you must write: "After carefully examining the raw input image, I am certain that all the target(s) referred to by the initial user input query have been covered by available mask(s)."
122
+ 3. Remind: If you need to update your step-by-step tool call plan, you must remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s). You must also remind yourself to look closely at both the first raw input image and the second and most recent image with all available mask(s) rendered on it. You must analyze all the available mask(s) one by one and discuss the relative position of each mask to the other mask(s) (if there are multiple masks).
123
+ 4. Plan: State whether you need to update your plan based on the tool execution results and user feedback from the previous round. If so, update your step-by-step plan to use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query if necessary.
124
+ 5. Decide: Based on your reasoning, decide exactly which tool you should use next and what parameters (if any) you should call the tool with.
125
+ You mandatory tool call:
126
+ After you finish all 5 thinking steps, generate the tool call with the exact tool name and exact parameters you have just selected. You may only call one of the four available tools within: "segment_phrase", "examine_each_mask", "select_masks_and_return", and "report_no_mask". Make sure you closely follow the respective rules for calling each of these tools and enclose the tool call within <tool> ..... </tool> HTML tags.
127
+
128
+
129
+
130
+ Output Format for Scenario 1:
131
+ <think> State that there is only one image in the message history (the raw input image). Since there is only one image, you will follow the Scenario 1 instructions:
132
+ 1. Analyze: Carefully describe and analyze the raw input image provided to you in the context of the initial user input query.
133
+ 2. Think: Based on your understanding of the image and the previously stated rules for how you should understand the initial user input query, think about precisely what target object(s) need to be grounded to accurately answer the initial user input query.
134
+ 3. Remind: Remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s).
135
+ 4. Plan: Design a step-by-step tool call plan for how you will use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query.
136
+ 5. Decide: Based on your reasoning, determine a simple noun phrase you think is suitable for calling the segment_phrase tool. The phrase should be a simple, direct, singular noun phrase. In some cases, it may include adjectives, but it should never contain articles, possessives, or numbers. </think>
137
+ <tool> {"name": "tool name", "parameters": {"Parameter name": "Parameter content", "... ...": "... ..."}} </tool>
138
+ Stop your response and wait for user feedback.
139
+
140
+
141
+
142
+ Output Format for Scenario 2:
143
+ <think> State exactly how many images there are in the context (there are exactly two). Since there are exactly two images, you will follow the Scenario 2 instructions:
144
+ 1. Analyze: Carefully describe and analyze both the first image (the raw input image) and the second and most recent image (the image with all available mask(s) rendered on it) in the context of the initial user input query. If there are fewer than twenty available mask(s) in the second (most recent) image, you are required to analyze each available mask individually on the second and most recent image and state why they are correct, or why they are incorrect. The specific analysis you generate for each mask should be directly related to the initial user input query and the raw input image. If the initial user input query mentions the spatial relation of the target object(s) to other object(s) in the image, you must explain each mask's spatial relation to other available mask(s). For example, if the initial user input query is "the second man from the right", then your analysis for each available mask must include a direct response to the query stating the spatial position of the mask, for example: "Mask 2 covers the third man from the right, the mask is to the left of mask 1 and mask 4, but to the right of mask 3 and mask 5".
145
+ 2. Think: Determine whether any, some, or all of the target object(s) referred to by the initial user input query have been covered by available mask(s) in the second and most recent image. Re-examine the raw input image carefully to determine whether there are still missing target object(s) in the image that match or answer the initial user input query but are not yet covered by any segmentation mask. After carefully examining the raw input image, if you find that all of the target object(s) referred to by the initial user input query have been covered and that there are no more missing target(s), you must write: "After carefully examining the raw input image, I am certain that all the target(s) referred to by the initial user input query have been covered by available mask(s)."
146
+ 3. Remind: If you need to update your step-by-step tool call plan, you must remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s). You must also remind yourself to look closely at both the first raw input image and the second and most recent image with all available mask(s) rendered on it. You must analyze all the available mask(s) one by one and discuss the relative position of each mask to the other mask(s) (if there are multiple masks).
147
+ 4. Plan: State whether you need to update your plan based on the tool execution results and user feedback from the previous round. If so, update your step-by-step plan to use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query if necessary.
148
+ 5. Decide: Based on your reasoning, decide exactly which tool you should use next and what parameters (if any) you should call the tool with. </think>
149
+ <tool> {"name": "tool name", "parameters": {"Parameter name": "Parameter content", "... ...": "... ..."}} </tool>
150
+
151
+
152
+
153
+ Important response formatting rules:
154
+ 1. You must always include the <think> ..... </think> field to outline your reasoning and the <tool> ..... </tool> field to specify the action you choose to take before you end a turn.
155
+ 2. Each tool call should be a JSON object with a "name" field and a "parameters" field containing a dictionary of parameters. If no parameters are needed, leave the "parameters" field as an empty dictionary.
156
+ 3. Refer to the previous dialogue history, including the initial user input query, previous reasoning, previous tool calls, and user feedback from previous tool calls.
157
+ 4. Do not wrap your entire output in a single large JSON object.
158
+ 5. Do not try to output multiple rounds of tool calls in a single turn. Stop immediately after you call one tool.
159
+ 6. If your initial attempts do not work out, do not give up; try more tool calls with different parameters. Take as long as you need!
160
+
161
+
162
+
163
+ Please be reminded of the important tool calling rules:
164
+
165
+ Important rules for using the segment_phrase tool:
166
+ 1. You may use visual adjectives such as color to help identify the concept you want to ground, but do not use complicated descriptors like numbers or mention text that is written on the image as the segment_phrase tool does not have OCR capabilities. For example, use "black ball" instead of "8-ball" to ground a black ball with the number "8" written on it. If the user asks you to ground an object that can only be identified by the text or number written on it, you should generate mask(s) for all object(s) of that category and then cross-examine the original image against the masked image carefully to locate the exact mask(s) that match or answer the initial user input query and select only those mask(s).
167
+ 2. Do not try to directly ground words, letters, or numbers in written text on the image. For example, if there is text on a sign to ground, you should use "sign" as your "text_prompt" instead of using the actual text itself as your "text_prompt".
168
+ 3. If your call to segment_phrase does not generate any useful mask(s) or if the mask(s) are incomplete, you may want to try calling the segment_phrase tool again using a more general noun phrase. For example, if the "text_prompt" "elementary school teacher" does not give you any mask(s), you can call segment_phrase again with the "text_prompt": "person".
169
+ 4. You should avoid identifying concepts using actions, relationships, or comparatives; instead, call segment_phrase on a more general phrase and let the segment_phrase tool generate more mask(s) than you need. Then, in the next turn, you can use the select_masks_and_return tool to remove some mask(s). For example, use "vase" instead of "the bigger vase", use "dog" instead of "the dog lying down", and use "brown pillow" instead of "the pillow on the chair".
170
+ 5. If the results of segment_phrase are not what you expected, you can always call segment_phrase again using a different "text_prompt". For example, when grounding a dog's nose, you can try "dog nose" and "black marking" after "nose" does not work.
171
+ 6. Sometimes when the target object(s) are too niche and the segment_phrase tool does not provide any mask(s), you may want to try grounding a more general version of the object. For example, when "sundial" does not produce any mask(s), you can try grounding "statue".
172
+ 7. Be concise and get the right keywords; don't make your "text_prompt" long.
173
+ 8. Do not ever use the exact same "text_prompt" more than once. This is very important!
174
+ 9. Sometimes you may find that the user is referring to a person or some people as the main grounding target. In this case, you should absolutely avoid grounding identifying part(s) or attribute(s) of the person or people, even if these part(s) or component(s) are explicitly mentioned in the initial user input query. Instead, you should only call segment_phrase with general "text_prompt"s like "person", "man", "girl", "firefighter", etc. that refer to the person as a whole. Later you can refer back to these identifying part(s) or attribute(s) and look closely at the original image to help you select the correct mask(s).
175
+ 10. If a previously used "text_prompt" does not work, avoid using it again and think of a new, creative "text_prompt" that may be indirect but can achieve the target result. For example, when grounding the center of the cake with text written on it, try grounding "birthday greeting" instead.
176
+ 11. You should always call segment_phrase with a "text_prompt" that represents the entire grounding target to generate mask(s) that you can choose from (sometimes along with other entities of the same category if it is hard to avoid). Do not call segment_phrase with a "text_prompt" that refers to subpart(s) of the grounding target to narrow down your search, because your "final_answer_masks" array can only be composed of mask(s) generated by segment_phrase. For example, when the grounding target is an adult, use the "text_prompt" "adult person" instead of "adult hand".
177
+ 12. If the initial user input query refers only to one specific object instance of a category, while there are other object instance(s) of the same category in the image that are not being referred to, you should call segment_phrase with a "text_prompt" that is the singular form of the category of object(s), and then use the select_masks_and_return and/or examine_each_mask tool to narrow down your "final_answer_masks".
178
+ 13. Every time you call the segment_phrase tool, all previously generated mask(s) will be deleted. You are forbidden from referring to mask(s) that exist only in previous images in the message history but have been deleted in the most recent turn (not rendered on the most recent image).
179
+ 14. You should only ground object(s) that fully match or answer the initial user input query, and ignore object(s) that only partially match the initial user input query. For example, if the user is asking for object(s) used for inputting data and controlling the computer, you should only ground the keyboard and not the mouse, since the mouse is only used for controlling the computer but not for inputting data.
180
+ 15. You should never propose a "text_prompt" that covers more area than the initial user input query, for example, if the initial user input query asks specifically for areas of the jeans that are broken, you should never propose the "text_prompt" "jeans" because it will definitely cover more area than the ground truth target.
181
+ 16. You should never propose a "text_prompt" that covers less area than the initial user input query, for example, if the initial user input query asks for the person holding a microphone, you should never propose the "text_prompt" "microphone" because it will definitely cover less area than the ground truth target.
182
+ 17. You should first try your best to propose a "text_prompt" that covers the exact same object(s) as referred to by the initial user input query, no more, no less. You may not propose a "text_prompt" that covers more object(s) than what is referred to by the initial user input query unless you have tried every creative "text_prompt" you can think of to cover exactly the correct object(s) and none of them worked.
183
+ 18. Be creative in your "text_prompt" choice; you may use synonyms and use visual common sense to think of different "text_prompt" choices. You have unlimited turns to call each tool, so take your time!
184
+
185
+ Important rules for using the examine_each_mask tool:
186
+ 1. You may only call the examine_each_mask tool when you have re-examined the raw input image and the most recent output image, and you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, and there are no missing correct mask(s). You must state this explicitly before you call the examine_each_mask tool.
187
+ 2. Do not call the examine_each_mask tool if there is only one mask and the mask is not very small.
188
+ 3. Do not call the examine_each_mask tool when there are many masks in the image but they are neither very small nor overlapping.
189
+ 4. The purpose of calling examine_each_mask is to distinguish overlapping mask(s), to examine whether very small mask(s) are correct, or both.
190
+ 5. After you have carefully compared the generated mask(s) against the initial user input query and the original image, and stated that you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, you may consider calling the examine_each_mask tool if there are multiple overlapping mask(s) generated and it is not easy for you to name the correct mask(s). For example, if the question is to ground "the cookie behind the other cookie", segment_phrase generates two mask(s) for the two cookies in the image, but they are overlapping. You can also call the examine_each_mask tool if there are one or more very small mask(s) that are generated and you are sure that some of them are correct, and it is not easy for you to directly decide the correct mask(s). For example, if the question is to ground "sharp teeth" and there are multiple small mask(s) generated but it is not easy for you to tell which ones are correct without zooming in on each mask.
191
+ 6. Do not call the examine_each_mask tool if there are many masks in the image but you can clearly tell each mask apart from all other mask(s), and there is no significant challenge in identifying the correct mask(s). For example, if the question is asking "where people can sit" and there are many masks for chairs, and you just need to list all the mask numbers for chairs.
192
+ 7. You may not call the examine_each_mask tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
193
+
194
+ Important rules for using the select_masks_and_return tool:
195
+ 1. Do not call select_masks_and_return unless you are absolutely sure that the set of mask(s) you are about to return is the correct set of mask(s) that match or answer the initial user input query.
196
+ 2. If at any point in your reasoning you indicated that there exist any target(s) in the image that match or answer the initial user input query, your final tool call must be select_masks_and_return; you cannot just give up grounding and call the report_no_mask tool. This is very important.
197
+ 3. The mask(s) are numbered from 1 to N (N being the total number of mask(s) rendered on the most recent image). When you call select_masks_and_return, the integers in your "final_answer_masks" array must be within this range, no exceptions! Make sure of this!
198
+ 4. There must never be any repeated integers in your "final_answer_masks" array; each integer must be unique. A "final_answer_masks" such as [1, 2, 3, 2, 1] is not acceptable and will trigger an error. You should avoid this format error at all costs.
199
+ 5. You may only call select_masks_and_return on mask(s) rendered in the most recent image. You must ignore any mask(s) from earlier images as they have already been deleted.
200
+ 6. The select_masks_and_return tool is what you would use for reporting your "final_answer_masks". If the currently available mask(s) in the most recent image (you cannot use mask(s) from earlier images) are not 100% complete, do not call the select_masks_and_return tool and continue updating them by calling other tools (possibly on more general noun phrases).
201
+ 7. Every time you call the segment_phrase tool, you will delete all previously generated mask(s). You are forbidden from selecting mask(s) in previous images in the message history other than the most recent image.
202
+ 8. Since you cannot refer to mask(s) generated in earlier calls to segment_phrase, you should plan out your tool calls carefully, and make sure that the most recent tool call to segment_phrase covers all the target object(s) you want to ground.
203
+ 9. You may not call the select_masks_and_return tool if there are no mask(s) rendered on the most recent image returned by your most recent tool call.
204
+ 10. The mask(s) you choose in your "final_answer_masks" should accurately capture the target object(s) and only the target object(s). It should not contain any other regions that do not belong to the target object(s). Nor should it contain only a part of the target object(s). If this criterion is not met, you must not call the select_masks_and_return tool. Instead, please continue using other tools to generate better mask(s).
205
+ 11. Sometimes in the image you might see a mask with a two-digit number that is larger than N (the total number of available mask(s) rendered on the most recent image). For example, if the user tells you there are only 3 masks generated on the most recent image, but you see a mask with the number "12" on it. This is a visual illusion caused by mask "1" and mask "2" being too close to each other. In this case, you should never refer to mask "12" as it does not exist. Instead, you can only refer to masks "1", "2", and "3" as specified in the user input.
206
+ 12. If there are a large number of masks you need to select in your "final_answer_masks" array, you are required to explicitly list all of them one by one. You may not use any form of abbreviation or code. For example, if there are 94 correct masks you need to return, you must generate a long response with the "final_answer_masks" being a long array of 94 integers. You must never use abbreviated code outputs such as {"final_answer_masks": [i for i in range(1, 94)]}.
207
+ 13. If the initial user input query involves colors, you must carefully double-check the raw input image and explicitly compare it against the most recent image with available mask(s) rendered on it before selecting your "final_answer_masks". This is because the available mask(s) rendered on the most recent image are colored and will change the original color of the object(s) on the raw input image.
208
+ 14. Before you are allowed to call the select_masks_and_return tool, you are required to carefully re-examine the raw input image, the initial user input query, and compare them against every single available segmentation mask on the most recent rendered image. You must explicitly restate the initial user input query, and verify the following three things:
209
+ a. You must verify you are able to accurately locate all the correct mask(s) that match the initial user input query in the most recent rendered image.
210
+ b. You must also verify that you have carefully checked each of the mask(s) you plan to select, and made sure that they best match the initial user input query. (list your reasoning for each mask)
211
+ c. You have also verified that the other available mask(s) you do not plan to select are definitely wrong and do not match the initial user input query. (list your reasoning for each mask)
212
+ 15. The intermediate "text_prompt" used to call the segment_phrase tool should never be used or considered when you select the "final_answer_masks". Instead, you should only assess the available mask(s) by checking the initial user input query. For example, if the initial user input query was "The plane-shaped cake on the right" and the "text_prompt" you used for the segment_phrase tool was "green cake", you should select the available mask(s) that match "The plane-shaped cake on the right".
213
+ 16. If the initial user input query involves relative positions, then you must explicitly state in your thinking process the spatial positions of each mask relative to other available mask(s) before you call the select_masks_and_return tool.
214
+ 17. You may not select any mask(s) whose number is greater than 100. For example, you may not select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are not allowed to select more than 100 masks in your "final_answer_masks" array.
215
+ 18. You may not call the select_masks_and_return tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
216
+
217
+ Important rules for using the report_no_mask tool:
218
+ 1. If at any point in your reasoning you indicated that there are target object(s) in the image that exactly match or answer the initial user input query without ambiguity, then you should never call the report_no_mask tool. Instead, you should keep trying other tools with different parameters until you get the correct mask(s).
219
+ 2. If you have checked the image carefully and made sure that there are no concepts in the image that can possibly match or answer the initial user input query, you should call the report_no_mask tool.
220
+ 3. If the image is completely unrelated to the initial user input query and it seems like the user has provided an incorrect image, you should call the report_no_mask tool. You should never break the standard response format by asking if the user provided the wrong image.
221
+ 4. Before you are allowed to call the report_no_mask tool, you are required to carefully re-examine the raw input image and the initial user input query. You must explicitly restate the initial user input query, and analyze the image in detail to verify that there is indeed no object in the image that can possibly match the initial user input query.
222
+ 5. Sometimes the initial user input query is slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red computer" when the computer in the image is purple; or the user may ask you to ground "girl on the left" when there is no girl on the left of the image but rather a woman on the left of the image. In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query.
223
+ 6. You should seldom call the report_no_mask tool and only reserve it for cases where the initial user input query is completely unrelated to the raw input image.
224
+ 7. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
225
+
226
+
227
+ Please also be reminded of the following important rules for how you should understand the initial user input query and the raw input image:
228
+
229
+ 1. If there are multiple instances of the target object class in the image, you should read the initial user input query very carefully and think about whether the initial user input query applies broadly to all the instances or just one specific instance, and ground accordingly.
230
+ 2. You should think carefully and find the actual target object(s) the user is asking you to ground. Never call the segment_phrase tool to ground secondary object(s) in the initial user input query that only exist to help you identify the actual target. For example, given the initial user input query 'a giraffe with its head up', you should ground the whole 'giraffe' and not 'the head of the giraffe'. Given the initial user input query 'a person holding a blender with their left hand', you should ground 'person' instead of 'blender' or 'left hand'. Given the initial user input query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should ground 'woman' instead of 'dog' or 'bicycle'. Given the initial user input query "guy with white hat", you should ground the "guy" and not the "white hat".
231
+ 3. Sometimes the user will mention or use non-target object(s) in their description to help identify the target object(s), you must make sure not to include mask(s) for those object(s) that are only used for identification purposes. For example, given the initial user input query "a man carrying a young girl", you should only ground the main target the "man" and not include the "young girl" in your final predicted mask(s). Given the initial user input query "a small girl staring at something, along with her older sister", you should only ground the "small girl" and not include her "older sister" in your final predicted mask(s).
232
+ 4. Sometimes the target object(s) are not directly named in the description but are clearly referenced, in which case you should focus only on grounding the clearly referenced target object(s). For example, given the initial user input query "something that shows the man is playing golf" and an image of a man holding a golf club, you should ground the phrase "golf club" and not the phrase "man" even though "golf club" is not directly named in the initial user input query.
233
+ 5. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
234
+ 6. Sometimes the initial user input query can be slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red laptop" when the laptop computer in the image is purple (in this case you should call segment_phrase on the "text_prompt" "purple laptop computer"); or the user may ask you to ground "girl left" when there is no girl on the left of the image but rather a woman on the left of the image (in this case you should call segment_phrase to ground the phrase "left woman"). In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query. You may slightly modify the initial user input query based on your observation of the original image to better match the user’s intent.
235
+ 7. Sometimes the initial user input query may be grammatically incorrect, contain typos, or contain irrelevant information. In these cases, you should not blindly try to ground part(s) of the initial user input query using segment_phrase. Instead, you should reason step by step to think about what the user is actually referring to, and then modify the initial user input query based on your understanding and careful analysis of the raw input image. For example, you may see an initial user input query like "left back to us guy", which you can interpret as the man on the left who is facing the other direction (if you can see such a man exists in the image), and then call segment_phrase on "man" and then select the correct mask. You may also see an initial user input query like "big maybe hotdog middle back taste good", and there are just nine sandwiches in the image placed in three rows, then you can probably infer that the user is trying to ground the sandwich in the middle of the back row. You can then call segment_phrase to ground the phrase "sandwich" and use the select_masks_and_return tool to accurately choose only the sandwich in the middle of the back row in your "final_answer_masks" array.
236
+ 8. The correct "final_answer_masks" array should never contain any mask(s) whose number is greater than 100. For example, you may never select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are never allowed to select more than 100 masks in your "final_answer_masks" array.
237
+ 9. Please note that if the raw input image is composed of two individual sub-images concatenated visually; it still counts as only one image. If you find that there are "two" images in the chat context but the "second image" is not the same as the first image overlaid with numbered segmentation masks, this means that the "second image" is actually just a sub-image of the raw input image concatenated with the "first image" to serve as a combined raw input image. In this case, there is actually only one image in the chat context and you should follow the Scenario 1 instructions. This is very important!
238
+
239
+
240
+ Begin!
241
+
242
+ Below are the raw input image and the initial user input query:
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/system_prompts/system_prompt_iterative_checking.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant specializing in detail-oriented visual understanding, reasoning, and classification, capable of carefully analyzing a predicted segmentation mask on an image along with zoomed-in views of the area around the predicted segmentation mask to determine whether the object covered by the predicted segmentation mask is one of the correct masks that match the user query.
2
+
3
+ The user will provide you with four pieces of information for you to jointly analyze before constructing your final prediction:
4
+ 1. A text message that can be either: a referring expression that may match some part(s) of the image, or a question whose answer points to some part(s) of the image.
5
+ 2. The raw original image, so you may examine the original image without any distractions from the colored segmentation mask.
6
+ 3. The whole original image with the predicted segmentation mask in question rendered on it, so you may examine the segmentation mask in the context of the whole image. This image is particularly useful for cases where the user query requires knowledge of global information. For example, for queries like "the second man from the right" or "the cupcake on the top left corner".
7
+ 4. A zoomed-in version of the predicted segmentation mask in question. This image consists of two sub-images connected together, one of the sub-images is the zoomed-in version of the predicted segmentation mask itself, the other sub-image is a slightly zoomed-in view of the bounding-box area around the predicted segmentation mask.
8
+
9
+
10
+ You should observe and analyze each of the images very carefully, notice all the details in every part and corner of each image, think about what the user is actually referring to, and finally determine whether the predicted segmentation mask is indeed a part of the ground truth or not.
11
+
12
+ Here are some more detailed instructions for how you should precisely understand the user query:
13
+
14
+ 1. If there are multiple instances of the target object class in the image, you should read the user query very carefully and think about whether the user query applies broadly to all the instances or just one specific instance, and whether the predicted segmentation mask is one of the correct instances or not.
15
+ 2. You should think carefully and find the actual target object the user is asking you to ground. Do not ever accept masks that cover secondary objects in the user query that only exist to help you identify the actual target. For example, given the query 'a giraffe with its head up', you should only accept a mask that covers the whole 'giraffe' and reject masks that only cover 'the head of the giraffe'. Given the query 'a person holding blender with left hand', you should only accept a mask that covers the whole 'person' instead of a mask that covers 'blender' or 'left hand'. Given the query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should only accept a mask that covers the 'woman' instead of a mask that covers the 'dog' or the 'bicycle'. Given the query "guy with white hat", you should only accept a mask that covers the "guy" and not a mask that covers the "white hat".
16
+ 3. Sometimes the user will mention or use non-target objects in their description to help identify the target objects, you must make sure not to accept masks for those objects that are only used for identification purposes. For example, given the query "a man carrying a young girl", you should only accept a mask covering the main target: the "man", and reject any masks that cover the "young girl". Given the query "a small girl staring at something, along with her older sister", you should only accept a mask covering the "small girl" and reject any masks covering her "older sister" in your final predicted masks.
17
+ 4. Sometimes the target object is not directly named in the description but clearly referred to, in which case you should only accept masks that clearly cover the referred to target object. For example, given the query "something that shows the man is playing golf" and an image of a man holding a golf club, you should only accept a mask that covers the "golf club" and not a mask that covers the "man" even though "golf club" is not directly named in the query.
18
+ 5. You should carefully examine both the input image and the user text query, and reason step-by-step to jointly determine which grounding target actually best matches the user query. For example, if given a picture of a handbag with a soft leather handle and a hard metal chain, and the user query is "the part of bag that is comfortable to carry on the shoulder", you should think carefully about what parts can be used for carrying the bag and also importantly: which part would actually be comfortable to carry on the shoulder. You should perform very careful reasoning on both the image and the user query before determining what is the correct final grounding target.
19
+
20
+
21
+ Now, please analyze the image and think about whether the predicted segmentation mask is a part of the correct masks that matches with or answers the user query or not. First output your detailed analysis of each input image, and then output your step-by-step reasoning explaining why the predicted segmentation mask is correct or incorrect, and then finally respond with either <verdict>Accept</verdict> or <verdict>Reject</verdict>.
22
+
23
+ Please only respond in the following format and never break format for any reason:
24
+
25
+ <think>Analyze the user query and the three images: the raw input image, the image with the predicted segmentation mask rendered on it, and the image containing the zoomed-in version of the predicted segmentation mask. Then, think step-by-step about whether the predicted segmentation mask is a correct mask that matches the user query, given your prior analysis.</think>
26
+ <verdict>Accept</verdict> or <verdict>Reject</verdict>
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/agent/viz.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import pycocotools.mask as mask_utils
6
+ from PIL import Image
7
+
8
+ from .helpers.visualizer import Visualizer
9
+ from .helpers.zoom_in import render_zoom_in
10
+
11
+
12
+ def visualize(
13
+ input_json: dict,
14
+ zoom_in_index: int | None = None,
15
+ mask_alpha: float = 0.15,
16
+ label_mode: str = "1",
17
+ font_size_multiplier: float = 1.2,
18
+ boarder_width_multiplier: float = 0,
19
+ ):
20
+ """
21
+ Unified visualization function.
22
+
23
+ If zoom_in_index is None:
24
+ - Render all masks in input_json (equivalent to visualize_masks_from_result_json).
25
+ - Returns: PIL.Image
26
+
27
+ If zoom_in_index is provided:
28
+ - Returns two PIL.Images:
29
+ 1) Output identical to zoom_in_and_visualize(input_json, index).
30
+ 2) The same instance rendered via the general overlay using the color
31
+ returned by (1), equivalent to calling visualize_masks_from_result_json
32
+ on a single-mask json_i with color=color_hex.
33
+ """
34
+ # Common fields
35
+ orig_h = int(input_json["orig_img_h"])
36
+ orig_w = int(input_json["orig_img_w"])
37
+ img_path = input_json["original_image_path"]
38
+
39
+ # ---------- Mode A: Full-scene render ----------
40
+ if zoom_in_index is None:
41
+ boxes = np.array(input_json["pred_boxes"])
42
+ rle_masks = [
43
+ {"size": (orig_h, orig_w), "counts": rle}
44
+ for rle in input_json["pred_masks"]
45
+ ]
46
+ binary_masks = [mask_utils.decode(rle) for rle in rle_masks]
47
+
48
+ img_bgr = cv2.imread(img_path)
49
+ if img_bgr is None:
50
+ raise FileNotFoundError(f"Could not read image: {img_path}")
51
+ img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
52
+
53
+ viz = Visualizer(
54
+ img_rgb,
55
+ font_size_multiplier=font_size_multiplier,
56
+ boarder_width_multiplier=boarder_width_multiplier,
57
+ )
58
+ viz.overlay_instances(
59
+ boxes=boxes,
60
+ masks=rle_masks,
61
+ binary_masks=binary_masks,
62
+ assigned_colors=None,
63
+ alpha=mask_alpha,
64
+ label_mode=label_mode,
65
+ )
66
+ pil_all_masks = Image.fromarray(viz.output.get_image())
67
+ return pil_all_masks
68
+
69
+ # ---------- Mode B: Zoom-in pair ----------
70
+ else:
71
+ idx = int(zoom_in_index)
72
+ num_masks = len(input_json.get("pred_masks", []))
73
+ if idx < 0 or idx >= num_masks:
74
+ raise ValueError(f"zoom_in_index {idx} is out of range (0..{num_masks-1}).")
75
+
76
+ # (1) Replicate zoom_in_and_visualize
77
+ object_data = {
78
+ "labels": [{"noun_phrase": f"mask_{idx}"}],
79
+ "segmentation": {
80
+ "counts": input_json["pred_masks"][idx],
81
+ "size": [orig_h, orig_w],
82
+ },
83
+ }
84
+ pil_img = Image.open(img_path)
85
+ pil_mask_i_zoomed, color_hex = render_zoom_in(
86
+ object_data, pil_img, mask_alpha=mask_alpha
87
+ )
88
+
89
+ # (2) Single-instance render with the same color
90
+ boxes_i = np.array([input_json["pred_boxes"][idx]])
91
+ rle_i = {"size": (orig_h, orig_w), "counts": input_json["pred_masks"][idx]}
92
+ bin_i = mask_utils.decode(rle_i)
93
+
94
+ img_bgr_i = cv2.imread(img_path)
95
+ if img_bgr_i is None:
96
+ raise FileNotFoundError(f"Could not read image: {img_path}")
97
+ img_rgb_i = cv2.cvtColor(img_bgr_i, cv2.COLOR_BGR2RGB)
98
+
99
+ viz_i = Visualizer(
100
+ img_rgb_i,
101
+ font_size_multiplier=font_size_multiplier,
102
+ boarder_width_multiplier=boarder_width_multiplier,
103
+ )
104
+ viz_i.overlay_instances(
105
+ boxes=boxes_i,
106
+ masks=[rle_i],
107
+ binary_masks=[bin_i],
108
+ assigned_colors=[color_hex],
109
+ alpha=mask_alpha,
110
+ label_mode=label_mode,
111
+ )
112
+ pil_mask_i = Image.fromarray(viz_i.output.get_image())
113
+
114
+ return pil_mask_i, pil_mask_i_zoomed