Master-Shi commited on
Commit
fa1f93a
·
verified ·
1 Parent(s): 03853c9

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. HuatuoGPT-Vision-Abla-New/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data.json +0 -0
  2. HuatuoGPT-Vision-Abla-New/run_ablation_grid_layer.sh +120 -0
  3. HuatuoGPT-Vision-Abla-New/run_ablation_grid_worker.sh +116 -0
  4. HuatuoGPT-Vision-Abla-New/run_eval_attnbias_sam_text.sh +41 -0
  5. HuatuoGPT-Vision-Abla-New/train_vl.py +496 -0
  6. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/__init__.py +1 -0
  7. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/agent_core.py +563 -0
  8. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/client_llm.py +205 -0
  9. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/client_sam3.py +138 -0
  10. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/__init__.py +1 -0
  11. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/boxes.py +438 -0
  12. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/keypoints.py +244 -0
  13. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/mask_overlap_removal.py +128 -0
  14. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/masks.py +560 -0
  15. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/rle.py +122 -0
  16. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/roi_align.py +75 -0
  17. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/som_utils.py +406 -0
  18. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/visualizer.py +1662 -0
  19. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/zoom_in.py +195 -0
  20. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/viz.py +114 -0
HuatuoGPT-Vision-Abla-New/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data.json ADDED
The diff for this file is too large to render. See raw diff
 
HuatuoGPT-Vision-Abla-New/run_ablation_grid_layer.sh ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Stage 2 of the two-stage greedy ablation search: run_ablation_grid.sh (+
5
+ # optionally run_ablation_grid_pick.sh) already found the best (s_text, s_vis)
6
+ # with the bias layer fixed at 17, and a first pass already tested
7
+ # LAYERS=(3 10 17 24 27) serially. This script covers the remaining 23 layers
8
+ # (the model has 28 total, indices 0-27, confirmed via
9
+ # PretrainedConfig.get_config_dict(...)['num_hidden_layers'] == 28) by
10
+ # splitting them across GPU 0 and GPU 2 via run_ablation_grid_layer_worker.sh
11
+ # (GPU 1/3 are occupied by other people's jobs on this workstation, so 0/2 are
12
+ # used instead of the usual 0/1), running concurrently -- no cache-warmup step first (see
13
+ # run_ablation_grid_layer_worker.sh's header for why that's safe here: the
14
+ # Pass0 cache should already be fully warm from every prior run in this repo
15
+ # sharing the same data_path/model_path/seed).
16
+ #
17
+ # After both workers finish, this script picks the best layer across ALL 28
18
+ # (the original 5 + these 23), fixed at the same winning (s_text, s_vis), and
19
+ # syncs the final (layer, s_text, s_vis) into every run_eval_attnbias_sam_*.sh.
20
+ #
21
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias is
22
+ # pinned at 0 (amplify_only) and the auction mechanism is OFF for this whole
23
+ # search, matching run_ablation_grid_worker.sh/run_ablation_grid_layer_worker.sh.
24
+ set -e
25
+
26
+ TOTAL=23 # len(LAYERS_REMAINING), see run_ablation_grid_layer_worker.sh
27
+ SPLIT=12 # indices [0, SPLIT) -> GPU 0, indices [SPLIT, TOTAL) -> GPU 2
28
+
29
+ echo "[ablation-grid-layer] launching GPU 0 on layer-indices [0, $SPLIT) and GPU 2 on [$SPLIT, $TOTAL) in parallel (no warmup)"
30
+
31
+ ./run_ablation_grid_layer_worker.sh 0 0 "$SPLIT" > ablation_grid_layer_gpu0.log 2>&1 &
32
+ PID0=$!
33
+ ./run_ablation_grid_layer_worker.sh 2 "$SPLIT" $((TOTAL - SPLIT)) > ablation_grid_layer_gpu2.log 2>&1 &
34
+ PID1=$!
35
+
36
+ echo "[ablation-grid-layer] gpu0 worker pid=$PID0 (log: ablation_grid_layer_gpu0.log), gpu2 worker pid=$PID1 (log: ablation_grid_layer_gpu2.log)"
37
+
38
+ wait "$PID0"
39
+ STATUS0=$?
40
+ wait "$PID1"
41
+ STATUS1=$?
42
+
43
+ if [ "$STATUS0" -ne 0 ] || [ "$STATUS1" -ne 0 ]; then
44
+ echo "[ablation-grid-layer] a worker failed (gpu0 exit=$STATUS0, gpu2 exit=$STATUS1) -- check ablation_grid_layer_gpu{0,2}.log" >&2
45
+ exit 1
46
+ fi
47
+
48
+ echo "[ablation-grid-layer] both workers finished, all $TOTAL remaining layers done"
49
+
50
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
51
+ conda activate huatuovision
52
+
53
+ STAGE1_LAYER=17
54
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
55
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
56
+ # every layer the model has been tested at: the original 5-point sweep plus
57
+ # the 23 "remaining" layers this script just ran.
58
+ LAYERS_ALL=(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)
59
+
60
+ # ── re-derive the winning (s_text, s_vis) directly from the strength grid's
61
+ # result files, same scan-and-compare as run_ablation_grid_pick.sh.
62
+ echo "[ablation-grid-layer] re-scanning the strength grid's results to find the winning (s_text, s_vis)..."
63
+ S_TEXT=""
64
+ S_VIS=""
65
+ STAGE1_BEST_SCORE=""
66
+ for ST in "${STRENGTHS_TEXT[@]}"; do
67
+ for SV in "${STRENGTHS_VIS[@]}"; do
68
+ STAGE1_OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${STAGE1_LAYER}_stext${ST}_svis${SV}"
69
+ STAGE1_RESULT_F=$(ls "$STAGE1_OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
70
+ if [ -z "$STAGE1_RESULT_F" ]; then
71
+ echo "[ablation-grid-layer] missing *_result.json under $STAGE1_OUTPUT_PATH -- has the strength grid finished?" >&2
72
+ exit 1
73
+ fi
74
+ STAGE1_SCORE=$(python -c "
75
+ import json
76
+ with open('$STAGE1_RESULT_F') as f:
77
+ d = json.load(f)
78
+ print(d['The total score for multiple-choice questions'])
79
+ ")
80
+ if [ -z "$STAGE1_BEST_SCORE" ] || python -c "exit(0 if $STAGE1_SCORE > $STAGE1_BEST_SCORE else 1)"; then
81
+ STAGE1_BEST_SCORE="$STAGE1_SCORE"
82
+ S_TEXT="$ST"
83
+ S_VIS="$SV"
84
+ fi
85
+ done
86
+ done
87
+ echo "[ablation-grid-layer] strength winner: s_text=$S_TEXT s_vis=$S_VIS (score=$STAGE1_BEST_SCORE)"
88
+
89
+ # ── pick the best layer across all 28, strength fixed at (S_TEXT, S_VIS).
90
+ BEST_LAYER=""
91
+ BEST_SCORE=""
92
+ for LAYER in "${LAYERS_ALL[@]}"; do
93
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
94
+ RESULT_F=$(ls "$OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
95
+ if [ -z "$RESULT_F" ]; then
96
+ echo "[ablation-grid-layer] missing *_result.json under $OUTPUT_PATH -- cannot pick best layer (layer=$LAYER not yet run)" >&2
97
+ exit 1
98
+ fi
99
+ SCORE=$(python -c "
100
+ import json
101
+ with open('$RESULT_F') as f:
102
+ d = json.load(f)
103
+ print(d['The total score for multiple-choice questions'])
104
+ ")
105
+ echo "[ablation-grid-layer] layer=$LAYER score=$SCORE"
106
+ if [ -z "$BEST_SCORE" ] || python -c "exit(0 if $SCORE > $BEST_SCORE else 1)"; then
107
+ BEST_SCORE="$SCORE"
108
+ BEST_LAYER="$LAYER"
109
+ fi
110
+ done
111
+
112
+ echo "[ablation-grid-layer] best overall across all 28 layers: layer=$BEST_LAYER s_text=$S_TEXT s_vis=$S_VIS (score=$BEST_SCORE)"
113
+ echo "[ablation-grid-layer] syncing into every run_eval_attnbias_sam_*.sh via sync_attn_params.py"
114
+
115
+ python sync_attn_params.py \
116
+ --layers_text "$BEST_LAYER" --key_bias_text "$S_TEXT" --nonkey_bias_text "0" \
117
+ --layers_vis "$BEST_LAYER" --key_bias_vis "$S_VIS" --nonkey_bias_vis "0"
118
+
119
+ echo "[ablation-grid-layer] done. All run_eval_attnbias_sam_*.sh now use the ablation-selected layer/strength (nonkey_bias=0, amplify_only style)"
120
+ echo "[ablation-grid-layer] (amplify_only keeps its pinned-zero side; text.sh/vis.sh keep their single-modality side -- see sync_attn_params.py)."
HuatuoGPT-Vision-Abla-New/run_ablation_grid_worker.sh ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Runs a contiguous slice of the (strength_text, strength_vis) grid on a single
5
+ # GPU, so the full 25-combo sweep can be split across e.g. GPU 0 and GPU 1 and
6
+ # run concurrently. The full pair list is built in the same fixed order
7
+ # (outer S_TEXT, inner S_VIS) as run_ablation_grid_pick.sh expects, so slicing
8
+ # it by [START, START+COUNT) here and picking over the *union* of all slices'
9
+ # output dirs later stays consistent -- this script does NOT do the final
10
+ # "pick best + sync" step, that only makes sense once every slice (on every
11
+ # GPU) has finished; run run_ablation_grid_pick.sh once by hand after all
12
+ # workers exit.
13
+ #
14
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias_text/vis
15
+ # are pinned at 0 (amplify_only -- ablation found boosting key regions without
16
+ # suppressing anything else beats full boost+suppress), AND the auction
17
+ # mechanism is OFF (--auction_enable is not passed) -- every Stage1/SAM-detected
18
+ # key position gets boosted, not just an auction-selected subset. This grid
19
+ # searches under the SAME conditions as the final method (no auction), so the
20
+ # winning strength is actually calibrated for what gets used, not for a
21
+ # different (with-auction) config. Output dirs are tagged
22
+ # "sam_both_amplify_noauction_..." so they don't collide with the earlier
23
+ # auction-enabled grid searches' results.
24
+ #
25
+ # Usage:
26
+ # ./run_ablation_grid_worker.sh <gpu_id> <start_index> <count>
27
+ # Example (25 combos split 13/12 across 2 GPUs -- 2/3 here because GPU 0/1 are
28
+ # occupied by other jobs on this workstation, not the usual 0/1):
29
+ # CUDA_VISIBLE_DEVICES managed internally from <gpu_id> -- don't set it yourself.
30
+ # ./run_ablation_grid_worker.sh 2 0 13 & # combos [0, 13) on GPU 2
31
+ # ./run_ablation_grid_worker.sh 3 13 12 & # combos [13, 25) on GPU 3
32
+ # wait
33
+ # ./run_ablation_grid_pick.sh
34
+ set -e
35
+
36
+ GPU_ID="$1"
37
+ START="$2"
38
+ COUNT="$3"
39
+ if [ -z "$GPU_ID" ] || [ -z "$START" ] || [ -z "$COUNT" ]; then
40
+ echo "usage: $0 <gpu_id> <start_index> <count>" >&2
41
+ exit 1
42
+ fi
43
+ export CUDA_VISIBLE_DEVICES="$GPU_ID"
44
+
45
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
46
+ conda activate huatuovision
47
+
48
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
49
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
50
+
51
+ SEED=42
52
+ MAX_NEW_TOKENS=256
53
+
54
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3/configs/full_lora_config.yaml"
55
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3"
56
+
57
+ INTERVENTION="both"
58
+ LAYER=17
59
+ # must stay identical to run_ablation_grid_pick.sh -- these define the pair
60
+ # ordering/indices that <start_index>/<count> slice into.
61
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
62
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
63
+
64
+ MAX_SAMPLES=""
65
+
66
+ # flatten into "s_text s_vis" pairs, outer S_TEXT / inner S_VIS -- same order
67
+ # run_ablation_grid_pick.sh iterates in, so index N here means the same combo
68
+ # there.
69
+ PAIRS=()
70
+ for S_TEXT in "${STRENGTHS_TEXT[@]}"; do
71
+ for S_VIS in "${STRENGTHS_VIS[@]}"; do
72
+ PAIRS+=("$S_TEXT $S_VIS")
73
+ done
74
+ done
75
+
76
+ TOTAL=${#PAIRS[@]}
77
+ END=$((START + COUNT))
78
+ if [ "$END" -gt "$TOTAL" ]; then
79
+ END="$TOTAL"
80
+ fi
81
+
82
+ echo "[ablation-grid-worker gpu=$GPU_ID] running combos [$START, $END) of $TOTAL total"
83
+
84
+ for ((i = START; i < END; i++)); do
85
+ read -r S_TEXT S_VIS <<< "${PAIRS[$i]}"
86
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
87
+ if [ -d "$OUTPUT_PATH" ]; then
88
+ echo "[ablation-grid-worker gpu=$GPU_ID] $OUTPUT_PATH already exists, skipping s_text=$S_TEXT s_vis=$S_VIS (delete the dir manually to re-run)"
89
+ continue
90
+ fi
91
+
92
+ echo "=================================================="
93
+ echo "[ablation-grid-worker gpu=$GPU_ID] idx=$i layer=$LAYER s_text=$S_TEXT s_vis=$S_VIS -> $OUTPUT_PATH"
94
+ echo "=================================================="
95
+
96
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
97
+ --data_path "$DATA_PATH" \
98
+ --model_path "$MODEL_PATH" \
99
+ --seed "$SEED" \
100
+ --max_new_tokens "$MAX_NEW_TOKENS" \
101
+ --output_path "$OUTPUT_PATH" \
102
+ --intervention "$INTERVENTION" \
103
+ --attn_layers_text "$LAYER" \
104
+ --attn_key_bias_text "$S_TEXT" \
105
+ --attn_nonkey_bias_text "0" \
106
+ --attn_layers_vis "$LAYER" \
107
+ --attn_key_bias_vis "$S_VIS" \
108
+ --attn_nonkey_bias_vis "0" \
109
+ --medsam3_config "$MEDSAM3_CONFIG" \
110
+ --medsam3_dir "$MEDSAM3_DIR" \
111
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
112
+
113
+ echo "[ablation-grid-worker gpu=$GPU_ID] idx=$i s_text=$S_TEXT s_vis=$S_VIS finished"
114
+ done
115
+
116
+ echo "[ablation-grid-worker gpu=$GPU_ID] done with combos [$START, $END)"
HuatuoGPT-Vision-Abla-New/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_text"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ # Modality ablation: text-only. Only the scispaCy keyword text positions get
12
+ # biased (key_bias_text / nonkey_bias_text); the vis side is forced to 0 bias
13
+ # inside _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 is
14
+ # skipped entirely (_needs_sam is False for "text"), so no medsam3_* args.
15
+ # Matches run_eval_attnbias_sam_both.sh's mechanism (amplify-only, auction
16
+ # OFF) so this differs from the final method by exactly one factor (modality
17
+ # restricted to text); compare against run_eval_attnbias_sam_vis.sh and
18
+ # run_eval_attnbias_sam_both.sh.
19
+ INTERVENTION="text"
20
+ ATTN_LAYERS_TEXT=17
21
+ ATTN_KEY_BIAS_TEXT=5.0
22
+ ATTN_NONKEY_BIAS_TEXT=0
23
+ ATTN_LAYERS_VIS="17"
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ # 单卡跑,跟run_eval.sh一样显式锁定卡2。
28
+ export CUDA_VISIBLE_DEVICES=2
29
+
30
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
31
+ --data_path "$DATA_PATH" \
32
+ --model_path "$MODEL_PATH" \
33
+ --seed "$SEED" \
34
+ --max_new_tokens "$MAX_NEW_TOKENS" \
35
+ --output_path "$OUTPUT_PATH" \
36
+ --intervention "$INTERVENTION" \
37
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
38
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
39
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
40
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
41
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla-New/train_vl.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import copy
3
+ import json
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ import random
8
+ import shutil
9
+ from typing import List, Dict, Any
10
+ from dataclasses import dataclass
11
+
12
+ import wandb
13
+ import datasets
14
+ from tqdm import tqdm
15
+ import gc
16
+ from jinja2 import Template
17
+ import torch.nn.functional as F
18
+ import torch.distributed as dist
19
+ from torch.utils.data import Dataset, DataLoader
20
+ from accelerate import Accelerator
21
+ from transformers import (
22
+ Qwen2_5_VLForConditionalGeneration,
23
+ Qwen2_5_VLProcessor,
24
+ set_seed,
25
+ get_cosine_schedule_with_warmup
26
+ )
27
+ from torch.optim.lr_scheduler import LambdaLR
28
+ import math
29
+ from qwen_vl_utils import fetch_image
30
+
31
+ # Set environment variables
32
+ os.environ['WANDB_DISABLE_CODE'] = 'true'
33
+ os.environ["WANDB_API_KEY"] = ''
34
+ os.umask(0)
35
+
36
+ # Set up logging
37
+ logger = logging.getLogger(__name__)
38
+ logging.basicConfig(level='INFO')
39
+
40
+ def get_custom_cosine_schedule_with_warmup(
41
+ optimizer,
42
+ num_warmup_steps,
43
+ num_training_steps,
44
+ min_lr_ratio=0.0,
45
+ num_cycles=0.5
46
+ ):
47
+ """
48
+ Custom cosine scheduler supporting minimum learning rate ratio
49
+ """
50
+ def lr_lambda(current_step):
51
+ if current_step < num_warmup_steps:
52
+ return float(current_step) / float(max(1, num_warmup_steps))
53
+ progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
54
+ cosine_factor = 0.5 * (1.0 + math.cos(math.pi * 2 * num_cycles * progress))
55
+ scaled_factor = (1 - min_lr_ratio) * cosine_factor + min_lr_ratio
56
+ return scaled_factor
57
+
58
+ return LambdaLR(optimizer, lr_lambda, last_epoch=-1)
59
+
60
+ def get_learning_rate(step, initial_lr, num_warmup_steps, num_training_steps, min_lr_ratio, num_cycles=0.5):
61
+ if step < num_warmup_steps:
62
+ return float(step) / float(max(1, num_warmup_steps)) * initial_lr
63
+ progress = float(step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
64
+ cosine_factor = 0.5 * (1.0 + math.cos(math.pi * 2 * num_cycles * progress))
65
+ scaled_factor = (1 - min_lr_ratio) * cosine_factor + min_lr_ratio
66
+ return scaled_factor * initial_lr
67
+
68
+ class TrainingMetrics:
69
+ def __init__(self, device):
70
+ self.n_step = 0
71
+ self.right = torch.Tensor([0]).to(device=device)
72
+ self.total = torch.Tensor([0]).to(device=device)
73
+ self.total_loss = torch.Tensor([0]).to(device=device)
74
+ self.world_size = dist.get_world_size()
75
+
76
+ def __call__(self, logits, labels, loss):
77
+ return self.update(logits, labels, loss)
78
+
79
+ def update(self, logits, labels, loss):
80
+ self.n_step += 1
81
+ with torch.no_grad():
82
+ shift_preds = logits[..., :-1, :].argmax(dim=-1)
83
+ shift_labels = labels[..., 1:]
84
+ self.right += (shift_preds == shift_labels).masked_fill(shift_labels.eq(-100), 0).sum().item()
85
+ self.total += (shift_labels != -100).sum().item()
86
+ self.total_loss += loss.item()
87
+
88
+ def get_metric(self, reset=True):
89
+ dist.all_reduce(self.right, op=torch.distributed.ReduceOp.SUM)
90
+ dist.all_reduce(self.total, op=torch.distributed.ReduceOp.SUM)
91
+ dist.all_reduce(self.total_loss, op=torch.distributed.ReduceOp.SUM)
92
+
93
+ acc = (self.right / self.total).item()
94
+ loss = self.total_loss.item() / (self.world_size * self.n_step)
95
+
96
+ if reset:
97
+ self.n_step = 0
98
+ self.right.fill_(0)
99
+ self.total.fill_(0)
100
+ self.total_loss.fill_(0)
101
+ return acc, loss
102
+
103
+ class SftDataset(Dataset):
104
+ """Pretraining dataset class"""
105
+ def __init__(self, config, processor, accelerator):
106
+ self.config = config
107
+ self.processor = processor
108
+ self.accelerator = accelerator
109
+
110
+ # Load pretraining data (supports multiple sources)
111
+ self.data = []
112
+ with open(config.data_path,'r') as f:
113
+ data = json.load(f)
114
+ self.data = data
115
+
116
+ # Convert conversation format
117
+ role_map = {'system': 'system', 'human': 'user', 'gpt': 'assistant'}
118
+ if 'value' in data[0]['conversations'][0]:
119
+ for da in data:
120
+ conv = []
121
+ for x in da['conversations']:
122
+ conv.append({
123
+ 'role': role_map[x['from']],
124
+ 'content': x['value']
125
+ })
126
+ da['conversations'] = conv
127
+
128
+ # Filter long samples and ensure assistant response is valid
129
+ tmp_data = []
130
+ for da in self.data:
131
+ if len(da['image']) > 8:
132
+ continue
133
+ if da['conversations'][-1]['role'] != 'assistant' or len(da['conversations'][-1]['content'].strip()) == 0:
134
+ continue
135
+ tmp_data.append(da)
136
+ self.data = tmp_data
137
+ accelerator.print(f'Training data size: {len(self.data)} samples')
138
+
139
+ self.assistant_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|im_start|>")
140
+ self.assistant_prefix_ids = self.processor.tokenizer.encode("<|im_start|>assistant\n", add_special_tokens=False, return_tensors="pt")[0]
141
+ self.eos_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|im_end|>")
142
+
143
+ self.image_sizes = (config.max_width, config.max_height)
144
+ accelerator.print(f'Total dataset size: {len(self.data)}')
145
+
146
+ # Padding
147
+ self.image_padding = {'pixel_values': torch.zeros(24, 1176), 'image_grid_thw': torch.tensor([[1, 4, 6]])}
148
+
149
+ def __len__(self) -> int:
150
+ return len(self.data)
151
+
152
+ def __getitem__(self, index: int) -> Dict[str, torch.Tensor]:
153
+ return self.data[index]
154
+
155
+ def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
156
+ texts = []
157
+ images = []
158
+
159
+ for item in batch:
160
+ img_num = 0
161
+
162
+ if len(item['image']) > 0 and '<image>' not in ''.join([x['content'] for x in item['conversations']]):
163
+ item["conversations"][0]['content'] = '\n'.join(['<image>']*len(item['image']))+'\n'+item["conversations"][0]['content']
164
+
165
+ if len(item['image']) > 0:
166
+ for k in item["conversations"]:
167
+ img_num += k['content'].count('<image>')
168
+ k['content'] = k['content'].replace("<image>", "<|vision_start|><|image_pad|><|vision_end|>")
169
+ assert img_num == len(item['image']), f"Image count mismatch: {img_num} != {len(item['image'])}\n{item['conversations']}"
170
+ input_text = self.processor.apply_chat_template(item["conversations"], add_generation_prompt=False, tokenize=False)
171
+ texts.append(input_text)
172
+ images.extend(item["image"])
173
+
174
+ img_list = [fetch_image({"type": "image", "image": img_path,"max_pixels": self.image_sizes[0] * self.image_sizes[1]}) for img_path in images]
175
+
176
+ if len(img_list) > 0:
177
+ inputs = self.processor(text=texts, images=img_list, return_tensors="pt", padding=True)
178
+ pixel_values = inputs['pixel_values']
179
+ image_grid_thw = inputs['image_grid_thw']
180
+ assert inputs['input_ids'].shape[0] <= self.config.max_seq_len, f"input_ids length exceeds max_seq_len: {inputs['input_ids'].shape[0]} > {self.config.max_seq_len}, may cause errors!!"
181
+ else:
182
+ inputs = self.processor.tokenizer(text=texts, return_tensors="pt", add_special_tokens=False, truncation=True, padding=True, max_length=self.config.max_seq_len)
183
+ pixel_values = self.image_padding['pixel_values']
184
+ image_grid_thw = self.image_padding['image_grid_thw']
185
+
186
+ labels = torch.full_like(inputs['input_ids'], -100)
187
+ for batch_idx in range(inputs['input_ids'].size(0)):
188
+ input_ids = inputs['input_ids'][batch_idx]
189
+ assistant_indices = (input_ids == self.assistant_token_id).nonzero(as_tuple=True)[0]
190
+
191
+ stop_flag = False
192
+
193
+ for idx in reversed(assistant_indices):
194
+ if not torch.equal(input_ids[idx:idx+len(self.assistant_prefix_ids)], self.assistant_prefix_ids):
195
+ continue
196
+
197
+ for j in range(idx + len(self.assistant_prefix_ids), len(input_ids)):
198
+ labels[batch_idx, j] = input_ids[j]
199
+ if input_ids[j] == self.eos_token_id:
200
+ stop_flag = True
201
+ break
202
+
203
+ if stop_flag:
204
+ break
205
+
206
+ assert inputs['attention_mask'].shape[0] <= self.config.max_seq_len, f"attention_mask length exceeds max_seq_len: {inputs['attention_mask'].shape[0]} > {self.config.max_seq_len}"
207
+
208
+ return {
209
+ "input_ids": inputs['input_ids'][:, :self.config.max_seq_len],
210
+ "labels": labels[:, :self.config.max_seq_len],
211
+ "attention_mask": inputs['attention_mask'][:, :self.config.max_seq_len],
212
+ "pixel_values": pixel_values,
213
+ "image_grid_thw": image_grid_thw
214
+ }
215
+
216
+ def save_checkpoint(
217
+ model,
218
+ processor,
219
+ accelerator: Accelerator,
220
+ args: argparse.Namespace,
221
+ epoch: int,
222
+ step: int,
223
+ global_step: int,
224
+ is_last: bool = False
225
+ ) -> None:
226
+ save_dir = os.path.join(args.output_dir, f"checkpoint-{epoch}-{global_step}")
227
+
228
+ if accelerator.is_main_process:
229
+ # Manage number of checkpoints
230
+ checkpoint_files = [f for f in os.listdir(args.output_dir) if f.startswith("checkpoint-")]
231
+ if args.max_ckpts > 0 and len(checkpoint_files) >= args.max_ckpts:
232
+ oldest_ckpt = min(checkpoint_files, key=lambda x: os.path.getctime(os.path.join(args.output_dir, x)))
233
+ shutil.rmtree(os.path.join(args.output_dir, oldest_ckpt))
234
+
235
+ os.makedirs(save_dir, exist_ok=True)
236
+ output_dir = os.path.join(save_dir, 'tfmr')
237
+
238
+ # Save model and tokenizer
239
+ if accelerator.state.deepspeed_plugin.zero_stage != 3:
240
+ model.save_pretrained(output_dir, state_dict=accelerator.get_state_dict(model))
241
+ processor.save_pretrained(output_dir)
242
+
243
+ logger.info(f'Model saved in {output_dir}')
244
+
245
+ # Handle DeepSpeed stage 3
246
+ if accelerator.state.deepspeed_plugin.zero_stage == 3:
247
+ unwrap_model = accelerator.unwrap_model(model)
248
+ unwrap_model.save_pretrained(
249
+ os.path.join(save_dir, 'tfmr'),
250
+ is_main_process=accelerator.is_main_process,
251
+ save_function=accelerator.save,
252
+ state_dict=accelerator.get_state_dict(model)
253
+ )
254
+
255
+ accelerator.wait_for_everyone()
256
+ logger.info(f'Checkpoint {epoch}-{global_step} saved successfully')
257
+
258
+ if args.save_state:
259
+ try:
260
+ accelerator.save_state(save_dir)
261
+ except Exception as e:
262
+ logger.info(f"Failed to save state: {e}")
263
+
264
+
265
+ def train(args: argparse.Namespace) -> None:
266
+ """Main training function"""
267
+ accelerator = Accelerator(
268
+ mixed_precision='bf16',
269
+ gradient_accumulation_steps=args.gradient_accumulation_steps
270
+ )
271
+
272
+ if accelerator.is_main_process:
273
+ wandb.init(
274
+ project=args.experiment_name,
275
+ name=args.run_name,
276
+ config=args,
277
+ dir=args.log_dir,
278
+ mode="offline"
279
+ )
280
+
281
+ accelerator.state.deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu'] = args.train_bsz_per_gpu
282
+ accelerator.state.deepspeed_plugin.deepspeed_config['train_batch_size'] = (
283
+ args.train_bsz_per_gpu *
284
+ dist.get_world_size() *
285
+ accelerator.gradient_accumulation_steps
286
+ )
287
+
288
+ processor = Qwen2_5_VLProcessor.from_pretrained(args.model_path, trust_remote_code=True)
289
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
290
+ args.model_path,
291
+ trust_remote_code=True,
292
+ attn_implementation='flash_attention_2',
293
+ torch_dtype=torch.bfloat16
294
+ )
295
+
296
+ if args.gradient_checkpointing:
297
+ model.gradient_checkpointing_enable()
298
+
299
+ # Freeze components if required
300
+ if args.freeze_vision_tower:
301
+ logger.info("Freezing vision tower parameters")
302
+ for param in model.visual.parameters():
303
+ param.requires_grad = False
304
+ for param in model.visual.merger.parameters():
305
+ param.requires_grad = True
306
+
307
+ if args.freeze_multi_modal_projector:
308
+ logger.info("Freezing multi-modal projector parameters")
309
+ for param in model.visual.merger.parameters():
310
+ param.requires_grad = False
311
+
312
+ if args.freeze_language_model:
313
+ logger.info("Freezing language model parameters")
314
+ for param in model.model.parameters():
315
+ param.requires_grad = False
316
+
317
+ # Display parameter statistics
318
+ if args.freeze_vision_tower or args.freeze_language_model or args.freeze_multi_modal_projector:
319
+ trainable_params, all_params = 0, 0
320
+ param_status = {}
321
+ for name, param in model.named_parameters():
322
+ all_params += param.numel()
323
+ if param.requires_grad:
324
+ trainable_params += param.numel()
325
+ module_name = name.split('.')[0] if '.' in name else name
326
+ if module_name not in param_status:
327
+ param_status[module_name] = {'trainable': 0, 'frozen': 0}
328
+ param_status[module_name]['trainable'] += param.numel()
329
+ else:
330
+ module_name = name.split('.')[0] if '.' in name else name
331
+ if module_name not in param_status:
332
+ param_status[module_name] = {'trainable': 0, 'frozen': 0}
333
+ param_status[module_name]['frozen'] += param.numel()
334
+
335
+ accelerator.print(f"Total model params: {all_params/1e6:.2f}M, Trainable: {trainable_params/1e6:.2f}M ({trainable_params/all_params*100:.2f}%)")
336
+ accelerator.print("Module-wise parameter status:")
337
+ for module, stats in param_status.items():
338
+ total = stats['trainable'] + stats['frozen']
339
+ if total > 0:
340
+ accelerator.print(f" - {module}: Total {total/1e6:.2f}M, Trainable {stats['trainable']/1e6:.2f}M ({stats['trainable']/total*100:.2f}%), Frozen {stats['frozen']/1e6:.2f}M ({stats['frozen']/total*100:.2f}%)")
341
+
342
+ # Optimizer setup
343
+ no_decay = ["bias", "LayerNorm.weight"]
344
+ optimizer_grouped_parameters = [
345
+ {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay},
346
+ {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
347
+ ]
348
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
349
+
350
+ train_dataset = SftDataset(args, processor, accelerator)
351
+ train_dataloader = DataLoader(
352
+ train_dataset,
353
+ batch_size=args.train_bsz_per_gpu,
354
+ shuffle=True,
355
+ drop_last=True,
356
+ collate_fn=train_dataset.collate_fn,
357
+ num_workers=4
358
+ )
359
+
360
+ num_training_steps = int(len(train_dataloader) * args.n_epochs) // accelerator.gradient_accumulation_steps // dist.get_world_size()
361
+ lr_scheduler = get_custom_cosine_schedule_with_warmup(
362
+ optimizer,
363
+ num_warmup_steps=int(args.warmup_rates * num_training_steps),
364
+ num_training_steps=num_training_steps,
365
+ min_lr_ratio=args.min_lr_ratio
366
+ )
367
+
368
+ model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader)
369
+ metric = TrainingMetrics(device=torch.cuda.current_device())
370
+ model.train()
371
+
372
+ global_step = 0
373
+ inepoch_step = 0
374
+ start_epoch = 0
375
+
376
+ for epoch in range(start_epoch, args.n_epochs):
377
+ train_iter = tqdm(train_dataloader, total=len(train_dataloader)) if accelerator.is_main_process else train_dataloader
378
+
379
+ for batch in train_iter:
380
+ if inepoch_step > 0:
381
+ inepoch_step -= 1
382
+ continue
383
+
384
+ outputs = model(
385
+ input_ids=batch['input_ids'],
386
+ labels=batch['labels'],
387
+ attention_mask=batch['attention_mask'],
388
+ pixel_values=batch['pixel_values'],
389
+ image_grid_thw=batch['image_grid_thw'],
390
+ return_dict=True,
391
+ use_cache=False
392
+ )
393
+ loss = outputs.loss
394
+ metric(outputs.logits, batch['labels'], loss)
395
+
396
+ accelerator.backward(loss)
397
+
398
+ if args.max_grad_norm > 0:
399
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
400
+
401
+ if (global_step + 1) % accelerator.gradient_accumulation_steps == 0:
402
+ optimizer.step()
403
+ lr_scheduler.step()
404
+ optimizer.zero_grad()
405
+
406
+ if (global_step + 1) % (accelerator.gradient_accumulation_steps * 2) == 0:
407
+ torch.cuda.empty_cache()
408
+
409
+ global_step += 1
410
+
411
+ if (global_step + 1) % accelerator.gradient_accumulation_steps == 0:
412
+ acc, train_loss = metric.get_metric()
413
+ if accelerator.is_main_process:
414
+ train_iter.set_postfix(
415
+ epoch=epoch,
416
+ step=global_step - 1,
417
+ total_steps=len(train_dataloader),
418
+ skip=accelerator.optimizer_step_was_skipped,
419
+ length=len(batch["input_ids"][0]),
420
+ loss=f"{train_loss:.3f}",
421
+ acc=f"{acc:.3f}",
422
+ lr=f"{lr_scheduler.get_last_lr()[0]:.2e}"
423
+ )
424
+
425
+ wandb.log({
426
+ 'loss': train_loss,
427
+ 'acc': acc,
428
+ 'lr': lr_scheduler.get_last_lr()[0]
429
+ }, step=global_step)
430
+
431
+ accelerator.wait_for_everyone()
432
+ save_checkpoint(
433
+ model=model,
434
+ processor=processor,
435
+ accelerator=accelerator,
436
+ args=args,
437
+ epoch=epoch,
438
+ step=global_step - 1,
439
+ global_step=global_step,
440
+ is_last=True
441
+ )
442
+
443
+
444
+ if __name__ == '__main__':
445
+ parser = argparse.ArgumentParser(description='Pretraining Configuration')
446
+
447
+ # Experiment
448
+ parser.add_argument('--experiment_name', type=str, help='Experiment name')
449
+ parser.add_argument('--run_name', type=str, default=None, help='Run name')
450
+ parser.add_argument('--model_path', type=str, default='', help='Pretrained model path')
451
+
452
+ # Data
453
+ parser.add_argument('--data_path', type=str, required=True, help='Training data path')
454
+ parser.add_argument('--output_dir', type=str, default='./', help='Model save path')
455
+ parser.add_argument('--max_ckpts', type=int, default=3, help='Max number of checkpoints')
456
+ parser.add_argument('--log_dir', type=str, default='./', help='Log directory')
457
+
458
+ # Training
459
+ parser.add_argument('--max_seq_len', type=int, default=4096, help='Max sequence length')
460
+ parser.add_argument('--gradient_checkpointing', action='store_true', help='Enable gradient checkpointing')
461
+ parser.add_argument('--gradient_accumulation_steps', type=int, default=16, help='Gradient accumulation steps')
462
+ parser.add_argument('--max_grad_norm', type=float, default=1.0, help='Gradient clipping threshold')
463
+ parser.add_argument('--train_bsz_per_gpu', type=int, default=1, help='Batch size per GPU')
464
+ parser.add_argument('--weight_decay', type=float, default=0.1, help='Weight decay')
465
+ parser.add_argument('--learning_rate', type=float, default=5e-6, help='Learning rate')
466
+ parser.add_argument('--min_lr_ratio', type=float, default=0.15, help='Min learning rate ratio')
467
+ parser.add_argument('--warmup_rates', type=float, default=0.05, help='Warmup rate')
468
+ parser.add_argument('--n_epochs', type=int, default=2, help='Number of training epochs')
469
+ parser.add_argument('--save_steps', type=int, default=2000, help='Checkpoint saving interval')
470
+ parser.add_argument('--save_state', action='store_true', help='Save accelerator state')
471
+ parser.add_argument('--resume_from_checkpoint', action='store_true', help='Resume from checkpoint')
472
+
473
+ parser.add_argument('--freeze_vision_tower', action='store_true', help='Freeze vision tower')
474
+ parser.add_argument('--freeze_language_model', action='store_true', help='Freeze language model')
475
+ parser.add_argument('--freeze_multi_modal_projector', action='store_true', help='Freeze multi-modal projector')
476
+
477
+ # Image
478
+ parser.add_argument('--max_width', type=int, default=420, help='Max image width')
479
+ parser.add_argument('--max_height', type=int, default=360, help='Max image height')
480
+
481
+ # Misc
482
+ parser.add_argument('--seed', type=int, default=42, help='Random seed')
483
+
484
+ args = parser.parse_args()
485
+
486
+ # Set paths
487
+ args.log_dir = os.path.join(args.log_dir, args.experiment_name)
488
+ args.output_dir = os.path.join(args.output_dir, args.experiment_name)
489
+ if args.run_name:
490
+ args.output_dir = os.path.join(args.output_dir, args.run_name)
491
+
492
+ os.makedirs(args.log_dir, exist_ok=True)
493
+ os.makedirs(args.output_dir, exist_ok=True)
494
+
495
+ set_seed(args.seed)
496
+ train(args)
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
+ )
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/agent/helpers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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)
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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